Java源码示例:org.apache.synapse.SynapseException

示例1
/**
 * This method enables the HTTP wire logs in log4j2 properties file.
 *
 * @param logLevel - The log-level of synapse-transport-http-wire logger
 */
public void configureHTTPWireLogs(String logLevel) {
    if (!isManagementApiAvailable) {
        Awaitility.await().pollInterval(50, TimeUnit.MILLISECONDS).atMost(DEFAULT_TIMEOUT, TimeUnit.SECONDS).
                until(isManagementApiAvailable());
    }
    try {
        SimpleHttpClient client = new SimpleHttpClient();
        Map<String, String> headers = new HashMap<>();
        headers.put("Accept", "application/json");

        String endpoint = "https://" + hostName + ":" + (DEFAULT_INTERNAL_API_HTTPS_PORT + portOffset) + "/management/"
                + "logging";

        JSONObject payload = new JSONObject();
        payload.put("loggerName", "synapse-transport-http-wire");
        payload.put("loggingLevel", logLevel);

        client.doPatch(endpoint, headers, payload.toString(), "application/json");
    } catch (IOException e) {
        throw new SynapseException("Error updating the log-level of synapse-transport-http-wire logger", e);
    }
}
 
示例2
/**
 * Throw Synapse Exception for any exception in class mediator
 * so that the fault handler will be invoked
 *
 * @param ERROR_CODE
 * @param ERROR_MESSAGE
 * @param ERROR_DETAIL
 * @param context
 */
public static void handle(String ERROR_CODE, String ERROR_MESSAGE, String ERROR_DETAIL, MessageContext context) {

    int array[] = {20, 20, 40};
    int total = 0;
    try {
        for (int i = 5; i >= 0; i--) {
            total += array[i];
        }
    } catch (Exception e) {
        context.setProperty(ERROR_CODE, "AB005");
        context.setProperty(ERROR_MESSAGE, "Error Message from class CsvValidatorMediator");
        context.setProperty(ERROR_DETAIL, "Error Details from class");

        String messageContextErrorCode = (String) context.getProperty(ERROR_CODE);
        String messageContextErrorMessage = (String) context.getProperty(ERROR_MESSAGE);
        String messageContextErrorDetail = (String) context.getProperty(ERROR_DETAIL);
        String separator = "?";

        String concatenatedMessage = (messageContextErrorCode + separator + messageContextErrorMessage + separator + messageContextErrorDetail);
        throw new SynapseException(concatenatedMessage);
    }
}
 
示例3
public String getSecret(String alias, SecretSrcData secretSrcData) {

		if (VaultType.DOCKER.equals(secretSrcData.getVaultType()) || VaultType.FILE.equals(secretSrcData.getVaultType())) {
			String resolvedAlias = secretSrcData.getSecretRoot() + alias;
			if (secretSrcData.isEncrypted()) {
				return fileSecretRepository.getSecret(resolvedAlias);
			}
			return fileSecretRepository.getPlainTextSecret(resolvedAlias);
		} else if (VaultType.ENV.equals(secretSrcData.getVaultType())) {
			if (secretSrcData.isEncrypted()) {
				return environmentSecretRepository.getSecret(alias);
			}
			return environmentSecretRepository.getPlainTextSecret(alias);
		} else if (VaultType.REG.equals(secretSrcData.getVaultType())) {
			// For registry type we only support plain text
			return parentRepository.getSecret(alias);
		} else {
			// Will never reach here unless customized
			throw new SynapseException("Unknown secret type : " + secretSrcData.getVaultType().toString());
		}
	}
 
示例4
/**
 * Function to retrieve plain text secret located in the secret file
 * @param alias
 * @return
 */
public String getPlainTextSecret(String alias) {
    // Read from file
    // At this point alias must represent the file path
    try {
        String plainText = readFile(alias);
        if (plainText == null || plainText.isEmpty()) {
            throw new SynapseException("Plain text secret value has not been set for alias "+ alias);
        }
        return plainText.trim();
    } catch (IOException e) {
        handleException("Error occurred while reading file resource : " + alias, e);
    }
    // Will not reach here
    return null;
}
 
