Example usage for java.io StringWriter flush

List of usage examples for java.io StringWriter flush

Introduction

In this page you can find the example usage for java.io StringWriter flush.

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:uk.ac.tgac.conan.core.service.impl.VelocityMergerServiceImpl.java

@Override
public void merge(File template, VelocityContext context, File output) throws IOException {

    log.debug("Loading template data");

    // Load the template
    String template_data = FileUtils.readFileToString(template);

    // Create the output writer
    StringWriter writer = new StringWriter();

    log.debug("Merging template and exectx");

    // Create Velocity properties
    Properties vp = new Properties();
    vp.setProperty("resource.loader", "class");
    vp.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
    vp.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    vp.setProperty("runtime.log.logsystem.log4j.logger", VelocityMergerServiceImpl.class.getName());

    // Merge the template and the exectx
    VelocityEngine ve = new VelocityEngine(vp);
    ve.init();// w  ww  .j av  a  2 s  .  c  o m
    ve.evaluate(context, writer, "LaTeX Report Builder", template_data);
    writer.flush();
    writer.close();

    log.debug("Writing merged file to disk");

    // Output to file 
    FileUtils.writeStringToFile(output, writer.toString());

    log.debug("Velocity template and exectx merged and saved successfully");
}

From source file:org.apache.olingo.client.core.serialization.AbstractODataBinder.java

@Override
public CommonODataEntity getODataEntity(final ResWrap<Entity> resource) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        try {//from   w w w.java2s. com
            client.getSerializer(ODataFormat.JSON).write(writer, resource.getPayload());
        } catch (final ODataSerializerException e) {
        }
        writer.flush();
        LOG.debug("EntityResource -> ODataEntity:\n{}", writer.toString());
    }

    final ContextURL contextURL = ContextURLParser.parse(resource.getContextURL());
    final URI base = resource.getContextURL() == null ? resource.getPayload().getBaseURI()
            : contextURL.getServiceRoot();
    final EdmType edmType = findType(resource.getPayload().getType(), contextURL, resource.getMetadataETag());
    FullQualifiedName typeName = null;
    if (resource.getPayload().getType() == null) {
        if (edmType != null) {
            typeName = edmType.getFullQualifiedName();
        }
    } else {
        typeName = new FullQualifiedName(resource.getPayload().getType());
    }

    final CommonODataEntity entity = resource.getPayload().getSelfLink() == null
            ? client.getObjectFactory().newEntity(typeName)
            : client.getObjectFactory().newEntity(typeName,
                    URIUtils.getURI(base, resource.getPayload().getSelfLink().getHref()));

    if (StringUtils.isNotBlank(resource.getPayload().getETag())) {
        entity.setETag(resource.getPayload().getETag());
    }

    if (resource.getPayload().getEditLink() != null) {
        entity.setEditLink(URIUtils.getURI(base, resource.getPayload().getEditLink().getHref()));
    }

    for (Link link : resource.getPayload().getAssociationLinks()) {
        entity.addLink(client.getObjectFactory().newAssociationLink(link.getTitle(),
                URIUtils.getURI(base, link.getHref())));
    }

    odataNavigationLinks(edmType, resource.getPayload(), entity, resource.getMetadataETag(), base);

    for (Link link : resource.getPayload().getMediaEditLinks()) {
        entity.addLink(client.getObjectFactory().newMediaEditLink(link.getTitle(),
                URIUtils.getURI(base, link.getHref())));
    }

    for (ODataOperation operation : resource.getPayload().getOperations()) {
        operation.setTarget(URIUtils.getURI(base, operation.getTarget()));
        entity.getOperations().add(operation);
    }

    if (resource.getPayload().isMediaEntity()) {
        entity.setMediaEntity(true);
        entity.setMediaContentSource(URIUtils.getURI(base, resource.getPayload().getMediaContentSource()));
        entity.setMediaContentType(resource.getPayload().getMediaContentType());
        entity.setMediaETag(resource.getPayload().getMediaETag());
    }

    for (Property property : resource.getPayload().getProperties()) {
        EdmType propertyType = null;
        if (edmType instanceof EdmEntityType) {
            final EdmElement edmProperty = ((EdmEntityType) edmType).getProperty(property.getName());
            if (edmProperty != null) {
                propertyType = edmProperty.getType();
            }
        }
        add(entity, getODataProperty(propertyType, property));
    }

    return entity;
}

