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.opendatakit.briefcase.util.XmlManipulationUtils.java

public static final SubmissionManifest parseDownloadSubmissionResponse(Document doc) throws ParsingException {

    // and parse the document...
    List<MediaFile> attachmentList = new ArrayList<MediaFile>();
    Element rootSubmissionElement = null;
    String instanceID = null;/*from w w  w.j  a  v a 2s. co  m*/

    // Attempt parsing
    Element submissionElement = doc.getRootElement();
    if (!submissionElement.getName().equals("submission")) {
        String msg = "Parsing downloadSubmission reply -- root element is not <submission> :"
                + submissionElement.getName();
        logger.error(msg);
        throw new ParsingException(msg);
    }
    String namespace = submissionElement.getNamespace();
    if (!namespace.equalsIgnoreCase(NAMESPACE_OPENDATAKIT_ORG_SUBMISSIONS)) {
        String msg = "Parsing downloadSubmission reply -- root element namespace is incorrect:" + namespace;
        logger.error(msg);
        throw new ParsingException(msg);
    }
    int nElements = submissionElement.getChildCount();
    for (int i = 0; i < nElements; ++i) {
        if (submissionElement.getType(i) != Element.ELEMENT) {
            // e.g., whitespace (text)
            continue;
        }
        Element subElement = (Element) submissionElement.getElement(i);
        namespace = subElement.getNamespace();
        if (!namespace.equalsIgnoreCase(NAMESPACE_OPENDATAKIT_ORG_SUBMISSIONS)) {
            // someone else's extension?
            continue;
        }
        String name = subElement.getName();
        if (name.equalsIgnoreCase("data")) {
            // find the root submission element and get its instanceID attribute
            int nIdElements = subElement.getChildCount();
            for (int j = 0; j < nIdElements; ++j) {
                if (subElement.getType(j) != Element.ELEMENT) {
                    // e.g., whitespace (text)
                    continue;
                }
                rootSubmissionElement = (Element) subElement.getElement(j);
                break;
            }
            if (rootSubmissionElement == null) {
                throw new ParsingException("no submission body found in submissionDownload response");
            }

            instanceID = rootSubmissionElement.getAttributeValue(null, "instanceID");
            if (instanceID == null) {
                throw new ParsingException("instanceID attribute value is null");
            }
        } else if (name.equalsIgnoreCase("mediaFile")) {
            int nIdElements = subElement.getChildCount();
            String filename = null;
            String hash = null;
            String downloadUrl = null;
            for (int j = 0; j < nIdElements; ++j) {
                if (subElement.getType(j) != Element.ELEMENT) {
                    // e.g., whitespace (text)
                    continue;
                }
                Element mediaSubElement = (Element) subElement.getElement(j);
                name = mediaSubElement.getName();
                if (name.equalsIgnoreCase("filename")) {
                    filename = XFormParser.getXMLText(mediaSubElement, true);
                } else if (name.equalsIgnoreCase("hash")) {
                    hash = XFormParser.getXMLText(mediaSubElement, true);
                } else if (name.equalsIgnoreCase("downloadUrl")) {
                    downloadUrl = XFormParser.getXMLText(mediaSubElement, true);
                }
            }
            attachmentList.add(new MediaFile(filename, hash, downloadUrl));
        } else {
            logger.warn("Unrecognized tag inside submission: " + name);
        }
    }

    if (rootSubmissionElement == null) {
        throw new ParsingException("No submission body found");
    }
    if (instanceID == null) {
        throw new ParsingException("instanceID attribute value is null");
    }

    // write submission to a string
    StringWriter fo = new StringWriter();
    KXmlSerializer serializer = new KXmlSerializer();

    serializer.setOutput(fo);
    // setting the response content type emits the xml header.
    // just write the body here...
    // this has the xmlns of the submissions download, indicating that it
    // originated from a briefcase download. Might be useful for discriminating
    // real vs. recovered data?
    rootSubmissionElement.setPrefix(null, NAMESPACE_OPENDATAKIT_ORG_SUBMISSIONS);
    try {
        rootSubmissionElement.write(serializer);
        serializer.flush();
        serializer.endDocument();
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new ParsingException("Unexpected IOException: " + e.getMessage());
    }

    return new SubmissionManifest(instanceID, fo.toString(), attachmentList);
}

From source file:org.kalypso.ogc.sensor.view.actions.DumpStructureHandler.java

/**
 * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
 *//*from w  ww  .  j  a v a2s  .  c  om*/
