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:org.bibalex.gallery.model.BAGGalleryAbstract.java

public String getMetaAlbumStrForMetadataFile(String metaAlbumFileName) throws BAGException {
    try {//from   ww  w.  ja v  a2s. co  m
        Element albumElt = this.getAlbumEltForMetadataFile(metaAlbumFileName);

        XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat().setEncoding("UTF-8"));

        StringWriter resultWriter = new StringWriter();

        outputter.output(albumElt, resultWriter);

        resultWriter.flush();
        resultWriter.close();

        String result = resultWriter.toString();

        return result;
    } catch (IOException e) {
        throw new BAGException(e);
    }

}

From source file:HtmlUtils.java

public String getTableContents(String align, Vector values, int elementCounter) throws IOException {

    StringWriter Cells = new StringWriter();
    String contents = new String();
    int vsize = values.size();

    Cells.write("<TR>");

    for (int i = 0; i < vsize; i++) {
        String value = values.elementAt(i).toString();

        if (i != 0) {
            if (i >= elementCounter) {

                if (i % elementCounter == 0) {
                    Cells.write("</TR>\n\n<TR>");
                }/*from www  .  j  a v a  2  s .  co  m*/
            }
        }

        Cells.write("<TD align=" + align + "> " + value + " </TD> \n");
    }

    Cells.write("</TR>");

    contents = Cells.toString();
    Cells.flush();
    Cells.close();

    return contents;
}

From source file:org.objectstyle.cayenne.exp.Expression.java

public String toString() {
    StringWriter buffer = new StringWriter();
    PrintWriter pw = new PrintWriter(buffer);
    encodeAsString(pw);//from w ww  .  ja  v a 2s. c  o m
    pw.close();
    buffer.flush();
    return buffer.toString();
}

From source file:org.opennms.netmgt.scriptd.ins.events.InsSession.java

private StringWriter getOutput() {
    LOG.debug("Sending alarms to the client");

    final StringWriter sw = new StringWriter();
    final List<Event> events = getEvents();
    if (events != null) {
        for (final Event xmlEvent : events) {
            LOG.info("Marshal Event with id: {}", xmlEvent.getDbid());
            JaxbUtils.marshal(xmlEvent, sw);
            LOG.debug("Flushing Event with id: {}", xmlEvent.getDbid());
            sw.flush();
        }//from w w w .ja va2s.com
    }
    return sw;

}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method triggers the shipping label generation process
 *///from   ww  w  .  ja v a2 s. c  om
