Java Code Examples for org.apache.camel.Message#getHeader()

The following examples show how to use org.apache.camel.Message#getHeader() . 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: SplitReaggregateSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
private void assertBooksByCategory(Exchange exchange) {
    Message in = exchange.getIn();
    @SuppressWarnings("unchecked")
    Set<String> books = Collections.checkedSet(in.getBody(Set.class), String.class);
    String category = in.getHeader("category", String.class);
    switch (category) {
        case "Tech":
            assertTrue(books.containsAll(Collections.singletonList("Apache Camel Developer's Cookbook")));
            break;
        case "Cooking":
            assertTrue(books.containsAll(Arrays.asList("Camel Cookbook",
                "Double decadence with extra cream", "Cooking with Butter")));
            break;
        default:
            fail();
            break;
    }
}
 
Example 2
Source File: SqlConnectorCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private boolean isRecordsFound(Message in) {

        switch (statementType) {

            case SELECT:
                Integer rowCount = (Integer) in.getHeader(CamelSqlConstants.SQL_ROW_COUNT);
                if (rowCount.intValue() > 0) {
                    return true;
                }
                break;

            case UPDATE:
            case DELETE:
            case INSERT:
                Integer updateCount = (Integer) in.getHeader(CamelSqlConstants.SQL_UPDATE_COUNT);
                if (updateCount.intValue() > 0) {
                    return true;
                }
                break;

        }
        return false;
    }
 
Example 3
Source File: ComplicatedProcessor.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    final String something = "SOMETHING";
    Message in = exchange.getIn();
    String action = in.getHeader("action", String.class);
    if ((action == null) || (action.isEmpty())) {
        in.setHeader("actionTaken", false);
    } else {
        in.setHeader("actionTaken", true);
        String body = in.getBody(String.class);
        if (action.equals("append")) {
            in.setBody(body + " " + something);
        } else if (action.equals("prepend")) {
            in.setBody(something + " " + body);
        } else {
            throw new IllegalArgumentException(
                "Unrecognized action requested: [" + action + "]");
        }
    }
}
 
Example 4
Source File: MyProcessor.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    String result = "Unknown language";

    final Message inMessage = exchange.getIn();
    final String body = inMessage.getBody(String.class);
    final String language = inMessage.getHeader("language", String.class);

    if ("en".equals(language)) {
        result = "Hello " + body;
    } else if ("fr".equals(language)) {
        result = "Bonjour " + body;
    }

    inMessage.setBody(result);
}
 
Example 5
Source File: ManagementBusInvocationPluginScript.java    From container with Apache License 2.0 5 votes vote down vote up
private TNodeTemplate getNodeTemplate(Message message, Csar csar, TRelationshipTemplate relationshipTemplate, TServiceTemplate serviceTemplate, String interfaceName, String operationName) throws NotFoundException {
    String nodeTemplateID = message.getHeader(MBHeader.NODETEMPLATEID_STRING.toString(), String.class);
    LOG.debug("NodeTemplateID: {}", nodeTemplateID);
    if (nodeTemplateID == null && relationshipTemplate != null) {
        // backfill the node template from the relationship template
        final TRelationshipType relationshipType = ToscaEngine.resolveRelationshipTypeReference(csar, relationshipTemplate.getType());
        final boolean isBoundToSourceNode = ToscaEngine.isOperationBoundToSourceNode(relationshipType, interfaceName, operationName);
        return isBoundToSourceNode
            ? (TNodeTemplate) relationshipTemplate.getSourceElement().getRef()
            : (TNodeTemplate) relationshipTemplate.getTargetElement().getRef();
    }
    return ToscaEngine.resolveNodeTemplate(serviceTemplate, nodeTemplateID);
}
 
Example 6
Source File: AuditSparqlProcessor.java    From fcrepo-camel-toolbox with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a Camel message to audit event description.
 * @param message Camel message produced by an audit event
 * @param subject RDF subject of the audit description
 */