From source file:com.tek42.perforce.parse.AbstractPerforceTemplate.java

/**
 * Executes a p4 command and returns the output as list of lines.
 * //from  w  ww. j a  v a  2s . c  o  m
 * TODO Introduce a method that handles prefixed messages (i.e. "p4 -s <sub-command>"),
 * and can thus stop reading once if reads the "exit: <exit-code>" line, which
 * should avoid the "expected" Exception at EOF.
 * 
 * @param cmd
 *      The perforce command to execute.  The command and arguments are
 *      each in their own array element (e.g. cmd = {"p4", "info"}).
 * @return
 *      The response from perforce as a list
 * @throws PerforceException 
 */
protected List<String> getRawPerforceResponseLines(String cmd[]) throws PerforceException {
    List<String> lines = new ArrayList<String>(1024);

    Executor p4 = depot.getExecFactory().newExecutor();
    String debugCmd = "";
    // get entire cmd to execute
    cmd = getExtraParams(cmd);

    // setup information for logging...
    for (String cm : cmd) {
        debugCmd += cm + " ";
    }

    // Perform execution and IO
    p4.exec(cmd);

    try {
        BufferedReader reader = p4.getReader();
        p4.getWriter().close();
        String line = null;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
    } catch (IOException ioe) {
        //this is generally not anything to worry about.  The underlying
        //perforce process terminated and that causes java to be angry.

        // TODO Given the above comment, should we bother to log a warning?
        // See this blog for a discussion of IOException with message "Write end dead" from pipes:
        //      http://techtavern.wordpress.com/2008/07/16/whats-this-ioexception-write-end-dead/

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        ioe.printStackTrace(pw);
        pw.flush();
        sw.flush();
        getLogger().warn("IOException reading from Perforce process (may just be EOF)");
        getLogger().warn(sw.toString());
    } finally {
        try {
            p4.getWriter().close();
        } catch (IOException e) {
            getLogger().warn("Write pipe failed to close.");
        }
        try {
            p4.getReader().close();
        } catch (IOException e) {
            getLogger().warn("Read pipe failed to close.");
        }
        p4.close();
    }

    return lines;
}

From source file:com.tek42.perforce.parse.AbstractPerforceTemplate.java

/**
 * Used by calls that make use of p4.exe's python dictionary output format.
 * @param cmd/*w  w  w.j av  a 2  s .  c o  m*/
 * @return
 * @throws PerforceException
 */

protected byte[] getRawPerforceResponseBytes(String cmd[]) throws PerforceException {
    List<Byte> bytes = new ArrayList<Byte>(1024);

    Executor p4 = depot.getExecFactory().newExecutor();
    String debugCmd = "";
    // get entire cmd to execute
    cmd = getExtraParams(cmd);

    // setup information for logging...
    for (String cm : cmd) {
        debugCmd += cm + " ";
    }

    // Perform execution and IO
    p4.exec(cmd);

    try {
        byte[] cbuf = new byte[1024];
        InputStream input = p4.getInputStream();
        p4.getWriter().close();
        int readCount = -1;
        while ((readCount = input.read(cbuf, 0, 1024)) != -1) {
            for (int i = 0; i < readCount; i++) {
                bytes.add(new Byte((byte) (cbuf[i] & 0xff)));
            }
        }
    } catch (IOException ioe) {
        //this is generally not anything to worry about.  The underlying
        //perforce process terminated and that causes java to be angry.

        // TODO Given the above comment, should we bother to log a warning?
        // See this blog for a discussion of IOException with message "Write end dead" from pipes:
        //      http://techtavern.wordpress.com/2008/07/16/whats-this-ioexception-write-end-dead/

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        ioe.printStackTrace(pw);
        pw.flush();
        sw.flush();
        getLogger().warn("IOException reading from Perforce process (may just be EOF)");
        getLogger().warn(sw.toString());
    } finally {
        try {
            p4.getWriter().close();
        } catch (IOException e) {
            getLogger().warn("Write pipe failed to close.");
        }
        try {
            p4.getReader().close();
        } catch (IOException e) {
            getLogger().warn("Read pipe failed to close.");
        }
        p4.close();
    }
    byte[] byteArray = new byte[bytes.size()];
    for (int i = 0; i < bytes.size(); i++) {
        byteArray[i] = bytes.get(i).byteValue();
    }
    return byteArray;
}

