org.apache.camel.RuntimeCamelException Java Examples

The following examples show how to use org.apache.camel.RuntimeCamelException. 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: ReactiveStreamsRecorder.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public CamelReactiveStreamsService getReactiveStreamsService() {
    synchronized (this.lock) {
        if (getReactiveStreamsEngineConfiguration() == null) {
            ReactiveStreamsEngineConfiguration reactiveStreamsEngineConfiguration = new ReactiveStreamsEngineConfiguration();
            reactiveStreamsEngineConfiguration.setThreadPoolMaxSize(getThreadPoolMaxSize());
            reactiveStreamsEngineConfiguration.setThreadPoolMinSize(getThreadPoolMinSize());
            reactiveStreamsEngineConfiguration.setThreadPoolName(getThreadPoolName());
            setReactiveStreamsEngineConfiguration(reactiveStreamsEngineConfiguration);
        }
        if (reactiveStreamService == null) {
            this.reactiveStreamService = reactiveStreamServiceFactory.newInstance(
                    getCamelContext(),
                    getReactiveStreamsEngineConfiguration());

            try {
                // Start the service and add it to the Camel context to expose managed attributes
                getCamelContext().addService(this.reactiveStreamService, true, true);
            } catch (Exception e) {
                throw new RuntimeCamelException(e);
            }
        }
    }

    return this.reactiveStreamService;
}
 
Example #2
Source File: ApiProviderReturnPathCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(ComponentProxyComponent component, Map<String, Object> options) {
    if (inputDataShape != null && inputDataShape.getKind() == DataShapeKinds.JSON_SCHEMA && inputDataShape.getSpecification() != null) {
        try {
            final JsonNode schema = READER.readTree(inputDataShape.getSpecification());
            Set<String> properties = SimpleJsonSchemaInspector.getProperties(schema);
            Set<String> extraneousProperties = new HashSet<>(properties);
            extraneousProperties.removeAll(Arrays.asList("parameters", "body"));

            if (!properties.isEmpty() && extraneousProperties.isEmpty()) {
                component.setBeforeProducer(new HttpRequestUnwrapperProcessor(schema));
            }
        } catch (IOException e) {
            throw new RuntimeCamelException(e);
        }
    }

    Integer httpResponseStatus =
            ConnectorOptions.extractOptionAndMap(options, HTTP_RESPONSE_CODE_PROPERTY, Integer::valueOf, 200);

    component.setAfterProducer(statusCodeUpdater(httpResponseStatus));
}
 
Example #3
Source File: ODataReadRouteSplitResultsTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmptyServiceUri() throws Exception {
    Connector odataConnector = createODataConnector(new PropertyBuilder<String>());

    Step odataStep = createODataStep(odataConnector, defaultTestServer.resourcePath());
    Integration odataIntegration = createIntegration(odataStep, mockStep);

    RouteBuilder routes = newIntegrationRouteBuilder(odataIntegration);
    context.addRoutes(routes);

    assertThatExceptionOfType(RuntimeCamelException.class)
        .isThrownBy(() -> {
            context.start();
        })
        .withMessageContaining("serviceUri is not set");
}
 
Example #4
Source File: SoapPayloadReaderFilter.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private void processStartElement(final XMLEvent event) {
    final QName name = event.asStartElement().getName();

    if (soapVersion.getEnvelope().equals(name)) {
        inEnvelope = true;
    } else if (inEnvelope && soapVersion.getHeader().equals(name)) {
        inHeader = true;
        // create a writer for headers
        this.headersWriter = new W3CDOMStreamWriter();
    } else if (inEnvelope && soapVersion.getBody().equals(name)) {
        inBody = true;
    }

    if (inBody && !inBodyPart) {
        inBodyPart = !soapVersion.getBody().equals(name);
        bodyPartName = name;
        bodyPartBytes = new ByteArrayOutputStream();
        try {
            bodyPartWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(new StreamResult(bodyPartBytes));
        } catch (XMLStreamException e) {
            throw new RuntimeCamelException(String.format("Error parsing body part %s: %s", bodyPartName,
                e.getMessage()), e);
        }
    }
}
 