private static String serializedGraphForMessage(final Message message, final Resource subject) throws IOException {

    // serialize triples
    final ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
    final Model model = createDefaultModel();

    // get info from jms message headers
    @SuppressWarnings("unchecked")
    final List<String> eventType = message.getHeader(FCREPO_EVENT_TYPE, emptyList(), List.class);
    final String dateTime = message.getHeader(FCREPO_DATE_TIME, EMPTY_STRING, String.class);
    @SuppressWarnings("unchecked")
    final List<String> agents = message.getHeader(FCREPO_AGENT, emptyList(), List.class);
    @SuppressWarnings("unchecked")
    final List<String> resourceTypes = message.getHeader(FCREPO_RESOURCE_TYPE, emptyList(), List.class);
    final String identifier = message.getHeader(FCREPO_URI, EMPTY_STRING, String.class);
    final Optional<String> premisType = getAuditEventType(eventType, resourceTypes);

    model.add( model.createStatement(subject, type, INTERNAL_EVENT) );
    model.add( model.createStatement(subject, type, PREMIS_EVENT) );
    model.add( model.createStatement(subject, type, PROV_EVENT) );

    // basic event info
    model.add( model.createStatement(subject, PREMIS_TIME, createTypedLiteral(dateTime, XSDdateTime)) );
    model.add( model.createStatement(subject, PREMIS_OBJ, createResource(identifier)) );

    agents.forEach(agent -> {
        model.add( model.createStatement(subject, PREMIS_AGENT, createTypedLiteral(agent, XSDstring)) );
    });

    premisType.ifPresent(rdfType -> {
        model.add(model.createStatement(subject, PREMIS_TYPE, createResource(rdfType)));
    });

    write(serializedGraph, model, NTRIPLES);
    return serializedGraph.toString("UTF-8");
}
 
Example 7
Source File: RestRouteBuilder.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private void switchDigital(Exchange exchange) {
	Message message = exchange.getMessage();
	Object pinRaw = message.getHeader("pin");
	String stateRaw = message.getBody(String.class);
	int pin = tryParse(String.valueOf(pinRaw)).getOrThrow("Pin %s not parseable", pinRaw);
	boolean state = parseBoolean(stateRaw);
	message.setBody(alpProtocolMessage(DIGITAL_PIN_READ).forPin(pin).withState(state));
}
 
Example 8
Source File: RestRouteBuilder.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private void patch(Exchange exchange, ALPProtocolKey startKey, ALPProtocolKey stopKey) {
	Message message = exchange.getMessage();
	Object pinRaw = message.getHeader("pin");
	String stateRaw = message.getBody(String.class);

	String[] split = stateRaw.split("=");
	checkState(split.length == 2, "Could not split %s by =", stateRaw);
	checkState(split[0].equalsIgnoreCase("listen"), "Expected listen=${state} but was %s", stateRaw);

	int pin = tryParse(String.valueOf(pinRaw)).getOrThrow("Pin %s not parseable", pinRaw);
	boolean state = parseBoolean(split[1]);
	message.setBody(alpProtocolMessage(state ? startKey : stopKey).forPin(pin).withoutValue());
}
 