示例5
public boolean startEndpoint(int port, String name, InboundProcessorParams params) {

        String epName = dataStore.getListeningEndpointName(port, SUPER_TENANT_DOMAIN_NAME);
        if (epName != null) {
            if (epName.equalsIgnoreCase(name)) {
                log.info(epName + " Endpoint is already started in port : " + port);
            } else {
                String msg = "Another endpoint named : " + epName + " is currently using this port: " + port;
                log.warn(msg);
                throw new SynapseException(msg);
            }
        } else {
            dataStore.registerListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME, InboundWebsocketConstants.WS, name,
                                                params);
            boolean start = startListener(port, name, params);

            if (start) {
                //do nothing
            } else {
                dataStore.unregisterListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME);
                return false;
            }
        }
        return true;

    }
 
示例6
public boolean startSSLEndpoint(int port, String name, InboundProcessorParams params) {

        String epName = dataStore.getListeningEndpointName(port, SUPER_TENANT_DOMAIN_NAME);

        if (epName != null) {
            if (epName.equalsIgnoreCase(name)) {
                log.info(epName + " Endpoint is already started in port : " + port);
            } else {
                String msg = "Another endpoint named : " + epName + " is currently using this port: " + port;
                log.warn(msg);
                throw new SynapseException(msg);
            }
        } else {
            dataStore.registerListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME, InboundWebsocketConstants.WSS, name,
                                                params);
            boolean start = startSSLListener(port, name, params);
            if (start) {
                //do nothing
            } else {
                dataStore.unregisterListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME);
                return false;
            }
        }
        return true;
    }
 
示例7
@Override
public boolean startEndpoint(int port, String name, InboundProcessorParams params) {

    params.getProperties().setProperty(MLLPConstants.HL7_INBOUND_TENANT_DOMAIN, Constants.SUPER_TENANT_DOMAIN_NAME);

    String epName = dataStore.getListeningEndpointName(port, Constants.SUPER_TENANT_DOMAIN_NAME);
    if (epName != null) {
        if (epName.equalsIgnoreCase(name)) {
            log.info(epName + " Endpoint is already started in port : " + port);
        } else {
            String msg = "Another endpoint named : " + epName + " is currently using this port: " + port;
            log.warn(msg);
            throw new SynapseException(msg);
        }
    } else {
        dataStore.registerListeningEndpoint(port, Constants.SUPER_TENANT_DOMAIN_NAME,
                                            InboundRequestProcessorFactoryImpl.Protocols.hl7.toString(), name,
                                            params);
        return startListener(port, name, params);
    }

    return false;
}
 
示例8
public VFSProcessor(InboundProcessorParams params) {
    this.name = params.getName();
    this.vfsProperties = params.getProperties();
    try {
        this.interval = Long.parseLong(vfsProperties.getProperty(PollingConstants.INBOUND_ENDPOINT_INTERVAL));
    } catch (NumberFormatException nfe) {
        throw new SynapseException("Invalid numeric value for interval.", nfe);
    } catch (Exception e) {
        throw new SynapseException("Invalid value for interval.", e);
    }
    this.sequential = true;
    if (vfsProperties.getProperty(PollingConstants.INBOUND_ENDPOINT_SEQUENTIAL) != null) {
        this.sequential = Boolean
                .parseBoolean(vfsProperties.getProperty(PollingConstants.INBOUND_ENDPOINT_SEQUENTIAL));
    }
    this.coordination = true;
    if (vfsProperties.getProperty(PollingConstants.INBOUND_COORDINATION) != null) {
        this.coordination = Boolean.parseBoolean(vfsProperties.getProperty(PollingConstants.INBOUND_COORDINATION));
    }
    this.injectingSeq = params.getInjectingSeq();
    this.onErrorSeq = params.getOnErrorSeq();
    this.synapseEnvironment = params.getSynapseEnvironment();
}
 