From source file:com.mobicage.rogerthat.xmpp.CallBackApiXMPPListener.java

/**
 * Establish an XMPP connection to XmppService and listen for Rogerthat API callbacks.
 *//*from   www.  ja  v  a  2  s.  c  om*/
public void startListening() {

    if (connectionThread != null) {
        throw new RuntimeException("Previous connection has not yet been closed!");
    }

    if (xmppUsername == null || xmppService == null || xmppPassword == null || sik == null)
        throw new RuntimeException("Not enough information present to setup an xmpp connection");

    final ConnectionListener connectionListener = new ConnectionListener() {
        @Override
        public void reconnectionSuccessful() {
            log.info("Reconnection to jabber server succeeded.");
            status = XmppConnectionStatus.Connected;
        }

        @Override
        public void reconnectionFailed(Exception e) {
            log.info("Reconnection to jabber server failed.");
        }

        @Override
        public void reconnectingIn(int seconds) {
            log.info("Reconnecting to jabber in " + seconds + " seconds ...");
            status = XmppConnectionStatus.Reconnecting;
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            log.info("Connection closed to jabber due to " + e.toString());
        }

        @Override
        public void connectionClosed() {
            log.info("Connection to jabber closed.");
        }
    };

    tasks.clear();

    connectionThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    Runnable task = tasks.take();
                    task.run();
                }
            } catch (StopListeningException e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "";
            } catch (Throwable e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "Connection interrupted.";
            } finally {
                connectionThread = null;
            }
        }
    });
    connectionThread.setName("Rogerthat callback listener");
    connectionThread.setDaemon(true);
    connectionThread.start();

    tasks.add(new Runnable() {
        @Override
        public void run() {
            ConnectionConfiguration conf = new ConnectionConfiguration(xmppService);

            status = XmppConnectionStatus.Connecting;

            log.info("Connecting to jabber server ...");
            conn = new XMPPConnection(conf);
            try {
                conn.connect();
            } catch (XMPPException e) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to reach Rogerthat servers.\n" + e.getMessage();
                conn = null;
                connectionThread = null;
                if (onConnectionFailed != null)
                    try {
                        onConnectionFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onConnectionFailed handler.", t);
                    }
                throw new RuntimeException(e); // Stop thread.
            }

            if (onConnected != null)
                try {
                    onConnected.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onConnected handler.", t);
                }

            conn.addConnectionListener(connectionListener);

            SASLAuthentication.supportSASLMechanism("PLAIN", 0);

            PacketFilter filter = new PacketFilter() {
                @Override
                public boolean accept(Packet packet) {
                    boolean accept = packet instanceof Message
                            && ROGERTHAT_CALLBACK_BOT.equals(packet.getFrom());
                    if (!accept)
                        log.info("Dropping packet:\n" + packet.toXML());
                    return accept;
                }
            };

            conn.addPacketListener(new PacketListener() {
                @Override
                public void processPacket(Packet packet) {
                    log.info("Processing packet:\n" + packet.toXML());
                    if (!(packet instanceof Message)) {
                        log.info("Ignoring non message packet.");
                        return;
                    }
                    Message message = (Message) packet;
                    PacketExtension extension = packet.getExtension("call", "mobicage:comm");
                    if (extension == null || !(extension instanceof CallbackRequestExtension)) {
                        log.info("Ignoring incomplete packet.");
                        return;
                    }
                    CallbackRequestExtension call = (CallbackRequestExtension) extension;
                    if (!sik.equals(call.getSik())) {
                        log.info("Ignoring packet with incorrect sik.");
                        return;
                    }
                    String json;
                    try {
                        json = new String(DatatypeConverter.parseBase64Binary(call.getBase64Body()), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        log.log(Level.WARNING, "Could not decode base64 packet.", e);
                        return;
                    }
                    final JSONObject request = (JSONObject) JSONValue.parse(json);

                    if (logTraffic)
                        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sik, json));

                    final String id = (String) request.get("id");

                    if (callbackDedup != null) {
                        byte[] response = callbackDedup.getResponse(id);
                        if (response != null) {
                            Message resultMessage = new Message(message.getFrom());
                            resultMessage.setFrom(message.getTo());
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            log.info("Sending message:\n" + resultMessage.toXML());
                            conn.sendPacket(resultMessage);
                            return;
                        }
                    }

                    final JSONObject result = new JSONObject();
                    final RequestContext requestContext = new RequestContext(id, sik);
                    try {
                        processor.process(request, result, requestContext);
                    } finally {
                        try {
                            StringWriter writer = new StringWriter();
                            try {
                                result.writeJSONString(writer);
                                writer.flush();
                                json = writer.toString();

                                if (logTraffic)
                                    log.info("Returning result:\n" + json);

                            } finally {
                                writer.close();
                            }
                        } catch (IOException e) {
                            log.log(Level.SEVERE, "Could not write json object to string", e);
                            return;
                        }
                        Message resultMessage = new Message(message.getFrom());
                        resultMessage.setFrom(message.getTo());
                        try {
                            byte[] response = json.getBytes("UTF-8");
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            if (callbackDedup != null) {
                                callbackDedup.storeResponse(id, response);
                            }
                        } catch (UnsupportedEncodingException e) {
                            log.log(Level.SEVERE, "Could not add result to message packet", e);
                            return;
                        }
                        log.info("Sending message:\n" + resultMessage.toXML());
                        conn.sendPacket(resultMessage);
                    }

                }
            }, filter);

            try {
                conn.login(xmppUsername, xmppPassword);
            } catch (XMPPException e1) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to authenticate jabber connection. Verify your configuration.\n"
                        + e1.getMessage();
                conn = null;
                connectionThread = null;
                if (onAuthenticationFailed != null)
                    try {
                        onAuthenticationFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onAuthenticationFailed handler.", t);
                    }
                throw new RuntimeException(); // Stop thread.
            }

            status = XmppConnectionStatus.Connected;

            if (onAuthenticated != null)
                try {
                    onAuthenticated.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onAuthenticated handler.", t);
                }
        }
    });

}

