Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

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

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessageFactory.java

/**
 * @see org.gbif.portal.util.mhf.message.MessageFactory#build(java.io.InputStream)
 *///from  www. j  ava  2 s . co m
public Message build(InputStream rawDataStream) throws MessageParseException {
    try {
        SAXReader xmlReader = new SAXReader();
        return new XMLMessage(xmlReader.read(rawDataStream));
    } catch (DocumentException e) {
        try {
            StringWriter sw = new StringWriter();
            int c;
            while ((c = rawDataStream.read()) != -1) {
                sw.write(c);
            }
            logger.warn("Unparsed data: " + sw.toString());
        } catch (IOException e1) {
            logger.warn("Unable to even read the stream... " + e1.getMessage());
        }

        throw new MessageParseException("RawXml is not parsable: " + e.getMessage(), e);
    }
}

From source file:org.opennms.upgrade.implementations.ServiceConfig1701MigratorOffline.java

@Override
public void execute() throws OnmsUpgradeException {
    try {/* w w w .  j  a v  a2s. com*/
        ServiceConfiguration currentCfg = JaxbUtils.unmarshal(ServiceConfiguration.class, configFile);

        log("Current configuration: " + currentCfg.getServiceCount() + " services.\n");

        for (int i = currentCfg.getServiceCount() - 1; i >= 0; i--) {
            final Service localSvc = currentCfg.getService(i);
            final String name = localSvc.getName();
            if (oldServices.contains(name)) {
                log("Removing old service %s\n", name);
                currentCfg.getServiceCollection().remove(i);
            }
        }

        log("New configuration: " + currentCfg.getServiceCount() + " services.\n");

        // now remove 
        final StringWriter sw = new StringWriter();
        sw.write("<?xml version=\"1.0\"?>\n");
        sw.write("<!-- NOTE!!!!!!!!!!!!!!!!!!!\n");
        sw.write("The order in which these services are specified is important - for example, Eventd\n");
        sw.write("will need to come up last so that none of the event topic subcribers loose any event.\n");
        sw.write("\nWhen splitting services to run on mutiple VMs, the order of the services should be\n");
        sw.write("maintained\n");
        sw.write("-->\n");
        JaxbUtils.marshal(currentCfg, sw);
        final FileWriter fw = new FileWriter(configFile);
        fw.write(sw.toString());
        fw.close();
    } catch (Exception e) {
        throw new OnmsUpgradeException("Can't fix services configuration because " + e.getMessage(), e);
    }
}

From source file:org.eclipse.jubula.client.cmd.JobConfiguration.java

/**
 * creates the job passend to command Line client
 * @param configFile File/*from   w w  w.j  av  a 2 s. c o  m*/
 * @throws IOException Error
 * @return Jobconfiguration
 */
public static JobConfiguration initJob(File configFile) throws IOException {
    JobConfiguration job;
    if (configFile != null) {
        // Create JobConfiguration from xml
        BufferedReader in = null;
        StringWriter writer = new StringWriter();
        try {
            in = new BufferedReader(new FileReader(configFile));
            String line = null;
            while ((line = in.readLine()) != null) {
                writer.write(line);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        String xml = writer.toString();
        job = JobConfiguration.readFromXML(xml);
    } else {
        // or create an emty JobConfiguration
        job = new JobConfiguration();
    }
    return job;
}

From source file:org.powertac.common.TariffSpecificationTests.java

@Test
public void testXmlSerialization() {
    Rate r = new Rate().withValue(-0.121).withDailyBegin(new DateTime(2011, 1, 1, 6, 0, 0, 0, DateTimeZone.UTC))
            .withDailyEnd(new DateTime(2011, 1, 1, 8, 0, 0, 0, DateTimeZone.UTC)).withTierThreshold(100.0);
    RegulationRate rr = new RegulationRate().withUpRegulationPayment(.05).withDownRegulationPayment(-.05)
            .withResponse(RegulationRate.ResponseTime.SECONDS);
    TariffSpecification spec = new TariffSpecification(broker, PowerType.CONSUMPTION).withMinDuration(20000l)
            .withSignupPayment(35.0).withPeriodicPayment(-0.05).addSupersedes(42l).addRate(r).addRate(rr);

    XStream xstream = new XStream();
    xstream.autodetectAnnotations(true);
    StringWriter serialized = new StringWriter();
    serialized.write(xstream.toXML(spec));
    //    System.out.println(serialized.toString());
    TariffSpecification xspec = (TariffSpecification) xstream.fromXML(serialized.toString());
    assertNotNull("deserialized something", xspec);
    //assertEquals("correct match", spec, xspec);
    assertEquals("correct signup", 35.0, xspec.getSignupPayment(), 1e-6);
    List<Long> supersedes = xspec.getSupersedes();
    assertNotNull("non-empty supersedes list", supersedes);
    assertEquals("one entry", 1, supersedes.size());
    assertEquals("correct entry", new Long(42l), supersedes.get(0));
    Rate xr = (Rate) xspec.getRates().get(0);
    assertNotNull("rate present", xr);
    assertTrue("correct rate type", xr.isFixed());
    assertEquals("correct rate value", -0.121, xr.getMinValue(), 1e-6);
    RegulationRate xrr = (RegulationRate) xspec.getRegulationRates().get(0);
    assertNotNull("rate present", xrr);
    assertEquals("correct up-reg rate", .05, xrr.getUpRegulationPayment(), 1e-6);
    assertEquals("correct down-reg rate", -.05, xrr.getDownRegulationPayment(), 1e-6);
    assertEquals("correct response time", RegulationRate.ResponseTime.SECONDS, xrr.getResponse());
}

From source file:com.ikon.util.MailUtils.java

/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 *//*from w w w  . j a v  a 2 s .c  o m*/
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();

    // Prepare a request object
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] { new NameValuePair("url", fullUrl) });
    httpclient.executeMethod(method);
    InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
    StringWriter sw = new StringWriter();
    int c;
    while ((c = isr.read()) != -1)
        sw.write(c);
    isr.close();
    method.releaseConnection();

    return sw.toString();
}