示例9
public RabbitMQListener(InboundProcessorParams params) {
    this.name = params.getName();
    this.injectingSeq = params.getInjectingSeq();
    this.onErrorSeq = params.getOnErrorSeq();
    this.synapseEnvironment = params.getSynapseEnvironment();
    this.rabbitmqProperties = params.getProperties();

    this.sequential = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(
            rabbitmqProperties.getProperty(PollingConstants.INBOUND_ENDPOINT_SEQUENTIAL)), true);

    this.coordination = BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBooleanObject(
            rabbitmqProperties.getProperty(PollingConstants.INBOUND_COORDINATION)), true);

    try {
        rabbitMQConnectionFactory = new RabbitMQConnectionFactory(rabbitmqProperties);
    } catch (RabbitMQException e) {
        throw new SynapseException("Error occurred while initializing the connection factory.", e);
    }

    injectHandler = new RabbitMQInjectHandler(injectingSeq, onErrorSeq, sequential, synapseEnvironment);
}
 
示例10
public RabbitMQInjectHandler(String injectingSeq, String onErrorSeq, boolean sequential,
                             SynapseEnvironment synapseEnvironment) {
    this.injectingSeq = injectingSeq;
    if (injectingSeq == null || injectingSeq.equals("")) {
        String msg = "Injecting Sequence name is not specified.";
        log.error(msg);
        throw new SynapseException(msg);
    }
    seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration().getSequence(injectingSeq);
    if (seq == null) {
        throw new SynapseException("Specified injecting sequence: " + injectingSeq + "is invalid.");
    }
    if (!seq.isInitialized()) {
        seq.init(synapseEnvironment);
    }
    this.onErrorSeq = onErrorSeq;
    this.sequential = sequential;
    this.synapseEnvironment = synapseEnvironment;
}
 
示例11
public MqttAsyncClient getMqttClient(String identifier) {
    if (tenantLoadingFlagMap.containsKey(identifier)) {
        //this is manually tenant loading case should return the client
        return mqttClientMap.get(identifier);
    } else {
        MqttAsyncCallback callback = mqttCallbackMap.get(identifier);
        //this is the case where recreation of same bounded inbound endpoint for server host
        //server port, client id
        String msg = "Client ID: " + callback.getMqttConnectionConsumer().getMqttAsyncClient().getClientId()
                + " Server Host: " + callback.getMqttConnectionConsumer().getMqttConnectionFactory().getServerHost()
                + " Server Port: " + callback.getMqttConnectionConsumer().getMqttConnectionFactory().getServerPort()
                + " is bound to existing MQTT Inbound Endpoint.";
        log.error(msg);
        throw new SynapseException(msg);
    }
}
 
示例12
/**
 * Initialize the kafka properties and the polling interval
 */
public KAFKAPollingConsumer(Properties kafkaProperties, long interval, String name) throws Exception {

    this.kafkaProperties = kafkaProperties;
    this.scanInterval = interval;
    this.name = name;
    try {
        if (kafkaProperties.getProperty(KAFKAConstants.THREAD_COUNT) == null || kafkaProperties
                .getProperty(KAFKAConstants.THREAD_COUNT).equals("")
                || Integer.parseInt(kafkaProperties.getProperty(KAFKAConstants.THREAD_COUNT)) <= 0) {
            this.threadCount = 1;
        } else {
            this.threadCount = Integer.parseInt(kafkaProperties.getProperty(KAFKAConstants.THREAD_COUNT));
        }
    } catch (NumberFormatException nfe) {
        log.error("Invalid numeric value for thread count." + nfe.getMessage(), nfe);
        throw new SynapseException("Invalid numeric value for thread count.", nfe);
    }
    if (kafkaProperties.getProperty(KAFKAConstants.TOPICS) != null) {
        this.topics = Arrays.asList(kafkaProperties.getProperty(KAFKAConstants.TOPICS).split(","));
    }
}
 
示例13
/**
 * Start the listener to listen when new messages come to the esb,the listener can be high level or low level.
 */