From source file:org.apache.axis2.corba.deployer.CorbaDeployer.java

private void populateService(AxisService service, OMElement service_element, String directory)
        throws DeploymentException {
    try {/*w  ww . j a  va2 s . c  om*/
        // Processing service level parameters
        Iterator itr = service_element.getChildrenWithName(new QName(TAG_PARAMETER));
        processParameters(itr, service, service.getParent());

        // process service description
        OMElement descriptionElement = service_element.getFirstChildWithName(new QName(TAG_DESCRIPTION));
        if (descriptionElement != null) {
            OMElement descriptionValue = descriptionElement.getFirstElement();
            if (descriptionValue != null) {
                StringWriter writer = new StringWriter();
                descriptionValue.build();
                descriptionValue.serialize(writer);
                writer.flush();
                service.setDocumentation(writer.toString());
            } else {
                service.setDocumentation(descriptionElement.getText());
            }
        } else {
            OMAttribute serviceNameatt = service_element.getAttribute(new QName(ATTRIBUTE_NAME));

            if (serviceNameatt != null) {
                if (!"".equals(serviceNameatt.getAttributeValue().trim())) {
                    service.setDocumentation(serviceNameatt.getAttributeValue());
                }
            }
        }
        OMAttribute serviceNameatt = service_element.getAttribute(new QName(ATTRIBUTE_NAME));

        // If the service name is explicitly specified in the services.xml
        // then use that as the service name
        if (serviceNameatt != null) {
            if (!"".equals(serviceNameatt.getAttributeValue().trim())) {
                service.setName(serviceNameatt.getAttributeValue());
                // To be on the safe side
                if (service.getDocumentation() == null) {
                    service.setDocumentation(serviceNameatt.getAttributeValue());
                }
            }
        }

        // Process WS-Addressing flag attribute
        OMAttribute addressingRequiredatt = service_element.getAttribute(new QName(ATTRIBUTE_WSADDRESSING));
        if (addressingRequiredatt != null) {
            String addressingRequiredString = addressingRequiredatt.getAttributeValue();
            AddressingHelper.setAddressingRequirementParemeterValue(service, addressingRequiredString);
        }

        // Setting service target namespace if any
        OMAttribute targetNameSpace = service_element.getAttribute(new QName(TARGET_NAME_SPACE));
        if (targetNameSpace != null) {
            String nameSpeceVale = targetNameSpace.getAttributeValue();
            if (nameSpeceVale != null && !"".equals(nameSpeceVale)) {
                service.setTargetNamespace(nameSpeceVale);
            }
        } else {
            if (service.getTargetNamespace() == null || "".equals(service.getTargetNamespace())) {
                service.setTargetNamespace(Java2WSDLConstants.DEFAULT_TARGET_NAMESPACE);
            }
        }

        // Setting schema namespece if any
        OMElement schemaElement = service_element.getFirstChildWithName(new QName(SCHEMA));
        if (schemaElement != null) {
            OMAttribute schemaNameSpace = schemaElement.getAttribute(new QName(SCHEMA_NAME_SPACE));
            if (schemaNameSpace != null) {
                String nameSpeceVale = schemaNameSpace.getAttributeValue();
                if (nameSpeceVale != null && !"".equals(nameSpeceVale)) {
                    service.setSchemaTargetNamespace(nameSpeceVale);
                }
            }
            OMAttribute elementFormDefault = schemaElement.getAttribute(new QName(SCHEMA_ELEMENT_QUALIFIED));
            if (elementFormDefault != null) {
                String value = elementFormDefault.getAttributeValue();
                if ("true".equals(value)) {
                    service.setElementFormDefault(true);
                } else if ("false".equals(value)) {
                    service.setElementFormDefault(false);
                }
            }
        }

        // Removing exclude operations
        OMElement excludeOperations = service_element.getFirstChildWithName(new QName(TAG_EXCLUDE_OPERATIONS));
        ArrayList excludeops = null;
        if (excludeOperations != null) {
            excludeops = new ArrayList();
            Iterator excludeOp_itr = excludeOperations.getChildrenWithName(new QName(TAG_OPERATION));
            while (excludeOp_itr.hasNext()) {
                OMElement opName = (OMElement) excludeOp_itr.next();
                excludeops.add(opName.getText().trim());
            }
        }
        if (excludeops == null) {
            excludeops = new ArrayList();
        }

        // processing service-wide modules which required to engage globally
        Iterator moduleRefs = service_element.getChildrenWithName(new QName(TAG_MODULE));
        while (moduleRefs.hasNext()) {
            OMElement moduleref = (OMElement) moduleRefs.next();
            OMAttribute moduleRefAttribute = moduleref.getAttribute(new QName(TAG_REFERENCE));
            String refName = moduleRefAttribute.getAttributeValue();
            axisConfig.addGlobalModuleRef(refName);
        }

        OMElement messageReceiver = service_element.getFirstChildWithName(new QName(TAG_MESSAGE_RECEIVERS));
        ClassLoader loader = service.getClassLoader();

        // Set default message recievers
        service.addMessageReceiver("http://www.w3.org/2004/08/wsdl/in-only",
                loadMessageReceiver(loader, "org.apache.axis2.corba.receivers.CorbaInOnlyMessageReceiver"));
        service.addMessageReceiver("http://www.w3.org/2004/08/wsdl/robust-in-only",
                loadMessageReceiver(loader, "org.apache.axis2.corba.receivers.CorbaInOnlyMessageReceiver"));
        service.addMessageReceiver("http://www.w3.org/2004/08/wsdl/in-out",
                loadMessageReceiver(loader, "org.apache.axis2.corba.receivers.CorbaMessageReceiver"));
        service.addMessageReceiver("http://www.w3.org/2004/08/wsdl/in-opt-out",
                loadMessageReceiver(loader, "org.apache.axis2.corba.receivers.CorbaInOutAsyncMessageReceiver"));

        if (messageReceiver != null) {
            HashMap mrs = processMessageReceivers(loader, messageReceiver);
            Iterator keys = mrs.keySet().iterator();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                service.addMessageReceiver(key, (MessageReceiver) mrs.get(key));
            }
        }

        // processing transports
        OMElement transports = service_element.getFirstChildWithName(new QName(TAG_TRANSPORTS));
        if (transports != null) {
            Iterator transport_itr = transports.getChildrenWithName(new QName(TAG_TRANSPORT));
            ArrayList trs = new ArrayList();
            while (transport_itr.hasNext()) {
                OMElement trsEle = (OMElement) transport_itr.next();
                String tarnsportName = trsEle.getText().trim();
                trs.add(tarnsportName);
            }
            service.setExposedTransports(trs);
        }

        // processing operations
        processOperations(service, axisConfig, excludeops, null, directory);
        Iterator operationsIterator = service.getOperations();
        while (operationsIterator.hasNext()) {
            AxisOperation operationDesc = (AxisOperation) operationsIterator.next();
            ArrayList wsamappings = operationDesc.getWSAMappingList();
            if (wsamappings == null) {
                continue;
            }
            if (service.getOperation(operationDesc.getName()) == null) {
                service.addOperation(operationDesc);
            }
            for (int j = 0; j < wsamappings.size(); j++) {
                String mapping = (String) wsamappings.get(j);
                if (mapping.length() > 0) {
                    service.mapActionToOperation(mapping, operationDesc);
                }
            }
        }

        for (int i = 0; i < excludeops.size(); i++) {
            String opName = (String) excludeops.get(i);
            service.removeOperation(new QName(opName));
        }
    } catch (XMLStreamException e) {
        throw new DeploymentException(e);
    } catch (AxisFault axisFault) {
        throw new DeploymentException(
                Messages.getMessage(DeploymentErrorMsgs.OPERATION_PROCESS_ERROR, axisFault.getMessage()),
                axisFault);
    } catch (Exception e) {
        throw new DeploymentException(e);
    }
}

