org.apache.synapse.SynapseException Java Examples

The following examples show how to use org.apache.synapse.SynapseException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApplicationThrottleControllerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: ESBIntegrationTest.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #3
Source File: WebsocketEndpointManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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;
    }
 
Example #4
Source File: WebsocketEndpointManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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;

    }
 
Example #5
Source File: SecretCipherHander.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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());
		}
	}
 
Example #6
Source File: FileSecretRepository.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: HL7EndpointManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: VFSProcessor.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #9
Source File: RabbitMQListener.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: RabbitMQInjectHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: MqttClientManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #12
Source File: KAFKAPollingConsumer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #13
Source File: CsvValidatorMediator.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #14
Source File: ApplicationThrottleControllerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: ApplicationThrottleControllerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #17
Source File: CsvValidatorMediator.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #18
Source File: ServiceBusUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #19
Source File: ConfigurationLoader.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
 
Example #20
Source File: SimpleKafkaMessageListener.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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");
}
 
Example #21
Source File: SimpleKafkaMessageListener.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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;
    }
 
Example #22
Source File: KAFKAPollingConsumer.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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(","));
    }
}
 
Example #23
Source File: APIResource.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the message by consuming the input stream.
 *
 * @param synCtx the Synapse Message Context
 */
public final void buildMessage(MessageContext synCtx) {
    try {
        RelayUtils.buildMessage(((Axis2MessageContext) synCtx).getAxis2MessageContext(), false);
    } catch (Exception e) {
        throw new SynapseException("Error while building the message. " + e.getMessage(), e);
    }
}
 
Example #24
Source File: KAFKAMessageListener.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Create the connection with the zookeeper to consume the messages
 */
public boolean createKafkaConsumerConnector() throws Exception {

    log.debug("Create the connection and start to consume the streams");
    boolean isCreated;
    try {
        if (consumerConnector == null) {
            log.info("Creating Kafka Consumer Connector...");

            //set default consumer timeout to 3000ms if it is not set by the user
            if (!kafkaProperties.containsKey(KAFKAConstants.CONSUMER_TIMEOUT)) {
                kafkaProperties.put(KAFKAConstants.CONSUMER_TIMEOUT, "3000");
            }
            consumerConnector = Consumer.createJavaConsumerConnector(new ConsumerConfig(kafkaProperties));
            log.info("Kafka Consumer Connector is created");
            start();
        }
        isCreated = true;
    } catch (ZkTimeoutException toe) {
        log.error(" Error in Creating Kafka Consumer Connector | ZkTimeout" + toe.getMessage());
        throw new SynapseException(" Error in Creating Kafka Consumer Connector| ZkTimeout");

    } catch (Exception e) {
        log.error(" Error in Creating Kafka Consumer Connector." + e.getMessage(), e);
        throw new SynapseException(" Error in Creating Kafka Consumer Connector ", e);
    }
    return isCreated;
}
 
Example #25
Source File: ApplicationThrottleControllerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhenThrottlingPolicyResourceContentRetrievalFailed()
        throws UserStoreException, RegistryException {
    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.doThrow(new RegistryException("Error while retrieving resource content")).when
            (throttlingPolicyResource).getContent();
    ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder,
            applicationId, THROTTLE_POLICY_KEY);
}
 
Example #26
Source File: SecureVaultUtils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * 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()));
}
 
Example #27
Source File: ConfigurationLoader.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private static InternalAPI createApi(String classFQName) {

        try {
            Object obj = Class.forName(classFQName).newInstance();
            if (obj instanceof InternalAPI) {
                return (InternalAPI) obj;
            } else {
                throw new SynapseException(
                        "Error creating Internal InternalAPI. The InternalAPI should be of type InternalAPI");
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new SynapseException("Error creating Internal InternalAPI for class name : " + classFQName, e);
        }
    }
 
Example #28
Source File: ApplicationThrottleControllerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhenThrottlingPolicyResourceRetrievalFailed() throws
        UserStoreException, RegistryException {
    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.doThrow(new RegistryException("Error while fetching resource ")).when(registry).get(RESOURCE_PATH);
    ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder, applicationId,
            THROTTLE_POLICY_KEY);
}
 
Example #29
Source File: ApplicationThrottleControllerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test(expected = SynapseException.class)
public void testCreatingThrottleContextThrowsSynapseExceptionWhenThrottlingPolicyResourceDoesNotExists() throws
        UserStoreException, RegistryException {
    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(false);
    ApplicationThrottleController.getApplicationThrottleContext(messageContext, throttleDataHolder, applicationId,
            THROTTLE_POLICY_KEY);
}
 
Example #30
Source File: APIThrottleHandlerTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test(expected = SynapseException.class)
public void testInitThrottlingThrowsSynapseExceptionWhenThrottlingPolicyDefinitionUnSpecified() {
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    messageContext.getConfiguration().getLocalRegistry().put(THROTTLE_POLICY_KEY, new Object());
    messageContext.setProperty(RESPONSE, "false");
    apiThrottleHandler.handleRequest(messageContext);
}