Example 9
Source File: RequestReceiver.java    From container with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the request is directed to the local OpenTOSCA Container / Management Bus. This is the case if the
 * {@link MBHeader#DEPLOYMENTLOCATION_STRING} header field equals the local host name.
 *
 * @param message the request message
 * @return <tt>true</tt> if the request is directed to this Management Bus, <tt>false</tt>
 * otherwise
 */
private boolean isDestinationLocal(final Message message) {

    final String deploymentLocation =
        message.getHeader(MBHeader.DEPLOYMENTLOCATION_STRING.toString(), String.class);
    LOG.debug("Deplyoment location header: {}", deploymentLocation);

    return deploymentLocation != null && deploymentLocation.equals(Settings.OPENTOSCA_CONTAINER_HOSTNAME);
}
 
Example 10
Source File: ResponseSoapPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected void convertMessage(Message in) {
    try {
        // get SOAP QNames from CxfPayload headers
        final SoapMessage soapMessage = in.getHeader("CamelCxfMessage", SoapMessage.class);
        final SoapVersion soapVersion = soapMessage.getVersion();

        // get CxfPayload body
        final CxfPayload<?> cxfPayload = in.getMandatoryBody(CxfPayload.class);
        final List<?> headers = cxfPayload.getHeaders();
        final List<Source> body = cxfPayload.getBodySources();

        final OutputStream outputStream = newOutputStream(in, cxfPayload);
        final XMLStreamWriter writer = newXmlStreamWriter(outputStream);

        // serialize headers and body into an envelope
        writeStartEnvelopeAndHeaders(soapVersion, headers, writer);
        if (body != null && !body.isEmpty()) {
            writeBody(writer, body, soapVersion);
        }
        writer.writeEndDocument();

        final InputStream inputStream = getInputStream(outputStream, writer);

        // set the input stream as the Camel message body
        in.setBody(inputStream);

    } catch (InvalidPayloadException | XMLStreamException | IOException e) {
        throw new RuntimeCamelException("Error parsing CXF Payload: " + e.getMessage(), e);
    }
}
 
Example 11
Source File: BoxUploadCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static String retrieveFilenameFromHeader(Message in, String ...keys) {
    String value = null;
    for (String key: keys) {
        value = in.getHeader(key, String.class);
        if (value != null) {
            break;
        }
    }
    return value;
}
 
Example 12
Source File: TracingLogListener.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
    final Message in = exchange.getIn();
    Span span = in.getHeader(IntegrationLoggingConstants.STEP_SPAN, Span.class);
    if (span == null) {
        span = tracer.activeSpan();
    }
    if (span != null) {
        span.log(message);
    }
    return message;
}
 
Example 13
Source File: IntegrationLoggingListener.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
    if (tracker == null) {
        return message;
    }

    final String activityId = ActivityTracker.getActivityId(exchange);
    if (activityId != null) {
        final Marker marker = camelLogger.getMarker();
        final String step = marker != null ? marker.getName() : "null";

        final Message in = exchange.getIn();
        String stepTrackerId = in.getHeader(IntegrationLoggingConstants.STEP_TRACKER_ID, String.class);
        if( stepTrackerId == null ) {
            stepTrackerId = KeyGenerator.createKey();
        }

        tracker.track(
            "exchange", activityId,
            "step", step,
            "id", stepTrackerId,
            "message", message
        );
    }

    return message;
}
 
Example 14
Source File: ActivityTracker.java    From syndesis with Apache License 2.0 5 votes vote down vote up
static void initializeTracking(Exchange exchange) {
    if (ObjectHelper.isEmpty(getActivityId(exchange))) {
        Message in = exchange.getIn();

        if (in != null && in.getHeader(IntegrationLoggingConstants.ACTIVITY_ID) != null) {
            exchange.setProperty(IntegrationLoggingConstants.ACTIVITY_ID, in.removeHeader(IntegrationLoggingConstants.ACTIVITY_ID));
        } else {
            exchange.setProperty(IntegrationLoggingConstants.ACTIVITY_ID, exchange.getExchangeId());
        }
    }
}
 
Example 15
Source File: OutMessageCaptureProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    final Message message = exchange.hasOut() ? exchange.getOut() : exchange.getIn();
    final String id = message.getHeader(IntegrationLoggingConstants.STEP_ID, String.class);

    if (id != null) {
        Message copy = message.copy();
        Map<String, Message> outMessagesMap = getCapturedMessageMap(exchange);
        if (copy instanceof MessageSupport && copy.getExchange() == null) {
            ((MessageSupport) copy).setExchange(message.getExchange());
        }

        outMessagesMap.put(id, copy);
    }
}
 