public void startsMessageListener() throws Exception {

    log.debug("Create the Kafka message listener");
    if (messageListener == null) {
        //Start a high level listener
        try {
            if (kafkaProperties.getProperty(KAFKAConstants.CONSUMER_TYPE) == null || kafkaProperties
                    .getProperty(KAFKAConstants.CONSUMER_TYPE).isEmpty() || kafkaProperties
                    .getProperty(KAFKAConstants.CONSUMER_TYPE)
                    .equalsIgnoreCase(AbstractKafkaMessageListener.CONSUMER_TYPE.HIGHLEVEL.getName())) {
                messageListener = new KAFKAMessageListener(threadCount, topics, kafkaProperties, injectHandler);
                //Start a low level listener
            } else if (kafkaProperties.getProperty(KAFKAConstants.CONSUMER_TYPE)
                    .equalsIgnoreCase(AbstractKafkaMessageListener.CONSUMER_TYPE.SIMPLE.getName())) {
                messageListener = new SimpleKafkaMessageListener(kafkaProperties, injectHandler);
            }
        } catch (Exception e) {
            log.error("The consumer type should be high level or simple." + e.getMessage(), e);
            throw new SynapseException("The consumer type should be high level or simple", e);
        }
    }
}
 
示例14
public boolean run() throws Exception {

        if (init) {
            return init;
        }
        // find the meta data about the topic and partition we are interested in
        PartitionMetadata metadata = findLeader(seedBrokers, port, topic, partition);
        if (metadata == null) {
            throw new SynapseException("Can't find metadata for Topic and Partition. Exiting");
        }
        if (metadata.leader() == null) {
            throw new SynapseException("Can't find Leader for Topic and Partition. Exiting");
        }
        this.leadBroker = metadata.leader().host();
        this.clientName = "Client_" + topic + "_" + partition;

        this.consumer = new SimpleConsumer(leadBroker, port, KAFKAConstants.BUFFER_SIZE, KAFKAConstants.SO_TIMEOUT,
                                           clientName);
        this.readOffset = getLastOffset(consumer, topic, partition, kafka.api.OffsetRequest.EarliestTime(), clientName);
        init = true;

        return init;
    }
 
示例15
private String findNewLeader(String oldLeader, String topic, int partition, int port) throws Exception {
    for (int i = 0; i < 3; i++) {
        boolean goToSleep = false;
        PartitionMetadata metadata = findLeader(replicaBrokers, port, topic, partition);
        if (metadata == null) {
            goToSleep = true;
        } else if (metadata.leader() == null) {
            goToSleep = true;
        } else if (oldLeader.equalsIgnoreCase(metadata.leader().host()) && i == 0) {
            goToSleep = true;
        } else {
            return metadata.leader().host();
        }
        if (goToSleep) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
            }
        }
    }
    throw new SynapseException("Unable to find new leader after Broker failure. Exiting");
}
 
示例16
private static InternalAPIHandler createHandler(String classFQName, String context, List<String> resources) {

        try {
            Constructor c = Class.forName(classFQName).getConstructor(String.class);
            Object obj = c.newInstance(context);
            if (obj instanceof InternalAPIHandler) {
                InternalAPIHandler internalAPIHandler = (InternalAPIHandler) obj;
                internalAPIHandler.setResources(resources);
                return internalAPIHandler;
            } else {
                throw new SynapseException("Error creating Internal InternalAPIHandler. "
                                                   + "The InternalAPIHandler should be of type InternalAPIHandler");
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException
                | InvocationTargetException e) {
            throw new SynapseException("Error creating Internal InternalAPIHandler for class name : " + classFQName, e);
        }
    }
 
示例17
public static String getSynapseConfigAbsPath(ServerContextInformation contextInformation) {
    String carbonHome = MicroIntegratorBaseUtils.getCarbonHome();
    ServerConfigurationInformation configInfo = getSynapseServerConfigInfo(contextInformation);
    if (configInfo == null) {
        String msg = "Unable to obtain ESB server configuration information";
        log.warn(msg);
        throw new SynapseException(msg);
    }

    File synapseConfigFile = new File(configInfo.getSynapseXMLLocation());
    String synapseConfigPath;
    if (synapseConfigFile.isAbsolute()) {
        synapseConfigPath = synapseConfigFile.getAbsolutePath();
    } else {
        synapseConfigPath = new File(carbonHome.trim(),
                configInfo.getSynapseXMLLocation()).getAbsolutePath();
    }
    return synapseConfigPath;
}
 
示例18
/**
 * Throw Synapse Exception for any exception in class mediator
 * so that the fault handler will be invoked
 *
 * @param ERROR_CODE
 * @param ERROR_MESSAGE
 * @param ERROR_DETAIL
 * @param context
 */
public static void handle(String ERROR_CODE, String ERROR_MESSAGE, String ERROR_DETAIL, MessageContext context) {

    int array[] = {20, 20, 40};
    int total = 0;
    try {
        for (int i = 5; i >= 0; i--) {
            total += array[i];
        }
    } catch (Exception e) {
        context.setProperty(ERROR_CODE, "AB005");
        context.setProperty(ERROR_MESSAGE, "Error Message from class CsvValidatorMediator");
        context.setProperty(ERROR_DETAIL, "Error Details from class");

        String messageContextErrorCode = (String) context.getProperty(ERROR_CODE);
        String messageContextErrorMessage = (String) context.getProperty(ERROR_MESSAGE);
        String messageContextErrorDetail = (String) context.getProperty(ERROR_DETAIL);
        String separator = "?";

        String concatenatedMessage = (messageContextErrorCode + separator + messageContextErrorMessage + separator + messageContextErrorDetail);
        throw new SynapseException(concatenatedMessage);
    }
}
 
示例19
@Test(expected = SynapseException.class)
public void testMsgFailWhenUnsupportedThrottleTypeProvided() throws XMLStreamException,
        ThrottleException {
    //Set concurrency count to be 100
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "INVALID", IP, 0, 60000,
            "true"),THROTTLE_POLICY_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    apiThrottleHandler.handleRequest(messageContext);
}
 
