Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphExecuter.java

public String getGraphAsString() throws GraphException, IOException {
    final StringWriter stringWriter = new StringWriter();
    try {/* w  w w  .ja  va 2  s. co  m*/
        AssignAllParameters();
        GraphIO.write(graph, stringWriter);
    } catch (Exception e) {
        throw new GraphException("Unable to write graph to string" + '\n' + e.getMessage());
    } finally {
        stringWriter.close();
    }
    return stringWriter.toString();
}

From source file:com.ecyrd.jspwiki.search.LuceneSearchProvider.java

/**
 * @param att Attachment to get content for. Filename extension is used to determine the type of the attachment.
 * @return String representing the content of the file.
 * FIXME This is a very simple implementation of some text-based attachment, mainly used for testing.
 * This should be replaced /moved to Attachment search providers or some other 'plugable' wat to search attachments
 *//*from   ww w . j  a  va 2s  . co  m*/
protected String getAttachmentContent(Attachment att) {
    AttachmentManager mgr = m_engine.getAttachmentManager();
    //FIXME: Add attachment plugin structure

    String filename = att.getFileName();

    if (filename.endsWith(".txt") || filename.endsWith(".xml") || filename.endsWith(".ini")
            || filename.endsWith(".html")) {
        InputStream attStream;

        try {
            attStream = mgr.getAttachmentStream(att);

            StringWriter sout = new StringWriter();
            FileUtil.copyContents(new InputStreamReader(attStream), sout);

            attStream.close();
            sout.close();

            return sout.toString();
        } catch (ProviderException e) {
            log.error("Attachment cannot be loaded", e);
            return null;
        } catch (IOException e) {
            log.error("Attachment cannot be loaded", e);
            return null;
        }
    }

    return null;
}

From source file:edu.harvard.i2b2.query.data.ModifierData.java