@Override
public Object execute(final ExecutionEvent event) {
    final IEvaluationContext context = (IEvaluationContext) event.getApplicationContext();
    final Shell shell = (Shell) context.getVariable(ISources.ACTIVE_SHELL_NAME);
    final IWorkbenchPart part = (IWorkbenchPart) context.getVariable(ISources.ACTIVE_PART_NAME);
    final ObservationChooser chooser = (ObservationChooser) part.getAdapter(ObservationChooser.class);

    final IRepository rep = chooser.isRepository(chooser.getSelection());
    if (rep == null)
        return Status.OK_STATUS;

    final StringWriter writer = new StringWriter();

    final IRunnableWithProgress runnable = new IRunnableWithProgress() {
        @Override
        public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            monitor.beginTask(Messages.getString("org.kalypso.ogc.sensor.view.DumpStructureHandler.0"), 1000); //$NON-NLS-1$

            try {
                rep.dumpStructure(writer, monitor);
                writer.close();
            } catch (final IOException e) {
                throw new InvocationTargetException(e);
            } catch (final RepositoryException e) {
                throw new InvocationTargetException(e);
            } finally {
                IOUtils.closeQuietly(writer);

                monitor.done();
            }
        }
    };

    try {
        PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);

        final Clipboard clipboard = new Clipboard(shell.getDisplay());
        clipboard.setContents(new Object[] { writer.toString() },
                new Transfer[] { TextTransfer.getInstance() });
        clipboard.dispose();
    } catch (final InvocationTargetException e) {
        e.printStackTrace();

        MessageDialog.openWarning(shell,
                Messages.getString("org.kalypso.ogc.sensor.view.DumpStructureHandler.1"), //$NON-NLS-1$
                e.getLocalizedMessage());
    } catch (final InterruptedException ignored) {
        // empty
    }

    return Status.OK_STATUS;
}

From source file:gdv.xport.DatenpaketTest.java

/**
 * Test-Methode fuer {@link gdv.xport.Datenpaket#export(java.io.Writer)}.
 * Damit die Assert's der Satzlaenge stimmen, muessen wir das
 * End-of-Datensatz abschalten.//  w w w.  java  2 s.c  om
 *
 * @throws IOException falls z.B. die Platte voll ist
 */
@Test
@SkipTestOn(property = "SKIP_EXPORT_TEST")
public void testEmptyExport() throws IOException {
    Datenpaket empty = new Datenpaket();
    StringWriter swriter = new StringWriter(1024);
    empty.export(swriter);
    String data = swriter.toString();
    swriter.close();
    int expectedLength = 1024 + 4 * Config.getEOD().length();
    assertEquals(expectedLength, data.length());
    Vorsatz vorsatz = datenpaket.getVorsatz();
    assertEquals("2.1", vorsatz.getVersion(Bezeichner.NAME_VERSION_SATZART_0001));
    assertEquals("1.1", vorsatz.getVersion(Bezeichner.NAME_VERSION_SATZART_9999));
    Nachsatz nachsatz = datenpaket.getNachsatz();
    assertEquals(0, nachsatz.getAnzahlSaetze());
    assertEquals(0.0, nachsatz.getGesamtBeitrag().toDouble(), 0.001);
    assertEquals(0.0, nachsatz.getGesamtBeitragBrutto().toDouble(), 0.001);
    assertEquals(0.0, nachsatz.getVersicherungsLeistungen().toDouble(), 0.001);
    assertEquals(0.0, nachsatz.getSchadenbearbeitungsKosten().toDouble(), 0.001);
}

From source file:com.plusub.lib.other.LruDiskCache.java

private static String readFully(Reader reader) throws IOException {
    StringWriter writer = null;
    try {/*ww  w . ja  v a2 s.  c o  m*/
        writer = new StringWriter();
        char[] buffer = new char[1024];
        int count;
        while ((count = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, count);
        }
        return writer.toString();
    } finally {
        try {
            reader.close();
            writer.close();
        } catch (Throwable e) {
        }
    }
}

From source file:com.connexta.arbitro.TestUtil.java

/**
 * This creates the XACML request from a file
 *
 * @param rootDirectory   root directory of the  request files
 * @param versionDirectory   version directory of the  request files
 * @param requestId  request file name// w  ww.ja v  a 2  s . c  om
 * @return String or null if any error
 */
public static String createRequest(String rootDirectory, String versionDirectory, String requestId) {

    File file = new File(".");
    StringWriter writer = null;
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.REQUEST_DIRECTORY + File.separator + requestId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        DOMSource domSource = new DOMSource(doc);
        writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        //ignore any exception and return null
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("Error closing stream ", e);
                //ignore any exception and return null
            }
        }
    }
    return null;
}