From source file:$.ExampleResource.java

/**
     * Default view for the base path.//from w w  w .j a v  a2  s.  com
     *
     * @param context
     * @return
     * @throws IOException
     */
    @GET
    @Produces(MediaType.TEXT_HTML)
    public String get(@Context ServletContext context) throws IOException {
        InputStream is = context.getResourceAsStream("/index.html");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringWriter sw = new StringWriter();
        String text = "";

        while ((text = reader.readLine()) != null) {
            sw.write(text);
        }
        return sw.toString();
    }

From source file:HtmlUtils.java

public String getBR(int lines) {

    StringWriter lineBR = new StringWriter();
    String lineBRs = new String();

    for (int i = 0; i <= lines; i++) {
        lineBR.write("<BR>\n");
    }//from  w ww  .  j av  a  2s. c  o  m
    lineBRs = lineBR.toString();

    return lineBRs;
}

From source file:org.opennms.upgrade.implementations.EOLServiceConfigMigratorOffline.java

@Override
public void execute() throws OnmsUpgradeException {
    final String[] eol = { "OpenNMS:Name=Linkd", "OpenNMS:Name=Xmlrpcd", "OpenNMS:Name=XmlrpcProvisioner",
            "OpenNMS:Name=AccessPointMonitor" };

    try {//from   w ww .ja v  a2  s.  c o  m
        final ServiceConfiguration currentCfg = JaxbUtils.unmarshal(ServiceConfiguration.class, configFile);

        // Remove any end-of-life'd daemons from service configuration
        for (final String serviceName : eol) {
            final Service eolService = getService(currentCfg, serviceName);
            if (eolService == null) {
                continue;
            }
            final String eolServiceName = eolService.getName();
            if (eolServiceName.equals(serviceName)) {
                final String displayName = serviceName.replace("OpenNMS:Name=", "");
                log("Disabling EOL service: " + displayName + "\n");
                eolService.setEnabled(false);
            }
        }

        final StringWriter sw = new StringWriter();
        sw.write("<?xml version=\"1.0\"?>\n");
        sw.write("<!-- NOTE!!!!!!!!!!!!!!!!!!!\n");
        sw.write("The order in which these services are specified is important - for example, Eventd\n");
        sw.write("will need to come up last so that none of the event topic subcribers loose any event.\n");
        sw.write("\nWhen splitting services to run on mutiple VMs, the order of the services should be\n");
        sw.write("maintained\n");
        sw.write("-->\n");
        JaxbUtils.marshal(currentCfg, sw);
        final FileWriter fw = new FileWriter(configFile);
        fw.write(sw.toString());
        fw.close();
    } catch (final Exception e) {
        throw new OnmsUpgradeException("Can't fix services configuration because " + e.getMessage(), e);
    }
}

From source file:mobac.program.model.Atlas.java

public String getToolTip() {
    StringWriter sw = new StringWriter(1024);
    sw.write("<html>");
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_atlas_title"));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_atlas_name", StringEscapeUtils.escapeHtml4(name)));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_atlas_layer", layers.size()));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_atlas_format", outputFormat.toString()));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_max_tile", calculateTilesToDownload()));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_area_start",
            Utilities.prettyPrintLatLon(getMaxLat(), true), Utilities.prettyPrintLatLon(getMinLon(), false)));
    sw.write(I18nUtils.localizedStringForKey("lp_atlas_info_area_end",
            Utilities.prettyPrintLatLon(getMinLat(), true), Utilities.prettyPrintLatLon(getMaxLon(), false)));
    sw.write("</html>");
    return sw.toString();
}

From source file:com.jbrisbin.vpc.jobsched.batch.BatchMessageConverter.java

public Object fromMessage(Message message) throws MessageConversionException {
    MessageProperties props = message.getMessageProperties();
    if (isAuthorized(props) && props.getContentType().equals("application/zip")) {
        BatchMessage msg = new BatchMessage();
        msg.setId(new String(props.getCorrelationId()));
        String timeout = "2";
        if (props.getHeaders().containsKey("timeout")) {
            timeout = props.getHeaders().get("timeout").toString();
        }//from  ww w .  ja va 2 s .c  o  m
        msg.setTimeout(Integer.parseInt(timeout));

        ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(message.getBody()));
        ZipEntry zentry;
        try {
            while (null != (zentry = zin.getNextEntry())) {
                byte[] buff = new byte[4096];
                StringWriter json = new StringWriter();
                for (int bytesRead = 0; bytesRead > -1; bytesRead = zin.read(buff)) {
                    json.write(new String(buff, 0, bytesRead));
                }
                msg.getMessages().put(zentry.getName(), json.toString());
            }
        } catch (IOException e) {
            throw new MessageConversionException(e.getMessage(), e);
        }

        return msg;
    } else {
        throw new MessageConversionException("Invalid security key.");
    }
}