Example 16
Source File: RequestReceiver.java    From container with Apache License 2.0 4 votes vote down vote up
/**
     * Deploy the IA that is specified in the incoming exchange by using the Management Bus deployment Plug-ins.
     *
     * @param exchange the exchange containing the needed information as header fields
     */
    public void invokeIADeployment(Exchange exchange) {

        LOG.debug("Received remote operation call for IA deployment.");
        final Message message = exchange.getIn();

        if (!isDestinationLocal(message)) {
            LOG.debug("Request is directed to another OpenTOSCA Container. Ignoring request!");
            return;
        }

        // check whether the request contains the needed header fields to send a response
        final Map<String, Object> headers = getResponseHeaders(message);
        if (Objects.isNull(headers)) {
            LOG.error("Request does not contain all needed header fields to send a response. Aborting operation!");
            return;
        }

        // create IA unique String from given message
        final String identifier = getUniqueSynchronizationString(message);
        if (Objects.isNull(identifier)) {
            LOG.error("Request does not contain all needed header fields to deploy the IA. Aborting operation!");
            return;
        }

        // URI of the deployed IA

        // retrieve needed data from the headers
        final String triggeringContainer = message.getHeader(MBHeader.TRIGGERINGCONTAINER_STRING.toString(), String.class);
        final QName typeImplementationID = message.getHeader(MBHeader.TYPEIMPLEMENTATIONID_QNAME.toString(), QName.class);
        final String implementationArtifactName = message.getHeader(MBHeader.IMPLEMENTATION_ARTIFACT_NAME_STRING.toString(), String.class);
        final URI serviceInstanceID = message.getHeader(MBHeader.SERVICEINSTANCEID_URI.toString(), URI.class);
        final CSARID csarID = message.getHeader(MBHeader.CSARID.toString(), CSARID.class);
        final QName portType = message.getHeader(MBHeader.PORT_TYPE_QNAME.toString(), QName.class);
        final String artifactType = message.getHeader(MBHeader.ARTIFACTTYPEID_STRING.toString(), String.class);
        final Long serviceTemplateInstanceID = Long.parseLong(StringUtils.substringAfterLast(serviceInstanceID.toString(), "/"));

        final String deploymentLocation = Settings.OPENTOSCA_CONTAINER_HOSTNAME;
//    logInformation(triggeringContainer, deploymentLocation, typeImplementationID, implementationArtifactName,
//      csarID, portType, artifactType, serviceTemplateInstanceID);

        URI endpointURI = null;
        // Prevent two threads from trying to deploy the same IA concurrently and avoid the deletion
        // of an IA after successful checking that an IA is already deployed.
        synchronized (ManagementBusServiceImpl.getLockForString(identifier)) {

            LOG.debug("Got lock for operations on the given IA. Checking if IA is already deployed...");

            final List<WSDLEndpoint> endpoints = endpointService.getWSDLEndpointsForNTImplAndIAName(triggeringContainer,
                deploymentLocation,
                typeImplementationID,
                implementationArtifactName);

            if (endpoints != null && endpoints.size() > 0) {

                // This case should not happen, as the 'master' Container sends only one deployment
                // request per IA and intercepts all other deployment actions if there is already an
                // endpoint.
                endpointURI = endpoints.get(0).getURI();

                LOG.warn("IA is already deployed. Storing only one endpoint at the remote side. Endpoint URI: {}",
                    endpointURI);
            } else {
                LOG.debug("IA not yet deployed. Trying to deploy...");

                final IManagementBusDeploymentPluginService deploymentPlugin =
                    pluginRegistry.getDeploymentPluginServices().get(artifactType);

                if (deploymentPlugin != null) {
                    LOG.debug("Deployment plug-in: {}. Deploying IA...", deploymentPlugin.toString());

                    // execute deployment via corresponding plug-in
                    exchange = deploymentPlugin.invokeImplementationArtifactDeployment(exchange);
                    endpointURI = exchange.getIn().getHeader(MBHeader.ENDPOINT_URI.toString(), URI.class);

                    // store new endpoint for the IA
                    final WSDLEndpoint endpoint =
                        new WSDLEndpoint(endpointURI, portType, triggeringContainer, deploymentLocation, new CsarId(csarID),
                            serviceTemplateInstanceID, null, typeImplementationID, implementationArtifactName, new HashMap<>());
                    endpointService.storeWSDLEndpoint(endpoint);
                } else {
                    LOG.error("No matching deployment plug-in found. Aborting deployment!");
                }
            }
        }

        LOG.debug("Sending response message containing endpoint URI: {}", endpointURI);

        // add the endpoint URI as operation result to the headers
        headers.put(MBHeader.ENDPOINT_URI.toString(), endpointURI);

        // create empty reply message and transmit it with the headers
        final CollaborationMessage replyBody = new CollaborationMessage(new KeyValueMap(), null);
        collaborationContext.getProducer().sendBodyAndHeaders("direct:SendMQTT", replyBody, headers);
    }
 
