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:io.github.microcks.web.ResourceController.java

@RequestMapping(value = "/resources/{serviceId}/{resourceType}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getServiceResource(@PathVariable("serviceId") String serviceId,
        @PathVariable("resourceType") String resourceType, HttpServletResponse response) {
    log.info("Requesting {} resource for service {}", resourceType, serviceId);

    Service service = serviceRepository.findOne(serviceId);
    if (service != null && ServiceType.GENERIC_REST.equals(service.getType())) {
        // Prepare HttpHeaders.
        InputStream stream = null;
        String resource = findResource(service);
        HttpHeaders headers = new HttpHeaders();

        // Get the correct template depending on resource type.
        if (SWAGGER_20.equals(resourceType)) {
            org.springframework.core.io.Resource template = new ClassPathResource("templates/swagger-2.0.json");
            try {
                stream = template.getInputStream();
            } catch (IOException e) {
                log.error("IOException while reading swagger-2.0.json template", e);
            }//from  ww w.j  ava2 s. c  o  m
            headers.setContentType(MediaType.APPLICATION_JSON);
        } else if (OPENAPI_30.equals(resourceType)) {
            org.springframework.core.io.Resource template = new ClassPathResource("templates/openapi-3.0.yaml");
            try {
                stream = template.getInputStream();
            } catch (IOException e) {
                log.error("IOException while reading openapi-3.0.yaml template", e);
            }
            headers.set("Content-Type", "text/yaml");
        }

        // Now process the stream, replacing patterns by value.
        if (stream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            StringWriter writer = new StringWriter();

            try (Stream<String> lines = reader.lines()) {
                lines.map(line -> replaceInLine(line, service, resource))
                        .forEach(line -> writer.write(line + "\n"));
            }
            return new ResponseEntity<>(writer.toString().getBytes(), headers, HttpStatus.OK);
        }
    }
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

From source file:org.springframework.web.servlet.resource.CssLinkResourceTransformer.java

@Override
public Resource transform(HttpServletRequest request, Resource resource,
        ResourceTransformerChain transformerChain) throws IOException {

    resource = transformerChain.transform(request, resource);

    String filename = resource.getFilename();
    if (!"css".equals(StringUtils.getFilenameExtension(filename))
            || resource instanceof GzipResourceResolver.GzippedResource) {
        return resource;
    }/*from  ww  w.java  2s.  c o m*/

    if (logger.isTraceEnabled()) {
        logger.trace("Transforming resource: " + resource);
    }

    byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
    String content = new String(bytes, DEFAULT_CHARSET);

    SortedSet<ContentChunkInfo> links = new TreeSet<>();
    for (LinkParser parser : this.linkParsers) {
        parser.parse(content, links);
    }

    if (links.isEmpty()) {
        if (logger.isTraceEnabled()) {
            logger.trace("No links found.");
        }
        return resource;
    }

    int index = 0;
    StringWriter writer = new StringWriter();
    for (ContentChunkInfo linkContentChunkInfo : links) {
        writer.write(content.substring(index, linkContentChunkInfo.getStart()));
        String link = content.substring(linkContentChunkInfo.getStart(), linkContentChunkInfo.getEnd());
        String newLink = null;
        if (!hasScheme(link)) {
            String absolutePath = toAbsolutePath(link, request);
            newLink = resolveUrlPath(absolutePath, request, resource, transformerChain);
        }
        if (logger.isTraceEnabled()) {
            if (newLink != null && !newLink.equals(link)) {
                logger.trace("Link modified: " + newLink + " (original: " + link + ")");
            } else {
                logger.trace("Link not modified: " + link);
            }
        }
        writer.write(newLink != null ? newLink : link);
        index = linkContentChunkInfo.getEnd();
    }
    writer.write(content.substring(index));

    return new TransformedResource(resource, writer.toString().getBytes(DEFAULT_CHARSET));
}

From source file:com.migratebird.script.ScriptContentHandle.java

public String getScriptContentsAsString(long maxNrChars) {
    try {/*  w w w . ja v a2s  . com*/
        InputStream inputStream = this.getScriptInputStream();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
            StringWriter stringWriter = new StringWriter();
            long count = 0;
            int c;
            while ((c = bufferedReader.read()) != -1) {
                stringWriter.write(c);
                if (++count >= maxNrChars) {
                    stringWriter.write("... <remainder of script is omitted>");
                    break;
                }
            }
            return stringWriter.toString();
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        return "<script content could not be retrieved>";
    }
}

From source file:com.npower.cp.xmlinventory.OTATemplateItem.java

/**
 * Set the content by filename./*  w  w w.j av  a2 s . co  m*/
 * The method will be called in Common Digester
 * @param filename
 * @throws IOException
 */
public void setFilename(String filename) throws IOException {
    if (StringUtils.isEmpty(filename)) {
        return;
    }
    String baseDir = System.getProperty(OTAInventoryImpl.CP_TEMPLATE_RESOURCE_DIR);
    File file = new File(baseDir, filename);
    Reader reader = new FileReader(file);
    StringWriter writer = new StringWriter();
    int c = reader.read();
    while (c > 0) {
        writer.write(c);
        c = reader.read();
    }
    this.content = writer.toString();
    reader.close();
}

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

@Test
public void xmlSerializationTest() {
    timeService.setCurrentTime(new DateTime(2011, 1, 10, 7, 0, 0, 0, DateTimeZone.UTC));
    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);

    XStream xstream = new XStream();
    xstream.processAnnotations(Rate.class);
    StringWriter serialized = new StringWriter();
    serialized.write(xstream.toXML(r));
    //System.out.println(serialized.toString());
    Rate xr = (Rate) xstream.fromXML(serialized.toString());
    assertNotNull("deserialized something", xr);
    ReflectionTestUtils.setField(xr, "timeService", timeService);
    assertEquals("correct value", 0.121, xr.getValue(), 1e-6);
    assertEquals("correct tier threshold", 100.0, xr.getTierThreshold(), 1e-6);
}