public ShipmentOrder generateShippingLabel(ShippingInfoDO shippingInfoDO, ShipmentRequest request)
        throws Exception {

    //Load the properties file 
    loadProperties();

    // JAXB Context of AccessRequest.java
    JAXBContext accessRequestJAXBC = JAXBContext.newInstance(AccessRequest.class.getPackage().getName());
    Marshaller accessRequestMarshaller = accessRequestJAXBC.createMarshaller();

    //JAXB Context of ShipmentConfirmRequest.java
    JAXBContext shipConfirmRequestJAXBC = JAXBContext.newInstance(ShipmentConfirmRequest.class);
    Marshaller shipConfirmRequestMarshaller = shipConfirmRequestJAXBC.createMarshaller();

    //JAXB Context of ShipmentConfirmResponse.java
    JAXBContext shipConfirmJAXBC = JAXBContext.newInstance(ShipmentConfirmResponse.class);
    Unmarshaller shipConfirmUnmarshaller = shipConfirmJAXBC.createUnmarshaller();

    //JAXB Context of ShipmentAcceptRequest.java
    JAXBContext shipAcceptJaxb = JAXBContext.newInstance(ShipmentAcceptRequest.class);
    Marshaller shipAcceptRequestMarshaller = shipAcceptJaxb.createMarshaller();

    //JAXB Context of ShipmentAcceptResponse.Java
    JAXBContext shipAcceptAXBC = JAXBContext.newInstance(ShipmentAcceptResponse.class);
    Unmarshaller shipAcceptUnmarshaller = shipAcceptAXBC.createUnmarshaller();

    StringWriter strWriter = new StringWriter();
    accessRequestMarshaller.marshal(shippingInfoDO.getUpsSecurity(), strWriter);
    shipConfirmRequestMarshaller.marshal(shippingInfoDO.getConfirmRequest(), strWriter);
    strWriter.flush();
    strWriter.close();
    String confirmInput = strWriter.getBuffer().toString();
    //--confirmInput = confirmInput.replace(ShippingConstants.XML_NAMESPACE, "");
    String strResults = contactService(confirmInput,
            properties.getProperty(ShippingConstants.SHIPPING_CONFIRM_URL));
    //--strResults = strResults.replace(ShippingConstants.SHIP_Response_TAG,ShippingConstants.ship_Response_Replace);
    String result = "";
    if (strResults.indexOf(ShippingConstants.error_Open_tag) != -1) {
        result = strResults.substring(strResults.indexOf(ShippingConstants.error_Open_tag),
                strResults.indexOf(ShippingConstants.error_Close_tag));
        result = result.replace(ShippingConstants.error_Open_tag, "");
    }
    ByteArrayInputStream input = new ByteArrayInputStream(strResults.getBytes());
    ShipmentConfirmResponse shipconfirmResponse = new ShipmentConfirmResponse();
    if (null != shipconfirmResponse.getResponse()) {
        shipconfirmResponse.getResponse().getError().add(new Error());
    }
    shipconfirmResponse = (ShipmentConfirmResponse) shipConfirmUnmarshaller.unmarshal(input);
    if (shipconfirmResponse.getResponse().getResponseStatusCode().equals("1")) {
        com.cts.ptms.model.accept.request.ObjectFactory acceptObjectFactory = new com.cts.ptms.model.accept.request.ObjectFactory();
        //ShipmentAcceptRequestObjectFactory acceptObjectFactory = new ShipmentAcceptRequestObjectFactory();
        ShipmentAcceptRequest shipAcceptRequest = acceptObjectFactory.createShipmentAcceptRequest();
        ShipmentAcceptRequest shipmentAcceptRequest = populateShipAcceptRequest(shipAcceptRequest,
                shipconfirmResponse);

        StringWriter strWriterResponse = new StringWriter();
        accessRequestMarshaller.marshal(shippingInfoDO.getUpsSecurity(), strWriterResponse);
        shipAcceptRequestMarshaller.marshal(shipmentAcceptRequest, strWriterResponse);
        strWriterResponse.flush();
        strWriterResponse.close();
        String acceptInput = strWriterResponse.getBuffer().toString();
        //--acceptInput = acceptInput.replace(ShippingConstants.XML_NAMESPACE, "");
        String strAcceptResults = contactService(acceptInput,
                properties.getProperty(ShippingConstants.SHIPPING_ACCEPT_URL));
        //--strAcceptResults = strAcceptResults.replace(ShippingConstants.SHIP_Accept_TAG,ShippingConstants.ship_Accept_Replace);
        ByteArrayInputStream inputAccept = new ByteArrayInputStream(strAcceptResults.getBytes());
        Object objectAccept = shipAcceptUnmarshaller.unmarshal(inputAccept);
        ShipmentAcceptResponse shipAcceptResponse = (ShipmentAcceptResponse) objectAccept;
        if (!shipAcceptResponse.getResponse().getResponseStatusDescription().equalsIgnoreCase("FAILURE")) {
            String imageSrc = shipAcceptResponse.getShipmentResults().getPackageResults().get(0).getLabelImage()
                    .getGraphicImage();
            byte[] decoded = Base64.getDecoder().decode(imageSrc);
            generateShippingLabelPDF(decoded,
                    shipAcceptResponse.getShipmentResults().getShipmentIdentificationNumber(), shippingInfoDO,
                    request);
            if (null != shipAcceptResponse.getShipmentResults().getForm()) {
                String formInfo = shipAcceptResponse.getShipmentResults().getForm().getImage()
                        .getGraphicImage();
                String formExtn = shipAcceptResponse.getShipmentResults().getForm().getImage().getImageFormat()
                        .getCode();
                String formDocType = shipAcceptResponse.getShipmentResults().getForm().getClass()
                        .getSimpleName();
                byte[] intlForms = Base64.getDecoder().decode(formInfo);
                generateShippingForms(intlForms,
                        shipAcceptResponse.getShipmentResults().getShipmentIdentificationNumber(), formDocType,
                        formExtn);
            }
            return createShipmentResposeObj(null, shipAcceptResponse);
        } else {
            return createShipmentResposeObj(null, shipAcceptResponse);
        }
    } else {
        shipconfirmResponse.getResponse().getError().get(0).setErrorDescription(result);
        return createShipmentResposeObj(shipconfirmResponse, null);
    }
}

From source file:de.xplib.xdbm.util.Config.java

/**
 * // w ww.j a  va 2 s  .c  om
 */