From source file:perflab.loadrunnerwrapperjenkins.LoadRunnerWrapper.java

private String getStringFromDoc(org.w3c.dom.Document doc) {
    try {//from   ww  w  .j a va  2s .com
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        writer.flush();
        return writer.toString();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.adobe.acs.commons.components.longformtext.impl.LongFormTextComponentImpl.java

@Override
public final String[] getTextParagraphs(final String text) {
    List<String> paragraphs = new ArrayList<String>();

    try {/*from  w ww .  j  a v  a2 s . c  om*/
        final Document doc = htmlParser.parse(null, IOUtils.toInputStream(text), "UTF-8");
        doc.getDocumentElement().normalize();

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        final NodeList bodies = doc.getElementsByTagName("body");

        if (bodies != null && bodies.getLength() == 1) {
            final org.w3c.dom.Node body = bodies.item(0);
            final NodeList children = body.getChildNodes();

            for (int i = 0; i < children.getLength(); i++) {
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);

                final org.w3c.dom.Node child = children.item(i);
                if (child == null) {
                    log.warn("Found a null dom node.");
                    continue;
                } else if (child.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
                    log.warn("Found a dom node is not an element; skipping");
                    continue;
                }

                stripNamespaces(child);
                transformer.transform(new DOMSource(child), result);
                writer.flush();

                final String outerHTML = writer.toString();

                if (StringUtils.isNotBlank(outerHTML)) {
                    paragraphs.add(outerHTML);
                }
            }
        } else {
            log.debug("HTML does not have a single body tag. Cannot parse as expected.");
        }
    } catch (Exception e) {
        log.warn("Long Form Text encountered a parser error: {}", e);
    }

    return paragraphs.toArray(new String[paragraphs.size()]);
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public static XmlElement getAtomElement(final StartElement start, final XMLEventReader reader)
        throws Exception {

    final XmlElement res = new XmlElement();
    res.setStart(start);//from  w ww. j a  va  2s .  c  o  m

    StringWriter content = new StringWriter();

    int depth = 1;

    while (reader.hasNext() && depth > 0) {
        final XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLStreamConstants.START_ELEMENT
                && start.getName().getLocalPart().equals(event.asStartElement().getName().getLocalPart())) {
            depth++;
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
                && start.getName().getLocalPart().equals(event.asEndElement().getName().getLocalPart())) {
            depth--;
        }

        if (depth == 0) {
            res.setEnd(event.asEndElement());
        } else {
            event.writeAsEncodedUnicode(content);
        }
    }

    content.flush();
    content.close();

    res.setContent(new ByteArrayInputStream(content.toString().getBytes()));

    return res;
}

From source file:fr.univlr.cri.planning.factory.HugICalendarFactory.java

/**
 * Lecture d'un fichier icalendar via l'API de la librairie ical4j. Les
 * occupations contenues dans la fenetre d'interrogation [dateDebut, dateFin]
 * sont retournees.//from  w  w w .jav a2  s .  c  o  m
 * 
 * @param pathICalendar
 *          : le chemin du fichier ICS
 * @param dateDebut
 *          : date de debut de la periode d'interrogation
 * @param dateFin
 *          : date de fin de la periode d'interrogation
 * @return
 * @throws CalendarNotFoundException
 */
private CalendarObject newCalendarObjectFromICalendarFileICal4J(String pathICalendar, NSTimestamp dateDebut,
        NSTimestamp dateFin) throws CalendarNotFoundException {

    CalendarObject oCal = null;

    InputStream in = null;
    try {
        // fin = new FileInputStream(pathICalendar);
        URL url = new URL(pathICalendar);
        URLConnection con = url.openConnection();
        con.connect();
        in = con.getInputStream();
    } catch (FileNotFoundException e) {
        throw new CalendarNotFoundException("Calendar " + pathICalendar + " non trouv ou acc?s refus.");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    /*
     * CalendarBuilder calendarBuilder = new CalendarBuilder();
     * 
     * try { long l1 = System.currentTimeMillis(); Calendar calendar =
     * calendarBuilder.build(in); oCal = new CalendarObject(pathICalendar); l1 =
     * System.currentTimeMillis() - l1; CktlLog.log(">> parsing : " + l1 +
     * " ms ("+pathICalendar+")");
     * 
     * // on passe au evenements for (Iterator i =
     * calendar.getComponents().iterator(); i.hasNext();) { Component component
     * = (Component) i.next(); if (component.getName().equals(Component.VEVENT))
     * { VEvent vEvent = (VEvent) component; oCal.addSPVEvent(new
     * SPVEvent(vEvent)); } }
     * 
     * 
     * 
     * } catch (IOException e) { throw new
     * CalendarNotFoundException("Calendar "+ pathICalendar
     * +" erreur de lecture " + e.getMessage()); } catch (ParserException e) {
     * throw new CalendarNotFoundException("Calendar "+ pathICalendar
     * +" erreur de lecture " + e.getMessage()); }
     */

    String string = null;

    try {
        long l1 = System.currentTimeMillis();
        URL url = new URL(pathICalendar);
        URLConnection con = url.openConnection();
        con.connect();

        BufferedInputStream bin = new BufferedInputStream(con.getInputStream());
        StringWriter out = new StringWriter();
        int b;
        while ((b = bin.read()) != -1)
            out.write(b);
        out.flush();
        out.close();
        bin.close();
        string = out.toString();
        l1 = System.currentTimeMillis() - l1;
        System.out.println("converting calendar url to string : " + l1 + " ms (" + pathICalendar + ")");
    } catch (IOException ie) {
        ie.printStackTrace();
    }

    long l1 = System.currentTimeMillis();
    StringReader sin = new StringReader(string);
    CalendarBuilder builder = new CalendarBuilder();

    Calendar calendar = null;
    try {
        calendar = builder.build(sin);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    l1 = System.currentTimeMillis() - l1;
    System.out.println("parse calendar string : " + l1 + " ms (" + pathICalendar + ")");

    oCal = new CalendarObject(pathICalendar);

    // on passe au evenements
    for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
        Component component = (Component) i.next();
        if (component.getName().equals(Component.VEVENT)) {
            VEvent vEvent = (VEvent) component;
            oCal.addSPVEvent(new SPVEvent(vEvent));
        }
    }

    // on met en cache notre affaire
    if (oCal != null) {
        putCalendarInCache(pathICalendar, oCal);
    }

    return oCal;
}