From source file:com.bstek.dorado.web.loader.DoradoLoader.java

public synchronized void load(ServletContext servletContext) throws Exception {
    if (!preloaded) {
        throw new IllegalStateException("Can not load dorado services before base configurations loaded.");
    }/*from   ww  w  .j  a  va2s. c  o  m*/

    if (loaded) {
        throw new IllegalStateException("Dorado services already loaded.");
    }
    loaded = true;

    EngineStartupListenerManager.notifyStartup();

    ConsoleStartedMessagesOutputter consoleStartedMessagesOutputter = (ConsoleStartedMessagesOutputter) DoradoContext
            .getCurrent().getServiceBean("consoleStartedMessagesOutputter");
    StringWriter buffer = new StringWriter();
    try {
        consoleStartedMessagesOutputter.output(buffer);
    } finally {
        buffer.close();
    }
    DoradoContext.dispose();

    Timer timer = new Timer();
    timer.schedule(new ConsoleMessageTimerTask(buffer.toString()), 500L);
}

From source file:org.mxupdate.eclipse.properties.ProjectProperties.java

/**
 * Stores current values of the {@link #properties} in given
 * <code>_file</code>. If the <code>_file</code> does not exists, the file
 * is created./*from   w w w . j a v a 2  s.c o m*/
 *
 * @throws CoreException    if file could not be created or updated
 * @throws IOException      if properties could not be written
 * @see #PROP_FILE_NAME
 */
public void store() throws CoreException, IOException {
    final IFile file = this.project.getFile(ProjectProperties.PROP_FILE_NAME);
    file.refreshLocal(IResource.DEPTH_ZERO, null);
    if (!file.exists()) {
        file.create(new ByteArrayInputStream(new byte[] {}), true, null);
    }
    final StringWriter writer = new StringWriter();
    this.properties.store(writer, null);
    final String content = writer.getBuffer().toString();
    writer.close();

    file.setContents(new ByteArrayInputStream(content.getBytes(ProjectProperties.ENCODING)), true, false, null);
}

From source file:com.sangupta.resumemaker.export.HtmlExport.java

@Override
public void export(UserData userData, File exportFile) {
    Template template = engine.getTemplate(TEMPLATE_NAME);

    VelocityContext pageModel = getModel(userData);

    StringWriter writer = new StringWriter();
    try {/*ww w  . ja  va2s .  co  m*/
        template.merge(pageModel, writer);
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        String unformattedHTML = writer.toString();
        String formattedHTML = HtmlUtils.tidyHtml(unformattedHTML);
        FileUtils.write(exportFile, formattedHTML);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.facebook.notifications.sample.MainActivity.java

/**
 * Mock an example push notification bundle from one of our local example JSON files.
 * @param exampleId The example id of the asset to load
 * @return a bundle with the contents of the specified example id
 *///from   w w  w  . j  a va  2s .c om
@NonNull
private Bundle getBundle(int exampleId) {
    try {
        InputStream inputStream = getAssets().open("example" + exampleId + ".json");

        StringWriter output = new StringWriter();
        IOUtils.copy(inputStream, output, Charset.forName("UTF-8"));

        JSONObject json = new JSONObject(output.toString());

        Bundle bundle = new Bundle();
        bundle.putString("fb_push_card", json.getJSONObject("fb_push_card").toString());
        JSONObject pushPayload = json.optJSONObject("fb_push_payload");
        if (pushPayload != null) {
            bundle.putString("fb_push_payload", pushPayload.toString());
        }

        output.close();
        inputStream.close();

        return bundle;
    } catch (Exception ex) {
        Log.e(LOG_TAG, "Error while getting bundle", ex);
        return new Bundle();
    }
}

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

/**
 * Test that reading from multiple readers doesn't change or stop the
 * writer./*from www. j  a v a  2 s.c o  m*/
 */
@Test(timeout = 1000)
public void testReaderConcatenation() throws Exception {
    String input = "";
    StringWriter wrt = new StringWriter();
    for (int i = 0; i < 10; i++) {
        String thisInput = RandomStringUtils.random(3708);
        input += thisInput;
        StringReader rdr = new StringReader(thisInput);
        Pipe p = new Pipe(rdr, wrt);
        p.start();
        p.join();
        rdr.close();
    }
    String output = wrt.toString();
    wrt.close();
    assertEquals(input, output);
}