public void save() {

    Document doc = null;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        Element config = (Element) doc.appendChild(doc.createElementNS(CONFIG_NS, "config"));
        config.setAttribute("xmlns", CONFIG_NS);

        Element ui = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "ui-settings"));

        Node lang = ui.appendChild(doc.createElementNS(CONFIG_NS, "language"));
        lang.appendChild(doc.createTextNode(this.locale.getLanguage()));

        Element drivers = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "drivers"));
        Iterator dIt = this.dbDrivers.keySet().iterator();
        while (dIt.hasNext()) {

            String jar = (String) dIt.next();

            Element driver = (Element) drivers.appendChild(doc.createElementNS(CONFIG_NS, "driver"));

            driver.setAttribute("jar", jar);
            driver.setAttribute("class", (String) this.dbDrivers.get(jar));

            if (!this.dbUris.containsKey(jar)) {
                continue;
            }

            String value = "";

            ArrayList uris = (ArrayList) this.dbUris.get(jar);
            for (int i = 0, l = uris.size(); i < l; i++) {
                value += uris.get(i) + "||";
            }
            value = value.substring(0, value.length() - 2);

            driver.setAttribute("uris", value);
        }

        Element conns = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "connections"));

        for (int i = 0, s = this.connections.size(); i < s; i++) {

            Connection conn = (Connection) this.connections.get(i);

            Element conne = (Element) conns.appendChild(doc.createElementNS(CONFIG_NS, "connection"));
            conne.setAttribute("jar", conn.getJarFile());
            conne.setAttribute("class", conn.getClassName());
            conne.setAttribute("uri", conn.getUri());
        }

        Element panels = (Element) config.appendChild(doc.createElementNS(CONFIG_NS, "plugins"));

        Iterator it = this.plugins.keySet().iterator();
        while (it.hasNext()) {

            PluginFile pluginFile = (PluginFile) this.plugins.get(it.next());

            Element elem = (Element) panels.appendChild(doc.createElementNS(CONFIG_NS, "plugin"));
            elem.setAttribute("jar", pluginFile.getJarFile());
            elem.setAttribute("class", pluginFile.getClassName());
            elem.setAttribute("id", pluginFile.getId());
            elem.setAttribute("position", pluginFile.getPosition());
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    if (doc != null) {

        OutputFormat of = new OutputFormat(doc);
        of.setIndenting(true);
        of.setIndent(1);
        of.setStandalone(true);

        StringWriter sw = new StringWriter();
        XMLSerializer xs = new XMLSerializer(sw, of);
        xs.setOutputCharStream(sw);

        try {
            xs.serialize(doc);

            sw.flush();

            System.out.println(sw.toString());

            sw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        try {
            FileWriter fw = new FileWriter(this.cfgFile);
            fw.write(sw.toString());
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.geotools.data.wfs.internal.v1_x.MapServerWFSStrategy.java

@Override
public InputStream getPostContents(WFSRequest request) throws IOException {
    InputStream in = super.getPostContents(request);

    if (request.getOperation().compareTo(WFSOperationType.GET_FEATURE) == 0
            && getVersion().compareTo("1.0.0") == 0 && mapServerVersion != null) {
        try {/* www. j av  a2 s . c  o m*/
            // Pre-5.6.7 versions of MapServer do not support the following gml:Box coordinate format:
            // <gml:coord><gml:X>-59.0</gml:X><gml:Y>-35.0</gml:Y></gml:coord><gml:coord>< gml:X>-58.0</gml:X><gml:Y>-34.0</gml:Y></gml:coord>
            // Rewrite the coordinates in the following format:
            // <gml:coordinates cs="," decimal="." ts=" ">-59,-35 -58,-34</gml:coordinates>
            String[] tokens = mapServerVersion.split("\\.");
            if (tokens.length == 3 && versionCompare(mapServerVersion, "5.6.7") < 0) {
                StringWriter writer = new StringWriter();
                IOUtils.copy(in, writer, "UTF-8");
                String pc = writer.toString();

                boolean reformatted = false;
                if (pc.contains("gml:Box") && pc.contains("gml:coord") && pc.contains("gml:X")
                        && pc.contains("gml:Y")) {

                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setNamespaceAware(true);
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(new ByteArrayInputStream(pc.getBytes()));

                    NodeList boxes = doc.getElementsByTagName("gml:Box");
                    for (int b = 0; b < boxes.getLength(); b++) {
                        Element box = (Element) boxes.item(b);
                        NodeList coords = box.getElementsByTagName("gml:coord");
                        if (coords != null && coords.getLength() == 2) {
                            Element coord1 = (Element) coords.item(0);
                            Element coord2 = (Element) coords.item(1);
                            if (coord1 != null && coord2 != null) {
                                Element coordX1 = (Element) (coord1.getElementsByTagName("gml:X").item(0));
                                Element coordY1 = (Element) (coord1.getElementsByTagName("gml:Y").item(0));
                                Element coordX2 = (Element) (coord2.getElementsByTagName("gml:X").item(0));
                                Element coordY2 = (Element) (coord2.getElementsByTagName("gml:Y").item(0));
                                if (coordX1 != null && coordY1 != null && coordX2 != null && coordY2 != null) {
                                    reformatted = true;
                                    String x1 = coordX1.getTextContent();
                                    String y1 = coordY1.getTextContent();
                                    String x2 = coordX2.getTextContent();
                                    String y2 = coordY2.getTextContent();

                                    box.removeChild(coord1);
                                    box.removeChild(coord2);

                                    Element coordinates = doc.createElement("gml:coordinates");
                                    coordinates.setAttribute("cs", ",");
                                    coordinates.setAttribute("decimal", ".");
                                    coordinates.setAttribute("ts", " ");
                                    coordinates.appendChild(
                                            doc.createTextNode(x1 + "," + y1 + " " + x2 + "," + y2));
                                    box.appendChild(coordinates);
                                }
                            }
                        }
                    }

                    if (reformatted) {
                        DOMSource domSource = new DOMSource(doc);
                        StringWriter domsw = new StringWriter();
                        StreamResult result = new StreamResult(domsw);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer transformer = tf.newTransformer();
                        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                        transformer.transform(domSource, result);
                        domsw.flush();
                        pc = domsw.toString();
                    }
                }
                in = new ByteArrayInputStream(pc.getBytes());
            }
        } catch (SAXException | ParserConfigurationException | TransformerException | IOException ex) {
            LOGGER.log(Level.FINE,
                    "Unexpected exception while rewriting 1.0.0 GETFEATURE request with BBOX filter",
                    ex.getMessage());
        }
    }

    return in;
}

From source file:org.apache.axis2.description.AxisDescription.java

public String getDocumentation() {
    if (documentation != null) {
        if (documentation instanceof OMText) {
            return ((OMText) documentation).getText();
        } else if (documentation instanceof OMElement) {
            StringWriter writer = new StringWriter();
            documentation.build();/*  w ww. java  2 s  .  c  o  m*/
            try {
                ((OMElement) documentation).serialize(writer);
            } catch (XMLStreamException e) {
                log.error(e);
            }
            writer.flush();
            return writer.toString();
        }
    }
    return null;
}

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

@Override
public CommonODataEntitySet getODataEntitySet(final ResWrap<EntitySet> resource) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        try {//w  w  w .jav a 2s .  c  o  m
            client.getSerializer(ODataFormat.JSON).write(writer, resource.getPayload());
        } catch (final ODataSerializerException e) {
        }
        writer.flush();
        LOG.debug("EntitySet -> ODataEntitySet:\n{}", writer.toString());
    }

    final URI base = resource.getContextURL() == null ? resource.getPayload().getBaseURI()
            : ContextURLParser.parse(resource.getContextURL()).getServiceRoot();

    final URI next = resource.getPayload().getNext();

    final CommonODataEntitySet entitySet = next == null ? client.getObjectFactory().newEntitySet()
            : client.getObjectFactory().newEntitySet(URIUtils.getURI(base, next.toASCIIString()));

    if (resource.getPayload().getCount() != null) {
        entitySet.setCount(resource.getPayload().getCount());
    }

    for (Entity entityResource : resource.getPayload().getEntities()) {
        add(entitySet, getODataEntity(
                new ResWrap<Entity>(resource.getContextURL(), resource.getMetadataETag(), entityResource)));
    }

    return entitySet;
}

From source file:de.tu_dortmund.ub.data.dswarm.Init.java

/**
 * uploads a file and creates a data resource with it
 *
 * @param filename/* ww w.j a v a  2s  .  c  om*/
 * @param name
 * @param description
 * @return responseJson
 * @throws Exception
 */
private String uploadFileAndCreateResource(final String filename, final String name, final String description,
        final String serviceName, final String engineDswarmAPI) throws Exception {

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        final HttpPost httpPost = new HttpPost(engineDswarmAPI + DswarmBackendStatics.RESOURCES_ENDPOINT);

        final File file1 = new File(filename);
        final FileBody fileBody = new FileBody(file1);
        final StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN);
        final StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN);

        final HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart(DswarmBackendStatics.NAME_IDENTIFIER, stringBodyForName)
                .addPart(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, stringBodyForDescription)
                .addPart(FILE_IDENTIFIER, fileBody).build();

        httpPost.setEntity(reqEntity);

        LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine()));

        try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();
            final HttpEntity httpEntity = httpResponse.getEntity();

            final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                    httpResponse.getStatusLine().getReasonPhrase());

            switch (statusCode) {

            case 201: {

                LOG.info(message);
                final StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, APIStatics.UTF_8);
                final String responseJson = writer.toString();
                writer.flush();
                writer.close();

                LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, responseJson));

                return responseJson;
            }
            default: {

                LOG.error(message);

                EntityUtils.consume(httpEntity);

                throw new Exception("something went wrong at resource upload: " + message);
            }
            }
        }
    }
}