Example 17
Source File: RequestReceiver.java    From container with Apache License 2.0 4 votes vote down vote up
/**
 * Undeploy the IA that is specified in the incoming exchange by using the Management Bus deployment Plug-ins.
 *
 * @param exchange the exchange containing the needed information as header fields
 */
public void invokeIAUndeployment(Exchange exchange) {

    LOG.debug("Received remote operation call for IA undeployment.");
    final Message message = exchange.getIn();

    if (!isDestinationLocal(message)) {
        LOG.debug("Request is directed to another OpenTOSCA Container. Ignoring request!");
        return;
    }

    // check whether the request contains the needed header fields to send a response
    final Map<String, Object> headers = getResponseHeaders(message);
    if (Objects.isNull(headers)) {
        LOG.error("Request does not contain all needed header fields to send a response. Aborting operation!");
        return;
    }

    // create IA unique String from given message
    final String identifier = getUniqueSynchronizationString(message);
    if (Objects.isNull(identifier)) {
        LOG.error("Request does not contain all needed header fields to deploy the IA. Aborting operation!");
        return;
    }

    boolean undeploymentState = false;

    // retrieve needed data from the headers
    final String triggeringContainer = message.getHeader(MBHeader.TRIGGERINGCONTAINER_STRING.toString(), String.class);
    final QName typeImplementationID = message.getHeader(MBHeader.TYPEIMPLEMENTATIONID_QNAME.toString(), QName.class);
    final String implementationArtifactName = message.getHeader(MBHeader.IMPLEMENTATION_ARTIFACT_NAME_STRING.toString(), String.class);
    final String artifactType = message.getHeader(MBHeader.ARTIFACTTYPEID_STRING.toString(), String.class);
    final String deploymentLocation = Settings.OPENTOSCA_CONTAINER_HOSTNAME;

    LOG.debug("Undeployment of IA: Triggering Container: {}, Deployment location: {}, NodeTypeImplementation ID: {}, IA name: {}, Type: {}",
        triggeringContainer, deploymentLocation, typeImplementationID, implementationArtifactName,
        artifactType);

    // Prevent two threads from trying to deploy the same IA concurrently and avoid the deletion
    // of an IA after successful checking that an IA is already deployed.
    synchronized (ManagementBusServiceImpl.getLockForString(identifier)) {

        LOG.debug("Got lock for operations on the given IA. Getting endpoints fot the IA...");

        // get all endpoints for the given parameters
        final List<WSDLEndpoint> endpoints =
            endpointService.getWSDLEndpointsForNTImplAndIAName(triggeringContainer,
                deploymentLocation,
                typeImplementationID,
                implementationArtifactName);

        if (endpoints != null && endpoints.size() > 0) {
            // only one endpoint is stored for remote IAs
            final WSDLEndpoint endpoint = endpoints.get(0);
            endpointService.removeWSDLEndpoint(endpoint);

            final IManagementBusDeploymentPluginService deploymentPlugin = pluginRegistry.getDeploymentPluginServices().get(artifactType);
            if (deploymentPlugin != null) {
                LOG.debug("Undeploying IA...");
                exchange = deploymentPlugin.invokeImplementationArtifactUndeployment(exchange);
                undeploymentState = exchange.getIn().getHeader(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), boolean.class);
            } else {
                LOG.error("No matching plug-in found. Aborting deployment!");
            }
        } else {
            LOG.error("No enpoint found for this IA. Undeployment not possible!");
        }
    }

    LOG.debug("Sending response message containing undeployment state: {}", undeploymentState);

    // add the undeployment state as operation result to the headers
    headers.put(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), undeploymentState);

    // create empty reply message and transmit it with the headers
    final CollaborationMessage replyBody = new CollaborationMessage(new KeyValueMap(), null);
    collaborationContext.getProducer().sendBodyAndHeaders("direct:SendMQTT", replyBody, headers);
}
 