Example #5
Source File: SoapPayloadReaderFilter.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private void closeBodyPart(XMLEvent event) {
    try {
        // copy the end element
        processBodyPartEvent(event);

        // close the writer and stream
        bodyPartWriter.close();
        bodyPartBytes.close();

        // add body part byte stream
        bodyParts.add(new StreamSource(bodyPartBytes.toInputStream()));

    } catch (XMLStreamException | IOException e) {
        throw new RuntimeCamelException("Error closing Body part: " + e.getMessage(), e);
    }
}
 
Example #6
Source File: ComponentProxyComponent.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public ComponentProxyComponent(String componentId, String componentScheme, String componentClass, CamelCatalog catalog) {
    this.componentId = StringHelper.notEmpty(componentId, "componentId");
    this.componentScheme = StringHelper.notEmpty(componentScheme, "componentScheme");
    this.componentSchemeAlias = Optional.empty();
    this.configuredOptions = new HashMap<>();
    this.remainingOptions = new HashMap<>();
    this.catalog = ObjectHelper.notNull(catalog, "catalog");

    if (ObjectHelper.isNotEmpty(componentClass)) {
        this.catalog.addComponent(componentScheme, componentClass);
    }

    try {
        this.definition = ComponentDefinition.forScheme(catalog, componentScheme);
    } catch (IOException e) {
        throw RuntimeCamelException.wrapRuntimeCamelException(e);
    }

    registerExtension(this::getComponentVerifierExtension);
}
 
Example #7
Source File: EMailComponent.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected ComponentDefinition getDefinition() {
    try {
        /*
         * The definition set on construction is the placeholder 'email'
         * so find the underlying defintion based on the specified protocol
         */
        return ComponentDefinition.forScheme(getCatalog(), getProtocol());
    } catch (IOException ex) {
        throw RuntimeCamelException.wrapRuntimeCamelException(ex);
    }
}
 
Example #8
Source File: SpringBootXmlCamelContextConfigurer.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(ApplicationContext applicationContext, SpringCamelContext camelContext) {
    CamelConfigurationProperties config = applicationContext.getBean(CamelConfigurationProperties.class);
    if (config != null) {
        try {
            LOG.debug("Merging XML based CamelContext with Spring Boot configuration properties");
            CamelAutoConfiguration.doConfigureCamelContext(applicationContext, camelContext, config);
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }
    }
}
 
Example #9
Source File: MasterContextCustomizer.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(CamelContext camelContext) {
    try {
        KubernetesClusterService clusterService = new KubernetesClusterService();
        if (ObjectHelper.isNotEmpty(configMapName)) {
            clusterService.setConfigMapName(this.configMapName);
        }
        if (ObjectHelper.isNotEmpty(this.labelKey) && ObjectHelper.isNotEmpty(this.labelValue)) {
            clusterService.setClusterLabels(Collections.singletonMap(this.labelKey, this.labelValue));
        }
        camelContext.addService(clusterService);
    } catch (Exception ex) {
        throw new RuntimeCamelException(ex);
    }
}
 
Example #10
Source File: ApplicationRuntime.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
public void addListener(Phase phase, ThrowingConsumer<Runtime, Exception> consumer) {
    addListener((p, runtime) -> {
        if (p == phase) {
            try {
                consumer.accept(runtime);
                return true;
            } catch (Exception e) {
                throw RuntimeCamelException.wrapRuntimeCamelException(e);
            }
        }

        return false;
    });
}
 
Example #11
Source File: RoutesConfigurer.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
protected void load(Runtime runtime, String[] routes) {
    for (String route: routes) {
        if (ObjectHelper.isEmpty(route)) {
            continue;
        }

        try {
            load(runtime, Sources.fromURI(route));
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }

        LOGGER.info("Loading routes from: {}", route);
    }
}
 
Example #12
Source File: Runtime.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
default void addRoutes(RoutesBuilder builder) {
    try {
        getCamelContext().addRoutes(builder);
    } catch (Exception e) {
        throw RuntimeCamelException.wrapRuntimeCamelException(e);
    }
}
 
Example #13
Source File: KnativeConfiguration.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
public KnativeConfiguration copy() {
    try {
        return (KnativeConfiguration)super.clone();
    } catch (CloneNotSupportedException e) {
        throw new RuntimeCamelException(e);
    }
}
 