From source file:org.ofbiz.content.data.DataResourceWorker.java

public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale,
        Map<String, Object> templateContext, Delegator delegator, Appendable out, boolean cache)
        throws IOException, GeneralException {
    Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("context"));
    if (context == null) {
        context = FastMap.newInstance();
    }// w w  w . java  2s  .c  o m
    String webSiteId = (String) templateContext.get("webSiteId");
    if (UtilValidate.isEmpty(webSiteId)) {
        if (context != null)
            webSiteId = (String) context.get("webSiteId");
    }

    String https = (String) templateContext.get("https");
    if (UtilValidate.isEmpty(https)) {
        if (context != null)
            https = (String) context.get("https");
    }

    String rootDir = (String) templateContext.get("rootDir");
    if (UtilValidate.isEmpty(rootDir)) {
        if (context != null)
            rootDir = (String) context.get("rootDir");
    }

    String dataResourceId = dataResource.getString("dataResourceId");
    String dataResourceTypeId = dataResource.getString("dataResourceTypeId");

    // default type
    if (UtilValidate.isEmpty(dataResourceTypeId)) {
        dataResourceTypeId = "SHORT_TEXT";
    }

    // text types
    if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) {
        String text = dataResource.getString("objectInfo");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
    } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
        GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText")
                .where("dataResourceId", dataResourceId).cache(cache).queryOne();
        if (electronicText != null) {
            String text = electronicText.getString("textData");
            writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
        }

        // object types
    } else if (dataResourceTypeId.endsWith("_OBJECT")) {
        String text = (String) dataResource.get("dataResourceId");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);

        // resource type
    } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
        String text = null;
        URL url = FlexibleLocation.resolveLocation(dataResource.getString("objectInfo"));

        if (url.getHost() != null) { // is absolute
            InputStream in = url.openStream();
            int c;
            StringWriter sw = new StringWriter();
            while ((c = in.read()) != -1) {
                sw.write(c);
            }
            sw.close();
            text = sw.toString();
        } else {
            String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
            String sep = "";
            if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
                sep = "/";
            }
            String fixedUrlStr = prefix + sep + url.toString();
            URL fixedUrl = new URL(fixedUrlStr);
            text = (String) fixedUrl.getContent();
        }
        out.append(text);

        // file types
    } else if (dataResourceTypeId.endsWith("_FILE_BIN")) {
        writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
    } else if (dataResourceTypeId.endsWith("_FILE")) {
        String dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
        String objectInfo = dataResource.getString("objectInfo");

        if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) {
            renderFile(dataResourceTypeId, objectInfo, rootDir, out);
        } else {
            writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
        }
    } else {
        throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId
                + "] is not supported in renderDataResourceAsText");
    }
}

From source file:com.jaxio.celerio.util.IOUtil.java

/**
 * Write to a string the bytes read from an input stream.
 *
 * @param charset the charset used to read the input stream
 * @return the inputstream as a string//  w ww  .  ja  v  a  2 s.  c o m
 */
public String inputStreamToString(InputStream is, String charset) throws IOException {
    InputStreamReader isr = null;
    if (null == charset) {
        isr = new InputStreamReader(is);
    } else {
        isr = new InputStreamReader(is, charset);
    }
    StringWriter sw = new StringWriter();
    int c = -1;
    while ((c = isr.read()) != -1) {
        sw.write(c);
    }
    isr.close();
    return sw.getBuffer().toString();
}

From source file:com.ibm.sbt.test.lib.MockSerializer.java