Example 18
Source File: InvocationRequestProcessor.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public void process(final Exchange exchange) throws ParseException, ApplicationBusExternalException, SAXException {

    String nodeTemplateID = null;
    Integer nodeInstanceID = null;
    Integer serviceInstanceID = null;
    String interfaceName = null;
    String operationName = null;
    LinkedHashMap<String, Object> params = null;

    InvocationRequestProcessor.LOG.debug("Processing Invocation request...");

    final Message message = exchange.getIn();

    serviceInstanceID = message.getHeader(Route.SI, Integer.class);
    InvocationRequestProcessor.LOG.debug("ServiceInstanceID: {}", serviceInstanceID);
    exchange.getIn().setHeader(ApplicationBusConstants.SERVICE_INSTANCE_ID_INT.toString(), serviceInstanceID);

    nodeInstanceID = message.getHeader(Route.NI, Integer.class);
    InvocationRequestProcessor.LOG.debug("NodeInstanceID: {}", nodeInstanceID);
    exchange.getIn().setHeader(ApplicationBusConstants.NODE_INSTANCE_ID_INT.toString(), nodeInstanceID);

    nodeTemplateID = message.getHeader(Route.NT, String.class);
    InvocationRequestProcessor.LOG.debug("NodeTemplateID: {}", nodeTemplateID);
    exchange.getIn().setHeader(ApplicationBusConstants.NODE_TEMPLATE_ID.toString(), nodeTemplateID);

    interfaceName = message.getHeader(Route.IN, String.class);
    InvocationRequestProcessor.LOG.debug("Interface: {}", interfaceName);
    exchange.getIn().setHeader(ApplicationBusConstants.INTERFACE_NAME.toString(), interfaceName);

    operationName = message.getHeader(Route.ON, String.class);
    InvocationRequestProcessor.LOG.debug("Operation: {}", operationName);
    exchange.getIn().setHeader(ApplicationBusConstants.OPERATION_NAME.toString(), operationName);

    final Form httpHeaders = (Form) exchange.getIn().getHeader("org.restlet.http.headers");
    final String contentType = httpHeaders.getValues("Content-Type").toString();

    InvocationRequestProcessor.LOG.debug("Content-Type: {}", contentType);

    final String bodyString = message.getBody(String.class);

    if (bodyString != null) {

        if (contentType != null && contentType.equals(MediaType.APPLICATION_JSON.getName())) {

            params = jsonStringToMap(bodyString);
        } else if (contentType != null && contentType.equals(MediaType.APPLICATION_XML.getName())) {

            params = xmlStringToMap(bodyString);
        } else {
            InvocationRequestProcessor.LOG.warn("The request entity media type is not supported. Supported types are {} and {}",
                MediaType.APPLICATION_JSON.getName(),
                MediaType.APPLICATION_XML.getName());
            throw new ApplicationBusExternalException(
                "The request entity media type is not supported. Supported types are "
                    + MediaType.APPLICATION_JSON.getName() + " and " + MediaType.APPLICATION_XML.getName(),
                Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode());
        }
    }

    exchange.getIn().setHeader(ApplicationBusConstants.APPLICATION_BUS_METHOD.toString(),
        ApplicationBusConstants.APPLICATION_BUS_METHOD_INVOKE.toString());

    exchange.getIn().setBody(params);
}
 