示例20
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhenThrottlingPolicyFailedDueToOMException()
        throws UserStoreException, RegistryException, XMLStreamException {
    Mockito.when(throttleDataHolder.getThrottleContext(applicationId)).thenReturn(null);
    PowerMockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(tenantID)).thenReturn(registry);
    PowerMockito.when(registry.resourceExists(RESOURCE_PATH)).thenReturn(true);
    PowerMockito.when(registry.get(RESOURCE_PATH)).thenReturn(throttlingPolicyResource);
    PowerMockito.when(throttlingPolicyResource.getContent()).thenReturn(THROTTLING_POLICY_DEFINITION.getBytes());
    PowerMockito.mockStatic(XMLInputFactory.class);
    XMLInputFactory factory = Mockito.mock(XMLInputFactory.class);
    PowerMockito.when(XMLInputFactory.newInstance()).thenReturn(factory);
    PowerMockito.doThrow(new OMException()).when(factory).createXMLStreamReader((ByteArrayInputStream)
            Mockito.anyObject());
    ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder,
            applicationId, THROTTLE_POLICY_KEY);
}
 
示例21
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhenNonXMLThrottlingPolicyContentTypeIsTextPlain()
        throws UserStoreException, RegistryException, XMLStreamException {
    Mockito.when(throttleDataHolder.getThrottleContext(applicationId)).thenReturn(null);
    PowerMockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(tenantID)).thenReturn(registry);
    PowerMockito.when(registry.resourceExists(RESOURCE_PATH)).thenReturn(true);
    PowerMockito.when(registry.get(RESOURCE_PATH)).thenReturn(throttlingPolicyResource);
    PowerMockito.when(throttlingPolicyResource.getContent()).thenReturn(THROTTLING_POLICY_DEFINITION.getBytes());
    PowerMockito.mockStatic(XMLInputFactory.class);
    XMLInputFactory factory = Mockito.mock(XMLInputFactory.class);
    PowerMockito.when(XMLInputFactory.newInstance()).thenReturn(factory);
    PowerMockito.doThrow(new XMLStreamException()).when(factory).createXMLStreamReader((ByteArrayInputStream)
            Mockito.anyObject());
    PowerMockito.when(throttlingPolicyResource.getMediaType()).thenReturn("text/plain");
    ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder,
            applicationId, THROTTLE_POLICY_KEY);
}
 