Example #14
Source File: RngErrorAction.java    From syndesis-extensions with Apache License 2.0 5 votes vote down vote up
@Handler
public void handle(@Body String body, @Headers Map headers, Exchange exchange) {
    Random random = new Random(System.currentTimeMillis());
    if( random.nextBoolean() ) {
        throw new RuntimeCamelException("Random error.. try your luck again next time.");
    }
}
 
Example #15
Source File: CamelContextMetadataMBean.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
    // unregister mbean
    try {
        camelContext.getManagementStrategy().unmanageObject(this);
    } catch (Exception e) {
        throw new RuntimeCamelException(e);
    }
}
 
Example #16
Source File: IntegrationRouteBuilder.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected InputStream createIntegrationInputStream() throws IOException {
    if (sourceProvider != null) {
        try {
            return sourceProvider.getSource(getContext());
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }
    }
    LOGGER.info("Loading integration from: {}", configurationUri);
    return ResourceHelper.resolveMandatoryResourceAsInputStream(getContext(), configurationUri);
}
 
Example #17
Source File: DefaultMessageConverter.java    From hazelcastmq with Apache License 2.0 5 votes vote down vote up
/**
 * Converts from a Camel message to a HzMq message. The headers are simply
 * copied unmodified. The body is mapped by type:
 * <ul>
 * <li>String: set on the HzMq message and the content type set to
 * text/plain</li>
 * <li>byte[]: set on the HzMq message and the content type set to
 * application/octet-stream</li>
 * <li>null: set on the HzMq message with no content type</li>
 * <li>all others: exception raised</li>
 * </ul>
 *
 * @param camelMsg the Camel message to convert
 *
 * @return the new HzMq message
 */
@Override
public HazelcastMQMessage fromCamelMessage(Message camelMsg) {
  HazelcastMQMessage mqMsg = new HazelcastMQMessage();

  Map<String, Object> camelHeaders = camelMsg.getHeaders();

  if (camelHeaders != null) {
    for (Map.Entry<String, Object> camelHeader : camelHeaders.entrySet()) {
      if (camelHeader.getValue() instanceof String) {
        mqMsg.getHeaders().put(camelHeader.getKey(), (String) camelHeader.
            getValue());
      }
    }
  }

  Object camelBody = camelMsg.getBody();
  if (camelBody instanceof String) {
    mqMsg.setBody((String) camelBody);
    mqMsg.setContentType("text/plain");
  }
  else if (camelBody instanceof byte[]) {
    mqMsg.setBody((byte[]) camelBody);
    mqMsg.setContentType("application/octet-stream");
  }
  else if (camelBody == null) {
    mqMsg.setBody((byte[]) null);
  }
  else {
    throw new RuntimeCamelException(format(
        "Unsupported message body type: %s", camelBody.getClass().getName()));
  }

  return mqMsg;
}
 
Example #18
Source File: SoapPayloadReaderFilter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private void processBodyPartEvent(XMLEvent event) {
    try {
        StaxUtils.writeEvent(event, bodyPartWriter);
    } catch (XMLStreamException e) {
        throw new RuntimeCamelException("Error reading SOAP Body: " + e.getMessage(), e);
    }
}
 
Example #19
Source File: SoapPayloadReaderFilter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private void processHeaderEvent(XMLEvent event) {
    try {
        StaxUtils.writeEvent(event, headersWriter);
    } catch (XMLStreamException e) {
        throw new RuntimeCamelException("Error reading SOAP Header: " + e.getMessage(), e);
    }
}
 
Example #20
Source File: RequestSoapPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected void convertMessage(final Message in) {
    try {
        final Source body = bodyAsSource(in);

        // extract body as stream, and headers as elements in single DOM
        final XMLEventReader bodyReader = XML_INPUT_FACTORY.createXMLEventReader(body);
        final SoapPayloadReaderFilter payloadFilter = new SoapPayloadReaderFilter(soapVersion);
        final XMLEventReader eventReader = XML_INPUT_FACTORY.createFilteredReader(bodyReader, payloadFilter);

        // all the work is done in the filter, so we ignore the event writer output
        try (OutputStream bos = new ByteArrayOutputStream()) {
            XMLEventWriter target = XML_OUTPUT_FACTORY.createXMLEventWriter(bos);
            target.add(eventReader);
        }

        // convert filtered parts to CxfPayload
        final CxfPayload<Source> cxfPayload = payloadFilter.getCxfPayload();

        // add existing SOAP headers
        final List<?> existingHeaders = (List<?>) in.getHeader(Header.HEADER_LIST);
        if (existingHeaders != null) {
            final List<Source> headers = cxfPayload.getHeaders();
            for (Object header : existingHeaders) {
                if (header instanceof Source) {
                    headers.add((Source) header);
                } else {
                    // wrap dom node
                    headers.add(new DOMSource((Node)header));
                }
            }
        }

        in.setBody(cxfPayload);

    } catch (XMLStreamException | InvalidPayloadException | IOException e) {
        throw new RuntimeCamelException("Error creating SOAP message from request message: " + e.getMessage(), e);
    }
}
 
