Search in sources :

Example 11 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project webservices-axiom by apache.

the class TestRootPartStreaming method runTest.

@Override
protected void runTest() throws Throwable {
    OMFactory factory = metaFactory.getOMFactory();
    // Programmatically create the message
    OMElement orgRoot = factory.createOMElement("root", null);
    for (int i = 0; i < 10000; i++) {
        factory.createOMElement("child", null, orgRoot).setText("Some text content");
    }
    // Serialize the message as XOP even if there will be no attachment parts
    OMOutputFormat format = new OMOutputFormat();
    format.setDoOptimize(true);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    orgRoot.serialize(baos, format);
    // Parse the message and monitor the number of bytes read
    InstrumentedInputStream in = new InstrumentedInputStream(new ByteArrayInputStream(baos.toByteArray()));
    OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder(factory, StAXParserConfiguration.DEFAULT, MultipartBody.builder().setInputStream(in).setContentType(format.getContentType()).build());
    OMElement root = builder.getDocumentElement();
    long count1 = in.getCount();
    XMLStreamReader reader = root.getXMLStreamReader(false);
    while (reader.hasNext()) {
        reader.next();
    }
    long count2 = in.getCount();
    // We expect that after requesting the document element, only a small part (corresponding to
    // the size of the parser buffer) should have been read:
    assertTrue(count1 < count2 / 2);
}
Also used : OMFactory(org.apache.axiom.om.OMFactory) XMLStreamReader(javax.xml.stream.XMLStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InstrumentedInputStream(org.apache.axiom.testutils.io.InstrumentedInputStream) OMElement(org.apache.axiom.om.OMElement) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) OMXMLParserWrapper(org.apache.axiom.om.OMXMLParserWrapper)

Example 12 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project webservices-axiom by apache.

the class TestSerializeUTF16 method runTest.

@Override
protected void runTest(OMDocument document) throws Throwable {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OMOutputFormat format = new OMOutputFormat();
    format.setCharSetEncoding("UTF-16");
    document.serializeAndConsume(baos, format);
    String xmlDocument = new String(baos.toByteArray(), "UTF-16");
    assertThat(xmlDocument).startsWith("<?xml version=\"1.0\" encoding=\"UTF-16\"?>");
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 13 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project webservices-axiom by apache.

the class PushOMDataSourceReader method proceed.

@Override
public boolean proceed() throws StreamException {
    // TODO: we might want to unwrap the NamespaceRepairingFilter (and some other filters) here
    XmlHandler handler = this.handler;
    OMOutputFormat format = null;
    XmlHandler current = handler;
    while (current instanceof XmlHandlerWrapper) {
        if (current instanceof XmlDeclarationRewriterHandler) {
            format = ((XmlDeclarationRewriterHandler) current).getFormat();
            break;
        }
        current = ((XmlHandlerWrapper) current).getParent();
    }
    if (format == null) {
        // This is for the OMSourcedElement expansion case
        format = new OMOutputFormat();
        format.setDoOptimize(true);
        handler = new PushOMDataSourceXOPHandler(handler);
    }
    try {
        XMLStreamWriter writer = new XmlHandlerStreamWriter(handler, null, AxiomXMLStreamWriterExtensionFactory.INSTANCE);
        // Seed the namespace context with the namespace context from the parent
        OMContainer parent = root.getParent();
        if (parent instanceof OMElement) {
            for (Iterator<OMNamespace> it = ((OMElement) parent).getNamespacesInScope(); it.hasNext(); ) {
                OMNamespace ns = it.next();
                writer.setPrefix(ns.getPrefix(), ns.getNamespaceURI());
            }
        }
        handler.startFragment();
        dataSource.serialize(new MTOMXMLStreamWriterImpl(new PushOMDataSourceStreamWriter(writer), format));
        handler.completed();
    } catch (XMLStreamException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof StreamException) {
            throw (StreamException) cause;
        } else {
            throw new StreamException(ex);
        }
    }
    return true;
}
Also used : OMNamespace(org.apache.axiom.om.OMNamespace) OMElement(org.apache.axiom.om.OMElement) XmlHandlerStreamWriter(org.apache.axiom.core.stream.stax.push.XmlHandlerStreamWriter) StreamException(org.apache.axiom.core.stream.StreamException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamException(javax.xml.stream.XMLStreamException) XmlHandlerWrapper(org.apache.axiom.core.stream.XmlHandlerWrapper) XmlHandler(org.apache.axiom.core.stream.XmlHandler) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) XmlDeclarationRewriterHandler(org.apache.axiom.om.impl.stream.XmlDeclarationRewriterHandler) OMContainer(org.apache.axiom.om.OMContainer)