Example 19
Source File: ManagementBusDeploymentPluginTomcat.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public Exchange invokeImplementationArtifactUndeployment(final Exchange exchange) {
    LOG.debug("Trying to undeploy IA from Tomcat.");
    final Message message = exchange.getIn();
    // set operation state to false and only change after successful undeployment
    message.setHeader(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), false);
    // get endpoint from header to calculate deployment path
    final URI endpointURI = message.getHeader(MBHeader.ENDPOINT_URI.toString(), URI.class);

    if (endpointURI == null) {
        LOG.error("No endpoint defined. Undeployment not possible!");
        return exchange;
    }

    final String endpoint = endpointURI.toString();
    LOG.debug("Endpoint for undeployment: {}", endpoint);
    // delete Tomcat URL prefix from endpoint
    String deployPath = endpoint.replace(Settings.ENGINE_IA_TOMCAT_URL, "");
    // delete ServiceEndpoint suffix from endpoints
    deployPath = deployPath.substring(0, StringUtils.ordinalIndexOf(deployPath, "/", 4));

    // command to perform deployment on Tomcat from local file
    final String undeploymentURL = Settings.ENGINE_IA_TOMCAT_URL + "/manager/text/undeploy?path=" + deployPath;
    LOG.debug("Undeployment command: {}", undeploymentURL);

    try {
        // perform undeployment request on Tomcat
        final HttpResponse httpResponse = this.httpService.Get(undeploymentURL, Settings.ENGINE_IA_TOMCAT_USERNAME, Settings.ENGINE_IA_TOMCAT_PASSWORD);
        final String response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

        LOG.debug("Tomcat response: {}", response);

        // check if WAR-File was undeployed successfully
        if (response.contains("OK - Undeployed application at context path [" + deployPath + "]")) {
            LOG.debug("IA successfully undeployed from Tomcat!");
            message.setHeader(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), true);
        } else {
            LOG.error("Undeployment not successfully!");
        }
    } catch (final IOException e) {
        LOG.error("IOException occured while undeploying the WAR-File: {}!", e);
    }
    return exchange;
}
 
Example 20
Source File: UndertowWsIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void fireWebSocketChannelEvents() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            final int port = getPort();
            /* sendToAll */
            from("undertow:ws://localhost:" + port + "/app5?fireWebSocketChannelEvents=true") //
                    .to("mock:result5") //
                    .to("undertow:ws://localhost:" + port + "/app5");
        }

    });

    camelctx.start();
    try {

        MockEndpoint result = camelctx.getEndpoint("mock:result5", MockEndpoint.class);
        result.expectedMessageCount(6);

        TestClient wsclient1 = new TestClient("ws://localhost:" + getPort() + "/app5", 2);
        TestClient wsclient2 = new TestClient("ws://localhost:" + getPort() + "/app5", 2);
        wsclient1.connect();
        wsclient2.connect();

        wsclient1.sendTextMessage("Gambas");
        wsclient2.sendTextMessage("Calamares");

        wsclient1.close();
        wsclient2.close();

        result.await(60, TimeUnit.SECONDS);

        final List<Exchange> exchanges = result.getReceivedExchanges();
        final Map<String, List<String>> connections = new HashMap<>();
        for (Exchange exchange : exchanges) {
            final Message in = exchange.getIn();
            final String key = (String) in.getHeader(UndertowConstants.CONNECTION_KEY);
            Assert.assertNotNull(key);
            List<String> messages = connections.get(key);
            if (messages == null) {
                messages = new ArrayList<String>();
                connections.put(key, messages);
            }
            String body = in.getBody(String.class);
            if (body != null) {
                messages.add(body);
            } else {
                messages.add(in.getHeader(UndertowConstants.EVENT_TYPE_ENUM, EventType.class).name());
            }
        }

        final List<String> expected1 = Arrays.asList(EventType.ONOPEN.name(), "Gambas", EventType.ONCLOSE.name());
        final List<String> expected2 = Arrays.asList(EventType.ONOPEN.name(), "Calamares",
                EventType.ONCLOSE.name());

        Assert.assertEquals(2, connections.size());
        final Iterator<List<String>> it = connections.values().iterator();
        final List<String> actual1 = it.next();
        Assert.assertTrue("actual " + actual1, actual1.equals(expected1) || actual1.equals(expected2));
        final List<String> actual2 = it.next();
        Assert.assertTrue("actual " + actual2, actual2.equals(expected1) || actual2.equals(expected2));
    } finally {
        camelctx.close();
    }

}