Example #21
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 #22
Source File: AbstractFaultSoapPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Exchange exchange) {
    final Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
    if (exception instanceof SoapFault) {

        SoapFault soapFault = (SoapFault) exception;
        final Message in = exchange.getIn();

        // get SOAP QNames from CxfPayload headers
        final SoapMessage soapMessage = in.getHeader("CamelCxfMessage", SoapMessage.class);
        final SoapVersion soapVersion = soapMessage.getVersion();

        try {

            // get CxfPayload body
            final CxfPayload<?> cxfPayload = in.getMandatoryBody(CxfPayload.class);

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

            handleFault(writer, soapFault, 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 #23
Source File: ODataReadToCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected void beforeProducer(Exchange exchange) throws IOException {
    Message in = exchange.getIn();

    String body = in.getBody(String.class);
    JsonNode node = OBJECT_MAPPER.readTree(body);
    JsonNode keyPredicateNode = node.get(KEY_PREDICATE);

    if (! ObjectHelper.isEmpty(keyPredicateNode)) {
        String keyPredicate = keyPredicateNode.asText();

        //
        // Change the resource path instead as there is a bug in using the
        // keyPredicate header (adds brackets around regardless of a subpredicate
        // being present). When that's fixed we can revert back to using keyPredicate
        // header instead.
        //
        in.setHeader(OLINGO4_PROPERTY_PREFIX + RESOURCE_PATH,
                     resourcePath + ODataUtil.formatKeyPredicate(keyPredicate, true));
    } else {
        //
        // Necessary to have a key predicate. Otherwise, read will try returning
        // all results which could very be painful for the running integration.
        //
        throw new RuntimeCamelException("Key Predicate value was empty");
    }

    in.setBody(EMPTY_STRING);
}
 
Example #24
Source File: ApiProviderStartEndpointCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(ComponentProxyComponent component, Map<String, Object> options) {
    final List<Processor> beforeConsumers = new ArrayList<>(2);
    if (outputDataShape != null && outputDataShape.getKind() == DataShapeKinds.JSON_SCHEMA && outputDataShape.getSpecification() != null) {
        try {
            final JsonNode schema = READER.readTree(outputDataShape.getSpecification());
            Set<String> properties = SimpleJsonSchemaInspector.getProperties(schema);
            Set<String> extraneousProperties = new HashSet<>(properties);
            extraneousProperties.removeAll(Arrays.asList("parameters", "body"));

            if (!properties.isEmpty() && extraneousProperties.isEmpty()) {
                beforeConsumers.add(new HttpRequestWrapperProcessor(schema));
            }
        } catch (IOException e) {
            throw new RuntimeCamelException(e);
        }
    }

    beforeConsumers.add(new HttpMessageToDefaultMessageProcessor());

    // removes all non Syndesis.* headers, this is so the headers that might
    // influence HTTP components in the flow after this connector don't
    // interpret them, for instance the `Host` header is particularly
    // troublesome
    beforeConsumers.add((e) -> e.getIn().removeHeaders("*", Exchange.CONTENT_TYPE, "Syndesis.*"));

    component.setBeforeConsumer(Pipeline.newInstance(context, beforeConsumers));
}
 
Example #25
Source File: SimpleManagementTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartupFailure() throws Exception {

    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> onames;
    
    try (CamelContext camelctx = new DefaultCamelContext()) {
    	
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("invalid:start");
            }
        });

        onames = server.queryNames(new ObjectName("org.apache.camel:*"), null);
        Assert.assertEquals(Collections.emptySet(), onames);

        try {
            camelctx.start();
            Assert.fail("Startup failure expected");
        } catch (RuntimeCamelException ex) {
            System.out.println(">>>>>>> Startup Exception: " + ex);
            // expected
        }
    }

    onames = server.queryNames(new ObjectName("org.apache.camel:*"), null);
    Assert.assertEquals(Collections.emptySet(), onames);
}
 
Example #26
Source File: XmlJaxbRecorder.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public RuntimeValue<ModelJAXBContextFactory> newContextFactory() {
    DefaultModelJAXBContextFactory factory = new DefaultModelJAXBContextFactory();
    if (ImageInfo.inImageBuildtimeCode()) {
        try {
            factory.newJAXBContext();
        } catch (JAXBException e) {
            throw new RuntimeCamelException("Unable to initialize Camel JAXBContext", e);
        }
    }
    return new RuntimeValue<>(factory);
}
 
Example #27
Source File: GmailSendEmailCustomizer.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static com.google.api.services.gmail.model.Message createMessage(String to, String from, String subject,
        String bodyText, String cc, String bcc) throws MessagingException, IOException {

    if (ObjectHelper.isEmpty(to)) {
        throw new RuntimeCamelException("Cannot create gmail message as no 'to' address is available");
    }

    if (ObjectHelper.isEmpty(from)) {
        throw new RuntimeCamelException("Cannot create gmail message as no 'from' address is available");
    }

    if (ObjectHelper.isEmpty(subject)) {
        LOG.warn("New gmail message wil have no 'subject'. This may not be want you wanted?");
    }

    if (ObjectHelper.isEmpty(bodyText)) {
        LOG.warn("New gmail message wil have no 'body text'. This may not be want you wanted?");
    }

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipients(javax.mail.Message.RecipientType.TO, getAddressesList(to));
    email.setSubject(subject);
    email.setText(bodyText);
    if (ObjectHelper.isNotEmpty(cc)) {
        email.addRecipients(javax.mail.Message.RecipientType.CC, getAddressesList(cc));
    }
    if (ObjectHelper.isNotEmpty(bcc)) {
        email.addRecipients(javax.mail.Message.RecipientType.BCC, getAddressesList(bcc));
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    email.writeTo(buffer);
    byte[] bytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
    com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example #28
Source File: Soap12FaultSoapPayloadConverter.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
protected void handleFault(XMLStreamWriter writer, SoapFault soapFault, SoapVersion soapVersion) {
    try {
        Map<String, String> namespaces = soapFault.getNamespaces();
        for (Map.Entry<String, String> e : namespaces.entrySet()) {
            writer.writeNamespace(e.getKey(), e.getValue());
        }

        String ns = soapVersion.getNamespace();
        writer.writeStartElement(SOAP_PREFIX, "Fault", ns);

        writer.writeStartElement(SOAP_PREFIX, "Code", ns);
        writer.writeStartElement(SOAP_PREFIX, "Value", ns);

        writer.writeCharacters(soapFault.getCodeString(getFaultCodePrefix(writer, soapFault.getFaultCode()), SOAP_PREFIX));
        writer.writeEndElement();

        if (soapFault.getSubCodes() != null) {
            int fscCount = 0;
            for (QName fsc : soapFault.getSubCodes()) {
                writer.writeStartElement(SOAP_PREFIX, "Subcode", ns);
                writer.writeStartElement(SOAP_PREFIX, "Value", ns);
                writer.writeCharacters(getCodeString(getFaultCodePrefix(writer, fsc), SOAP_PREFIX, fsc));
                writer.writeEndElement();
                fscCount++;
            }
            while (fscCount > 0) {
                writer.writeEndElement();
                fscCount--;
            }
        }
        writer.writeEndElement();

        writer.writeStartElement(SOAP_PREFIX, "Reason", ns);
        writer.writeStartElement(SOAP_PREFIX, "Text", ns);
        String lang = soapFault.getLang();
        if (StringUtils.isEmpty(lang)) {
            lang = getLangCode();
        }
        writer.writeAttribute("xml", "http://www.w3.org/XML/1998/namespace", "lang", lang);
        writer.writeCharacters(getFaultMessage(soapFault));
        writer.writeEndElement();
        writer.writeEndElement();

        if (soapFault.getRole() != null) {
            writer.writeStartElement(SOAP_PREFIX, "Role", ns);
            writer.writeCharacters(soapFault.getRole());
            writer.writeEndElement();
        }

        prepareStackTrace(ns, soapFault);

        if (soapFault.hasDetails()) {
            Element detail = soapFault.getDetail();
            writer.writeStartElement(SOAP_PREFIX, "Detail", ns);

            Node node = detail.getFirstChild();
            while (node != null) {
                StaxUtils.writeNode(node, writer, true);
                node = node.getNextSibling();
            }

            // Details
            writer.writeEndElement();
        }

        // Fault
        writer.writeEndElement();
    } catch (Exception xe) {
        throw new RuntimeCamelException("XML Write Exception: " + xe.getMessage(), xe);
    }
}
 
Example #29
Source File: JaxbDataFormatAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Bean(name = "jaxb-dataformat-factory")
@ConditionalOnMissingBean(JaxbDataFormat.class)
public DataFormatFactory configureJaxbDataFormatFactory() throws Exception {
    return new DataFormatFactory() {
        @Override
        public DataFormat newInstance() {
            JaxbDataFormat dataformat = new JaxbDataFormat();
            if (CamelContextAware.class
                    .isAssignableFrom(JaxbDataFormat.class)) {
                CamelContextAware contextAware = CamelContextAware.class
                        .cast(dataformat);
                if (contextAware != null) {
                    contextAware.setCamelContext(camelContext);
                }
            }
            try {
                Map<String, Object> parameters = new HashMap<>();
                IntrospectionSupport.getProperties(configuration,
                        parameters, null, false);
                CamelPropertiesHelper.setCamelProperties(camelContext,
                        dataformat, parameters, false);
            } catch (Exception e) {
                throw new RuntimeCamelException(e);
            }
            if (ObjectHelper.isNotEmpty(customizers)) {
                for (DataFormatCustomizer<JaxbDataFormat> customizer : customizers) {
                    boolean useCustomizer = (customizer instanceof HasId)
                            ? HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.dataformat.customizer",
                                    "camel.dataformat.jaxb.customizer",
                                    ((HasId) customizer).getId())
                            : HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.dataformat.customizer",
                                    "camel.dataformat.jaxb.customizer");
                    if (useCustomizer) {
                        LOGGER.debug(
                                "Configure dataformat {}, with customizer {}",
                                dataformat, customizer);
                        customizer.customize(dataformat);
                    }
                }
            }
            return dataformat;
        }
    };
}
 
Example #30
Source File: SnakeYAMLDataFormatAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Bean(name = "yaml-snakeyaml-dataformat-factory")
@ConditionalOnMissingBean(SnakeYAMLDataFormat.class)
public DataFormatFactory configureSnakeYAMLDataFormatFactory()
        throws Exception {
    return new DataFormatFactory() {
        @Override
        public DataFormat newInstance() {
            SnakeYAMLDataFormat dataformat = new SnakeYAMLDataFormat();
            if (CamelContextAware.class
                    .isAssignableFrom(SnakeYAMLDataFormat.class)) {
                CamelContextAware contextAware = CamelContextAware.class
                        .cast(dataformat);
                if (contextAware != null) {
                    contextAware.setCamelContext(camelContext);
                }
            }
            try {
                Map<String, Object> parameters = new HashMap<>();
                IntrospectionSupport.getProperties(configuration,
                        parameters, null, false);
                CamelPropertiesHelper.setCamelProperties(camelContext,
                        dataformat, parameters, false);
            } catch (Exception e) {
                throw new RuntimeCamelException(e);
            }
            if (ObjectHelper.isNotEmpty(customizers)) {
                for (DataFormatCustomizer<SnakeYAMLDataFormat> customizer : customizers) {
                    boolean useCustomizer = (customizer instanceof HasId)
                            ? HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.dataformat.customizer",
                                    "camel.dataformat.yaml-snakeyaml.customizer",
                                    ((HasId) customizer).getId())
                            : HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.dataformat.customizer",
                                    "camel.dataformat.yaml-snakeyaml.customizer");
                    if (useCustomizer) {
                        LOGGER.debug(
                                "Configure dataformat {}, with customizer {}",
                                dataformat, customizer);
                        customizer.customize(dataformat);
                    }
                }
            }
            return dataformat;
        }
    };
}