@Override
public Document retrieveMetadataXMLfromONTAndSetOriginalXML(Document incompleteXMLDoc) {
    try {/*w  w  w . j av a2  s  .  c  o m*/
        // call ONT service to get the full XML for the modifier         
        GetModifierInfoType vocab = new GetModifierInfoType();
        vocab.setHiddens(true);
        vocab.setSynonyms(false);
        vocab.setMax(200);
        vocab.setType("default");
        vocab.setBlob(true);
        vocab.setAppliedPath(applied_path);
        vocab.setSelf(modifier_key);
        String xmlContent = OntServiceDriver.getModifierInfo(vocab, "");

        // parse the XML and build a DOM
        java.io.StringReader xmlStringReader = new StringReader(xmlContent);
        SAXBuilder parser = new SAXBuilder();
        Document conceptDoc = parser.build(xmlStringReader);

        //bugbug: printouts
        System.err.println("Modifier XML from ONT"); // bugbug:
        System.err.println(MessageUtil.prettyFormat(xmlContent, 5)); // bugbug:

        // work with DOM to extract the <ont:concepts> node
        Element elementMsgBody = conceptDoc.getRootElement().getChild(MESSAGE_BODY);
        Element modifiersTag = (Element) elementMsgBody.getChild(MODIFIERS,
                Namespace.getNamespace(ONT_NAMESPACE)); // get a copy of the <concepts> tag
        Element modifierTag = (Element) ((Element) modifiersTag.getContent(DataUtils.makeTagFilter(MODIFIER))
                .get(0)).clone(); // we expect only 1 modifier, so we grab the first one         
        modifierTag.detach();

        // add the modifierXML as a child to the <concpet> element in incompleteXMLDoc
        Element dndTag = (Element) incompleteXMLDoc.getContent(DataUtils.DRAG_AND_DROP_TAG_FILTER).get(0);
        Element conceptsTag = (Element) dndTag.getContent(DataUtils.CONCEPTS_TAG_FILTER).get(0);
        Element conceptTag = (Element) conceptsTag.getContent(DataUtils.makeTagFilter(CONCEPT)).get(0);
        conceptTag.removeChild(MODIFIER); // remove the incomplete modifier tag if it exists         
        conceptTag.addContent(modifierTag); // add the complete version
        //conceptTag.removeChild( QueryConceptTreeNodeData.TAG_IS_XML_COMPLETE ); // remove <isXMLComplete> if it exists

        // find the <ont:concept> node and set its supplemental <isXMLComplete> tag to "true"
        Element isXMLCoompleteTag = new Element(QueryConceptTreeNodeData.TAG_IS_XML_COMPLETE); // mark the concept as having a complete XML, add the supplemental tag
        isXMLCoompleteTag.setText(DataConst.TRUE);
        conceptTag.addContent(isXMLCoompleteTag);

        // get a String representation of the XML and set it as the originalXML for this node.
        StringWriter strWriter = new StringWriter();
        DataUtils.prettyPrintXMLDoc(incompleteXMLDoc, strWriter);
        this.finalizeOriginalXML(strWriter.toString()); // set and finalize originalXML

        System.err.println("Completed Modifier  XML: "); // bugbug:
        System.err.println(strWriter.toString()); // bugbug:         
        //System.err.println("Updated ModifierData ");

        strWriter.close();

        // return the DOM document for good measure.
        return incompleteXMLDoc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.clough.android.androiddbviewer.ADBVApplication.java

@Override
public void onCreate() {
    super.onCreate();

    // Getting user configured(custom) SQLiteOpenHelper instance.
    sqliteOpenHelper = getDataBase();/* www .j a  v a 2 s.  c om*/

    // getDataBase() could return a null
    if (sqliteOpenHelper != null) {

        // Background operation of creating the server socket.
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // Server socket re create when device is being disconnected or
                    // when AndroidDBViewer desktop application is being closed.
                    // Creating server socket will exit when
                    // android application runs in low memory or when
                    // android application being terminated due some reasons.
                    l1: while (flag) {
                        serverSocket = new ServerSocket(1993);
                        socket = serverSocket.accept();
                        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        pw = new PrintWriter(socket.getOutputStream(), true);

                        // Keeps a continuous communication between android application and
                        // AndroidDBViewer desktop application through IO streams of the accepted socket connection.
                        // There will be continuous data parsing between desktop application and android application.
                        // Identification of device being disconnected or desktop application being closed will be determined
                        // only when there is a NULL data being received.
                        l2: while (flag) {

                            // Format of the parsing data string is JSON, a content of a 'Data' instance
                            String requestJSONString = br.readLine();

                            if (requestJSONString == null) {

                                // Received a null response from desktop application, due to disconnecting the
                                // device or closing the AndroidDBViewer desktop application.
                                // Therefore, closing all current connections and streams to re create the server
                                // socket so that desktop application can connect in it's next run.

                                // Device disconnection doesn't produce an IOException.
                                // Also, even after calling
                                // socket.close(), socket.shutdownInput() and socket.shutdownOutput()
                                // within a shutdown hook in desktop application, the socket connection
                                // in this async task always gives
                                // socket.isConnected() as 'true' ,
                                // socket.isClosed() as 'false' ,
                                // socket.isInputShutdown() as 'false' and
                                // socket.isOutputShutdown() as 'false' .
                                // But, bufferedReader.readLine() starts returning 'null' continuously.
                                // So, inorder to desktop application to connect with the device again,
                                // there should be a ServerSocket waiting to accept a socket connection, in device.
                                closeConnection();
                                continue l1;
                            } else {

                                // Received a valid response from the desktop application.
                                Data data;
                                try {

                                    // Converting received request to a 'Data' instance.
                                    data = new Data(new JSONObject(requestJSONString));
                                    int status = data.getStatus();
                                    if (status == Data.CONNECTION_REQUEST) {

                                        // Very first request from desktop application to
                                        // establish the connection and setting the response as
                                        // connection being accepted.
                                        data.setStatus(Data.CONNECTION_ACCEPTED);
                                    } else if (status == Data.LIVE_CONNECTION) {

                                        // When there is no user interaction in desktop application,
                                        // data being passed from desktop application to android
                                        // application with the status of LIVE_CONNECTION, and the
                                        // same data send again to the desktop application from android application,
                                        // to notify that connection is still alive.
                                        // This exchange won't change until  there is a request from
                                        // desktop application with a different status.
                                    } else if (status == Data.QUERY) {

                                        // Requesting to perform a query execution.

                                        String result = "No result";
                                        try {

                                            // Performing select, insert, delete and update queries.
                                            Cursor cursor = sqliteOpenHelper.getWritableDatabase()
                                                    .rawQuery(data.getQuery(), null);

                                            // Flag to identify the firs move of the cursor
                                            boolean firstTime = true;

                                            int columnCount = 0;

                                            // JSONArray to hold the all JSONObjects, created per every row
                                            // of the result returned, executing the given query.
                                            JSONArray jsonArray = new JSONArray();

                                            // Moving the cursor to the next row of retrieved result
                                            // after executing the requested query.
                                            while (cursor.moveToNext()) {

                                                if (firstTime) {

                                                    // Column count of the result returned, executing the given query.
                                                    columnCount = cursor.getColumnCount();
                                                    firstTime = false;
                                                }

                                                // JOSNObject to hold the values of a single row
                                                JSONObject jsonObject = new JSONObject();
                                                for (int i = 0; i < columnCount; i++) {
                                                    int columnType = cursor.getType(i);
                                                    String columnName = cursor.getColumnName(i);
                                                    if (columnType == Cursor.FIELD_TYPE_STRING) {
                                                        jsonObject.put(columnName, cursor.getString(i));
                                                    } else if (columnType == Cursor.FIELD_TYPE_BLOB) {
                                                        jsonObject.put(columnName,
                                                                cursor.getBlob(i).toString());
                                                    } else if (columnType == Cursor.FIELD_TYPE_FLOAT) {
                                                        jsonObject.put(columnName,
                                                                String.valueOf(cursor.getFloat(i)));
                                                    } else if (columnType == Cursor.FIELD_TYPE_INTEGER) {
                                                        jsonObject.put(columnName,
                                                                String.valueOf(cursor.getInt(i)));
                                                    } else if (columnType == Cursor.FIELD_TYPE_NULL) {
                                                        jsonObject.put(columnName, "NULL");
                                                    } else {
                                                        jsonObject.put(columnName, "invalid type");
                                                    }
                                                }
                                                jsonArray.put(jsonObject);
                                            }
                                            result = jsonArray.toString();
                                            cursor.close();
                                        } catch (Exception e) {

                                            // If SQL error is occurred when executing the requested query,
                                            // error content will be the response to the desktop application.
                                            StringWriter sw = new StringWriter();
                                            PrintWriter epw = new PrintWriter(sw);
                                            e.printStackTrace(epw);
                                            result = sw.toString();
                                            epw.close();
                                            sw.close();
                                        } finally {
                                            data.setResult(result);
                                        }
                                    } else if (status == Data.DEVICE_NAME) {

                                        // Requesting device information
                                        data.setResult(Build.BRAND + " " + Build.MODEL);
                                    } else if (status == Data.APPLICATION_ID) {

                                        // Requesting application id (package name)
                                        data.setResult(getPackageName());
                                    } else if (status == Data.DATABASE_NAME) {

                                        // Requesting application database name.
                                        // Will provide the database name according
                                        // to the SQLiteOpenHelper user provided
                                        data.setResult(sqliteOpenHelper.getDatabaseName());
                                    } else {

                                        // Unidentified request state.
                                        closeConnection();
                                        continue l1;
                                    }
                                    String responseJSONString = data.toJSON().toString();
                                    pw.println(responseJSONString);
                                } catch (JSONException e) {

                                    // Response couldn't convert to a 'Data' instance.
                                    // Desktop application will be notified to close the application.
                                    closeConnection();
                                    continue l1;
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    // Cannot create a server socket. Letting background process to end.
                }
            }
        }).start();
    }
}

From source file:com.hypirion.io.PipeTest.java

/**
 * Test that multiple pipes running concurrently won't leave any chars
 * behind./*from  www .  ja  v a2s .c  o m*/
 */
@Test(timeout = 1000)
public void testConcurrentReaderPiping() throws Exception {
    final int charCount = 30;
    final char[] vals = "123456789".toCharArray();
    final int n = vals.length;
    Reader[] readers = new Reader[n];
    // Generate n readers with charCount equal elements in them.
    for (int i = 0; i < n; i++) {
        String s = "";
        for (int j = 0; j < charCount; j++) {
            s += vals[i];
        }
        StringReader sr = new StringReader(s);
        readers[i] = new SlowReader(sr);
    }
    StringWriter wrt = new StringWriter();
    Pipe[] pipes = new Pipe[n];
    for (int i = 0; i < n; i++) {
        pipes[i] = new Pipe(readers[i], wrt);
    }
    for (int i = 0; i < n; i++) {
        pipes[i].start();
    }
    for (int i = 0; i < n; i++) {
        pipes[i].join();
        readers[i].close();
    }

    // Count up elements and ensure that we've got the correct amount of
    // characters of each type.
    String out = wrt.toString();
    char[] output = out.toCharArray();
    wrt.close();
    for (char v : vals) {
        int sum = 0;
        for (char c : output) {
            if (c == v) {
                sum++;
            }
        }
        assertEquals(charCount, sum);
    }
}

From source file:org.apache.wiki.search.LuceneSearchProvider.java

/**
 * @param att Attachment to get content for. Filename extension is used to determine the type of the attachment.
 * @return String representing the content of the file.
 * FIXME This is a very simple implementation of some text-based attachment, mainly used for testing.
 * This should be replaced /moved to Attachment search providers or some other 'pluggable' wat to search attachments
 */// w  ww .j  av a 2 s . c  o  m
protected String getAttachmentContent(Attachment att) {
    AttachmentManager mgr = m_engine.getAttachmentManager();
    //FIXME: Add attachment plugin structure

    String filename = att.getFileName();

    boolean searchSuffix = false;
    for (String suffix : SEARCHABLE_FILE_SUFFIXES) {
        if (filename.endsWith(suffix)) {
            searchSuffix = true;
        }
    }

    if (searchSuffix) {
        InputStream attStream;

        try {
            attStream = mgr.getAttachmentStream(att);

            StringWriter sout = new StringWriter();
            FileUtil.copyContents(new InputStreamReader(attStream), sout);

            attStream.close();
            sout.close();

            return sout.toString();
        } catch (ProviderException e) {
            log.error("Attachment cannot be loaded", e);
            return null;
        } catch (IOException e) {
            log.error("Attachment cannot be loaded", e);
            return null;
        }
    }

    return null;
}

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

/**
 * This method triggers the shipping label generation process
 *///from  www .  ja  v  a 2s  . c o  m
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:com.webcohesion.enunciate.modules.java_xml_client.JavaXMLClientModule.java

/**
 * Processes the specified template with the given model.
 *
 * @param templateURL The template URL.//from   w  ww  .j  a va  2 s  . c o m
 * @param model       The root model.
 */
public String processTemplate(URL templateURL, Object model) throws IOException, TemplateException {
    debug("Processing template %s.", templateURL);
    Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);

    configuration.setTemplateLoader(new URLTemplateLoader() {
        protected URL getURL(String name) {
            try {
                return new URL(name);
            } catch (MalformedURLException e) {
                return null;
            }
        }
    });

    configuration.setTemplateExceptionHandler(new TemplateExceptionHandler() {
        public void handleTemplateException(TemplateException templateException, Environment environment,
                Writer writer) throws TemplateException {
            throw templateException;
        }
    });

    configuration.setLocalizedLookup(false);
    configuration.setDefaultEncoding("UTF-8");
    configuration.setObjectWrapper(new JavaXMLClientObjectWrapper());
    Template template = configuration.getTemplate(templateURL.toString());
    StringWriter unhandledOutput = new StringWriter();
    template.process(model, unhandledOutput);
    unhandledOutput.close();
    return unhandledOutput.toString();
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static String transformXml(Transformer t, Source s) throws TransformerException, IOException {

    StringWriter out = new StringWriter(getBufSize());
    transformXml(t, s, out);/*from ww  w .  j a  va 2s  . com*/
    out.close();

    return (out.getBuffer().toString());

}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase.java

public void migrateDisplayModel(UpdateSettings settings) throws Exception {
    log.debug("Beginning migration of display model");
    OntModel displayModel = settings.getDisplayModel();
    Model addStatements = ModelFactory.createDefaultModel();
    Model removeStatements = ModelFactory.createDefaultModel();
    //remove old tbox and display metadata statements and add statements from new versions
    replaceTboxAndDisplayMetadata(displayModel, addStatements, removeStatements, settings);
    //Update statements for data getter class types that have changed in 1.5 
    updateDataGetterClassNames(displayModel, addStatements, removeStatements);
    //add cannot delete flags to pages that shouldn't allow deletion on page list
    addCannotDeleteFlagDisplayModel(displayModel, addStatements, removeStatements);
    //removes requiresTemplate statement for people page
    updatePeoplePageDisplayModel(displayModel, addStatements, removeStatements);
    //add page list
    addPageListDisplayModel(displayModel, addStatements, removeStatements, settings);
    //update data getter labels
    updateDataGetterLabels(displayModel, addStatements, removeStatements, settings);

    displayModel.enterCriticalSection(Lock.WRITE);
    try {//  w  w w  .j  av  a 2 s.c  o  m
        if (log.isDebugEnabled()) {
            StringWriter sw = new StringWriter();
            addStatements.write(sw, "N3");
            log.debug("Statements to be added are: ");
            log.debug(sw.toString());
            sw.close();
            sw = new StringWriter();
            removeStatements.write(sw, "N3");
            log.debug("Statements to be removed are: ");
            log.debug(sw.toString());
            sw.close();
        }
        displayModel.remove(removeStatements);
        displayModel.add(addStatements);
    } finally {
        displayModel.leaveCriticalSection();
    }
}