Example 14 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project webservices-axiom by apache.

the class AbstractOMDataSource method getXMLBytes.

@Override
public final byte[] getXMLBytes(String encoding) throws UnsupportedEncodingException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OMOutputFormat format = new OMOutputFormat();
    format.setCharSetEncoding(encoding);
    try {
        serialize(baos, format);
    } catch (XMLStreamException ex) {
        throw new OMException(ex);
    }
    return baos.toByteArray();
}
Also used : XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) OMException(org.apache.axiom.om.OMException)

Example 15 with OMOutputFormat

use of org.apache.axiom.om.OMOutputFormat in project wso2-axis2-transports by wso2.

the class RabbitMQMessageSender method publish.

/**
 * Perform the creation of exchange/queue and the Outputstream
 *
 * @param message    the RabbitMQ AMQP message
 * @param msgContext the Axis2 MessageContext
 */
public void publish(RabbitMQMessage message, MessageContext msgContext) throws AxisRabbitMQException, IOException {
    String exchangeName = null;
    AMQP.BasicProperties basicProperties = null;
    byte[] messageBody = null;
    if (rmqChannel.isOpen()) {
        String queueName = properties.get(RabbitMQConstants.QUEUE_NAME);
        String routeKey = properties.get(RabbitMQConstants.QUEUE_ROUTING_KEY);
        exchangeName = properties.get(RabbitMQConstants.EXCHANGE_NAME);
        String exchangeType = properties.get(RabbitMQConstants.EXCHANGE_TYPE);
        String replyTo = properties.get(RabbitMQConstants.REPLY_TO_NAME);
        String correlationID = properties.get(RabbitMQConstants.CORRELATION_ID);
        String queueAutoDeclareStr = properties.get(RabbitMQConstants.QUEUE_AUTODECLARE);
        String exchangeAutoDeclareStr = properties.get(RabbitMQConstants.EXCHANGE_AUTODECLARE);
        boolean queueAutoDeclare = true;
        boolean exchangeAutoDeclare = true;
        if (!StringUtils.isEmpty(queueAutoDeclareStr)) {
            queueAutoDeclare = Boolean.parseBoolean(queueAutoDeclareStr);
        }
        if (!StringUtils.isEmpty(exchangeAutoDeclareStr)) {
            exchangeAutoDeclare = Boolean.parseBoolean(exchangeAutoDeclareStr);
        }
        message.setReplyTo(replyTo);
        if (StringUtils.isEmpty(correlationID)) {
            // if reply-to is enabled a correlationID must be available. If not specified, use messageID
            correlationID = message.getMessageId();
        }
        if (!StringUtils.isEmpty(correlationID)) {
            message.setCorrelationId(correlationID);
        }
        if (queueName == null || queueName.equals("")) {
            log.debug("No queue name is specified");
        }
        if (routeKey == null && !"x-consistent-hash".equals(exchangeType)) {
            if (queueName == null || queueName.equals("")) {
                log.debug("Routing key is not specified");
            } else {
                log.debug("Routing key is not specified. Using queue name as the routing key.");
                routeKey = queueName;
            }
        }
        // read publish properties corr id and route key from message context
        Object prRouteKey = msgContext.getProperty(RabbitMQConstants.QUEUE_ROUTING_KEY);
        Object prCorrId = msgContext.getProperty(RabbitMQConstants.CORRELATION_ID).toString();
        if (prRouteKey != null) {
            routeKey = prRouteKey.toString();
            log.debug("Specifying routing key from axis2 properties");
        }
        if (prCorrId != null) {
            message.setCorrelationId(prCorrId.toString());
            log.debug("Specifying correlation id from axis2 properties");
        }
        // Declaring the queue
        if (queueAutoDeclare && queueName != null && !queueName.equals("")) {
            RabbitMQUtils.declareQueue(rmqChannel, queueName, properties);
        }
        // Declaring the exchange
        if (exchangeAutoDeclare && exchangeName != null && !exchangeName.equals("")) {
            RabbitMQUtils.declareExchange(rmqChannel, exchangeName, properties);
            if (queueName != null && !"x-consistent-hash".equals(exchangeType)) {
                // Create bind between the queue and exchange with the routeKey
                try {
                    rmqChannel.getChannel().queueBind(queueName, exchangeName, routeKey);
                } catch (IOException e) {
                    handleException("Error occurred while creating the bind between the queue: " + queueName + " & exchange: " + exchangeName + " with route-key " + routeKey, e);
                }
            }
        }
        AMQP.BasicProperties.Builder builder = buildBasicProperties(message);
        String deliveryModeString = properties.get(RabbitMQConstants.QUEUE_DELIVERY_MODE);
        int deliveryMode = RabbitMQConstants.DEFAULT_DELIVERY_MODE;
        if (deliveryModeString != null) {
            deliveryMode = Integer.parseInt(deliveryModeString);
        }
        builder.deliveryMode(deliveryMode);
        if (!StringUtils.isEmpty(replyTo)) {
            builder.replyTo(replyTo);
        }
        basicProperties = builder.build();
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault);
        }
        // given. Queue/exchange creation, bindings should be done at the broker
        try {
            // x-consistent-hash type
            if (exchangeType != null && exchangeType.equals("x-consistent-hash")) {
                routeKey = UUID.randomUUID().toString();
            }
        } catch (UnsupportedCharsetException ex) {
            handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
        }
        try {
            messageFormatter.writeTo(msgContext, format, out, false);
            messageBody = out.toByteArray();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        try {
            /**
             * Check for parameter on confirmed delivery in RabbitMq to ensure reliable delivery.
             * Can be enabled by setting the parameter "rabbitmq.confirm.delivery" to "true" in broker URL.
             */
            boolean isConfirmedDeliveryEnabled = Boolean.parseBoolean(properties.get(RabbitMQConstants.CONFIRMED_DELIVERY));
            if (isConfirmedDeliveryEnabled) {
                rmqChannel.getChannel().confirmSelect();
            }
            if (exchangeName != null && exchangeName != "") {
                rmqChannel.getChannel().basicPublish(exchangeName, routeKey, basicProperties, messageBody);
            } else {
                rmqChannel.getChannel().basicPublish("", routeKey, basicProperties, messageBody);
            }
            if (isConfirmedDeliveryEnabled) {
                rmqChannel.getChannel().waitForConfirmsOrDie();
            }
        } catch (IOException e) {
            handleException("Error while publishing the message", e);
        } catch (InterruptedException e) {
            handleException("InterruptedException while waiting for AMQP message confirm :", e);
        }
    } else {
        handleException("Channel cannot be created");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) AxisRabbitMQException(org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException) IOException(java.io.IOException) MessageFormatter(org.apache.axis2.transport.MessageFormatter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AMQP(com.rabbitmq.client.AMQP) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Aggregations

OMOutputFormat (org.apache.axiom.om.OMOutputFormat)64 MessageFormatter (org.apache.axis2.transport.MessageFormatter)24 ByteArrayOutputStream (java.io.ByteArrayOutputStream)21 OutputStream (java.io.OutputStream)18 IOException (java.io.IOException)16 AxisFault (org.apache.axis2.AxisFault)13 MessageContext (org.apache.axis2.context.MessageContext)12 OMElement (org.apache.axiom.om.OMElement)11 DataHandler (javax.activation.DataHandler)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 StringWriter (java.io.StringWriter)6 XMLStreamException (javax.xml.stream.XMLStreamException)6 SOAPEnvelope (org.apache.axiom.soap.SOAPEnvelope)6 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)5 OMText (org.apache.axiom.om.OMText)5 Map (java.util.Map)4 MultipartBody (org.apache.axiom.mime.MultipartBody)4 SOAPFactory (org.apache.axiom.soap.SOAPFactory)4 Collection (java.util.Collection)3