示例22
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhileProcessingNonXMLThrottlingPolicyContent()
        throws UserStoreException, RegistryException, XMLStreamException {
    Mockito.when(throttleDataHolder.getThrottleContext(applicationId)).thenReturn(null);
    PowerMockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantID);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(tenantID)).thenReturn(registry);
    PowerMockito.when(registry.resourceExists(RESOURCE_PATH)).thenReturn(true);
    PowerMockito.when(registry.get(RESOURCE_PATH)).thenReturn(throttlingPolicyResource);
    PowerMockito.when(throttlingPolicyResource.getContent()).thenReturn("\\xc3\\x28".getBytes());
    PowerMockito.mockStatic(XMLInputFactory.class);
    XMLInputFactory factory = Mockito.mock(XMLInputFactory.class);
    PowerMockito.when(XMLInputFactory.newInstance()).thenReturn(factory);
    PowerMockito.doThrow(new XMLStreamException()).when(factory).createXMLStreamReader((ByteArrayInputStream)
            Mockito.anyObject());
    PowerMockito.mockStatic(OMAbstractFactory.class);
    OMFactory omFactory = Mockito.mock(OMFactory.class);
    PowerMockito.when(OMAbstractFactory.getOMFactory()).thenReturn(omFactory);
    Mockito.doThrow(IOException.class).when(omFactory).createOMText((DataHandler) Mockito.anyObject(), Mockito
            .anyBoolean());
    ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder,
            applicationId, THROTTLE_POLICY_KEY);
}
 
示例23
private void handleException(String msg, Exception e, MessageContext msgContext) {
    log.error(msg, e);
    if (msgContext.getServiceLog() != null) {
        msgContext.getServiceLog().error(msg, e);
    }
    throw new SynapseException(msg, e);
}
 
示例24
/**
 * {@inheritDoc}
 */
public void init(SynapseEnvironment synEnv) {
    try {
        cfgCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(clientRepository != null
                ? clientRepository : DEFAULT_CLIENT_REPO, axis2xml != null ? axis2xml : DEFAULT_AXIS2_XML);
    } catch (AxisFault e) {
        String msg = "Error initializing OAuth mediator : " + e.getMessage();
        throw new SynapseException(msg, e);
    }
}
 
示例25
/**
 * Checks if the message contains Authorization header or query strings
 *
 * @param synCtx
 * @return
 */
private boolean validateRequest(MessageContext synCtx) {

    boolean isOauth2 = false;
    String accessToken = null;

    org.apache.axis2.context.MessageContext msgContext = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    Map headersMap =
            (Map) msgContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String authHeader = (String) headersMap.get("Authorization");

    // if we can't find the OAuth header, prompt error
    if (authHeader == null) {
        throw new SynapseException("Not a valid OAuth Request");
    }

    // checking for OAuth 2.0 params
    if (authHeader != null && authHeader.startsWith(OAuthConstants.BEARER)) {
        isOauth2 = true;
        // Do not need do validate an empty OAuth2 token
        if (authHeader.length() > OAuthConstants.BEARER.length()) {
            accessToken = authHeader.substring(OAuthConstants.BEARER.length()).trim();
        }
    }

    // not a valid OAuth 2.0 request
    if (isOauth2 == true && accessToken == null) {
        // Throw a correct descriptive message.
        throw new SynapseException("Invalid or empty OAuth 2.0 token");
    }

    return isOauth2;
}
 
示例26
/**
 * {@inheritDoc}
 */
public Mediator createSpecificMediator(OMElement element, Properties properties) {
    if (!ELEMENT_OAUTH.equals(element.getQName())) {
        handleException("Unable to create the OAuth mediator. "
                + "Unexpected element as the OAuth mediator configuration");
    }

    OAuthMediator mediator = null;
    OMAttribute remoteServiceUrl = null;
    OMAttribute username = null;
    OMAttribute password = null;

    mediator = new OAuthMediator();

    remoteServiceUrl = element.getAttribute(ATTR_NAME_SERVICE_EPR);
    if (remoteServiceUrl != null && remoteServiceUrl.getAttributeValue() != null) {
        mediator.setRemoteServiceUrl(remoteServiceUrl.getAttributeValue());
    } else {
        throw new SynapseException(
                "The 'remoteServiceUrl' attribute is required for the OAuth mediator");
    }
    username = element.getAttribute(ATTR_NAME_USERNAME);
    if (username != null && username.getAttributeValue() != null) {
        mediator.setUsername(username.getAttributeValue());
    } else {
        throw new SynapseException("The 'username' attribute is required for the OAuth mediator");
    }
    password = element.getAttribute(ATTR_NAME_PASSWORD);
    if (password != null && password.getAttributeValue() != null) {
        mediator.setPassword(password.getAttributeValue());
    } else {
        throw new SynapseException("The 'password' attribute is required for the OAuth mediator");
    }

    addAllCommentChildrenToList(element, mediator.getCommentsList());

    return mediator;
}
 