public synchronized HttpResponse recordResponse(HttpResponse response) {
    try {/*from w  w w.j  a v  a  2  s .co m*/
        StringWriter out = new StringWriter();
        out.write("\n<response ");

        out.write("statusCode=\"");
        int statusCode = response.getStatusLine().getStatusCode();
        out.write(String.valueOf(statusCode).trim());
        out.write("\" ");
        out.write("statusReason=\"");
        String reasonPhrase = response.getStatusLine().getReasonPhrase();
        out.write(String.valueOf(reasonPhrase).trim());
        out.write("\">\n");
        out.write("<headers>");
        Header[] allHeaders = response.getAllHeaders();
        out.write(serialize(allHeaders));
        String serializedEntity = null;
        if (response.getEntity() != null) {
            out.write("</headers>\n<data><![CDATA[");
            serializedEntity = serialize(response.getEntity().getContent());
            serializedEntity = serializedEntity.replaceAll("<!\\[CDATA\\[", "\\!\\[CDATA\\[")
                    .replaceAll("\\]\\]>", "\\]\\]");
            out.write(serializedEntity);
            out.write("]]></data>\n</response>");
        } else {
            out.write("</headers>\n</response>");
        }
        out.flush();
        out.close();
        writeData(out.toString());

        return buildResponse(allHeaders, statusCode, reasonPhrase, serializedEntity);

    } catch (IOException e) {
        throw new UnsupportedOperationException(e);
    }
}

From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java

/** FIXME: refactor
 * Extract the content of a scitation.aip.org page.
 * (changed code from ScrapingContext.getContentAsString)
 * @param urlConn Connection to api page (from url.openConnection())
 * @param cookie Cookie for auth./*w  w  w  . j av  a2s  .c  o  m*/
 * @return Content of aip page.
 * @throws IOException
 */
private String getPageContent(HttpURLConnection urlConn, String cookie) throws IOException {

    urlConn.setAllowUserInteraction(true);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(false);
    urlConn.setUseCaches(false);
    urlConn.setFollowRedirects(true);
    urlConn.setInstanceFollowRedirects(false);
    urlConn.setRequestProperty("Cookie", cookie);

    urlConn.setRequestProperty("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
    urlConn.connect();

    // build content
    StringWriter out = new StringWriter();
    InputStream in = new BufferedInputStream(urlConn.getInputStream());
    int b;
    while ((b = in.read()) >= 0) {
        out.write(b);
    }

    urlConn.disconnect();
    in.close();
    out.flush();
    out.close();

    return out.toString();
}

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

@Test
public void xmlSerializationTestHc() {
    timeService.setCurrentTime(new DateTime(2011, 1, 10, 7, 0, 0, 0, DateTimeZone.UTC));
    Rate r = new Rate().withFixed(false).withExpectedMean(0.10)
            // applies from 6:00-8:00
            .withDailyBegin(new DateTime(2011, 1, 1, 6, 0, 0, 0, DateTimeZone.UTC))
            .withDailyEnd(new DateTime(2011, 1, 1, 8, 0, 0, 0, DateTimeZone.UTC)).withMaxCurtailment(0.4)
            .withTierThreshold(100.0);//  ww  w .  ja  v  a  2s.com
    ReflectionTestUtils.setField(r, "timeService", timeService);
    Instant now = timeService.getCurrentTime();
    //rate tomorrow at 6:00 = 0.22
    assertTrue("add rate", r.addHourlyCharge(new HourlyCharge(now.plus(TimeService.HOUR * 23), 0.22)));
    //rate tomorrow at 7:00 = 0.18
    assertTrue("add rate 2", r.addHourlyCharge(new HourlyCharge(now.plus(TimeService.HOUR * 24), 0.18)));

    // check original rates
    assertEquals("correct value now", 0.10, r.getValue(now), 1e-6);
    //assertEquals("correct value tomorrow at 6:00", 0.22, r.getValue(now.plus(TimeService.HOUR * 23)), 1e-6);
    //assertEquals("correct value tomorrow at 7:00", 0.18, r.getValue(now.plus(TimeService.HOUR * 24)), 1e-6);

    XStream xstream = new XStream();
    xstream.processAnnotations(Rate.class);
    StringWriter serialized = new StringWriter();
    serialized.write(xstream.toXML(r));
    //System.out.println(serialized.toString());
    Rate xr = (Rate) xstream.fromXML(serialized.toString());
    assertNotNull("deserialized something", xr);
    ReflectionTestUtils.setField(xr, "timeService", timeService);
    assertEquals("correct value", 0.10, xr.getValue(), 1e-6);
    assertEquals("correct curtailment", 0.4, xr.getMaxCurtailment(), 1e-6);
    assertEquals("correct tier threshold", 100.0, xr.getTierThreshold(), 1e-6);
    assertEquals("correct value tomorrow at 6:00", 0.22, xr.getValue(now.plus(TimeService.HOUR * 23)), 1e-6);
    assertEquals("correct value tomorrow at 7:00", 0.18, xr.getValue(now.plus(TimeService.HOUR * 24)), 1e-6);
}