示例27
/**
 * Returns the decrypted value for a secret.
 *
 * @param encryptedValue encrypted password text
 */
public static String decryptSecret(String encryptedValue) {
    DecryptionProvider decyptProvider = CipherInitializer.getInstance().getDecryptionProvider();
    if (encryptedValue == null || encryptedValue.isEmpty()) {
      return encryptedValue;
    }
    if (decyptProvider == null) {
        // This cannot happen unless someone mess with OSGI references
        throw new SynapseException("Secret repository has not been initialized.");
    }
    return new String(decyptProvider.decrypt(encryptedValue.trim().getBytes()));
}
 
示例28
@Override
public void init() {
    if (isPortUsedByAnotherApplication(port)) {
        log.warn("Port " + port + "used by inbound endpoint " + name + " is already used by another application "
                         + "hence undeploying inbound endpoint");
        throw new SynapseException("Port " + port + " used by inbound endpoint " + name + " is already used by "
                                           + "another application.");
    } else {
        HTTPEndpointManager.getInstance().startSSLEndpoint(port, name, sslConfiguration, processorParams);
    }

}
 
示例29
/**
 * Start Http Inbound endpoint in a particular port
 *
 * @param port   port
 * @param name   endpoint name
 * @param params inbound endpoint params
 */
public boolean startEndpoint(int port, String name, InboundProcessorParams params) {

    InboundHttpConfiguration config = buildConfiguration(port, name, params);

    String epName = dataStore.getListeningEndpointName(port, SUPER_TENANT_DOMAIN_NAME);
    if (epName != null) {
        if (epName.equalsIgnoreCase(name)) {
            applyConfiguration(config, SUPER_TENANT_DOMAIN_NAME, port);
            log.info(epName + " Endpoint is already started in port : " + port);
        } else {
            String msg = "Another endpoint named : " + epName + " is currently using this port: " + port;
            log.warn(msg);
            throw new SynapseException(msg);
        }
    } else {
        dataStore
                .registerListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME, InboundHttpConstants.HTTP, name, params);
        boolean start = startListener(port, name, params);

        if (start) {
            applyConfiguration(config, SUPER_TENANT_DOMAIN_NAME, port);
        } else {
            dataStore.unregisterListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME);
            return false;
        }
    }
    return true;

}
 
示例30
/**
 * Start Https Inbound endpoint in a particular port
 *
 * @param port port
 * @param name endpoint name
 */
public boolean startSSLEndpoint(int port, String name, SSLConfiguration sslConfiguration,
                                InboundProcessorParams params) {

    InboundHttpConfiguration config = buildConfiguration(port, name, params);

    String epName = dataStore.getListeningEndpointName(port, SUPER_TENANT_DOMAIN_NAME);

    if (PassThroughInboundEndpointHandler.isEndpointRunning(port)) {
        if (epName != null && epName.equalsIgnoreCase(name)) {
            applyConfiguration(config, SUPER_TENANT_DOMAIN_NAME, port);
            log.info(epName + " Endpoint is already started in port : " + port);
        } else {
            String msg =
                    "Cannot Start Endpoint " + name + " Already occupied port " + port + " by another Endpoint ";
            log.warn(msg);
            throw new SynapseException(msg);
        }
    } else {
        if (epName != null && epName.equalsIgnoreCase(name)) {
            log.info(epName + " Endpoint is already registered in registry");
        } else {
            dataStore.registerSSLListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME, InboundHttpConstants.HTTPS, name,
                                                   sslConfiguration, params);
        }
        boolean start = startSSLListener(port, name, sslConfiguration, params);
        if (start) {
            applyConfiguration(config, SUPER_TENANT_DOMAIN_NAME, port);
        } else {
            dataStore.unregisterListeningEndpoint(port, SUPER_TENANT_DOMAIN_NAME);
            return false;
        }
    }
    return true;
}