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.botlibre.util.Utils.java

/**
 * Strip the html tags from the text.//from   w  w w  . ja  v  a2  s.c  om
 */
public static String stripTags(String html) {
    if (html == null) {
        return "";
    }
    if ((html.indexOf('<') == -1) || (html.indexOf('>') == -1)) {
        return html;
    }
    StringWriter writer = new StringWriter();
    TextStream stream = new TextStream(html);
    while (!stream.atEnd()) {
        String text = stream.upTo('<');
        writer.write(text);
        int position = stream.getPosition();
        stream.skip();
        String word = stream.nextWord();
        if (word != null) {
            if (word.equals("p")) {
                writer.write("\n\n");
            } else if (word.equals("br")) {
                writer.write("\n");
            } else if (word.equals("div")) {
                writer.write("\n");
            }
            stream.skipTo('>');
            if (stream.atEnd()) {
                stream.setPosition(position);
                writer.write(stream.upToEnd());
            } else {
                stream.skip();
            }
        }
    }
    return writer.toString();
}

From source file:org.ambraproject.search.service.IndexingServiceImpl.java

@SuppressWarnings("unchecked")
@Override//from   w w  w  . java  2 s . co m
public void reindexAcademicEditors() throws Exception {
    log.info("Reindexing Academic Editors");
    List<AcademicEditorView> editors = this.raptorService.getAcademicEditor();

    Map<String, String> params = new HashMap<String, String>();
    params.put("separator", "\t");
    params.put("f.ae_subject.split", "true");
    params.put("f.ae_subject.separator", ";");

    StringWriter sw = new StringWriter();
    CSVWriter csvWriter = new CSVWriterBuilder(sw).entryConverter(new AcademicEditorConverter())
            .strategy(new CSVStrategy('\t', '\"', '#', false, true)).build();

    //Add the header row
    sw.write(
            "id\tae_name\tae_last_name\tae_institute\tae_country\tae_subject\tdoc_type\tcross_published_journal_key\n");

    csvWriter.writeAll(editors);

    String csvData = sw.toString();

    log.info("CSV data created @ {} ", csvData.length());

    //Post the updates
    this.solrHttpService.makeSolrPostRequest(params, csvData, true);

    //Delete old data
    this.solrHttpService.makeSolrPostRequest(Collections.<String, String>emptyMap(),
            "<delete><query>timestamp:[* TO NOW-1HOUR] AND doc_type:(academic_editor OR section_editor)</query></delete>",
            false);

    log.info("Reindexing Academic Editors complete");
}

From source file:org.commonjava.couch.io.CouchAppReader.java

public CouchApp readAppDefinition(final AppDescription description) throws IOException, CouchDBException {
    ClassLoader cloader = Thread.currentThread().getContextClassLoader();
    String appName = description.getAppName();

    CouchApp app = new CouchApp(appName, description);

    String appBase = APP_BASEPATH + description.getClasspathAppResource();

    String viewBase = appBase + VIEW_SUBPATH;

    Set<String> listing = description.getViewNames();
    if (listing != null) {
        for (String view : listing) {
            String mapPath = viewBase + view + MAP_JS;
            String reducePath = viewBase + view + REDUCE_JS;

            String map = null;//  w  ww  . j a  va  2s.  c o m

            InputStream in = cloader.getResourceAsStream(mapPath);
            if (in == null) {
                throw new CouchDBException(
                        "Cannot read view: %s in CouchDB application: %s (classpath resource: %s)", view,
                        appName, mapPath);
            }

            StringWriter sWriter = new StringWriter();
            try {
                List<String> lines = readLines(in);
                for (String line : lines) {
                    String test = line.trim();
                    if (test.startsWith("#") || test.startsWith("/*") || test.startsWith("*")
                            || test.startsWith("//")) {
                        continue;
                    }
                    sWriter.write(line);
                    sWriter.write('\n');
                }
            } finally {
                closeQuietly(in);
            }
            map = sWriter.toString();

            String reduce = null;

            in = cloader.getResourceAsStream(reducePath);
            sWriter = new StringWriter();
            if (in != null) {
                try {
                    copy(in, sWriter);
                } finally {
                    closeQuietly(in);
                }
                reduce = sWriter.toString();
            }

            app.addView(view, new CouchAppView(map, reduce));
        }
    }

    return app;
}

From source file:org.sakaiproject.tool.assessment.qti.helper.AuthoringXml.java

/**
 * get a template as a string from its input stream
 * @param templateName//from ww  w  .j  a v a 2s .com
 * @return the xml string
 */
public String getTemplateAsString(InputStream templateStream) {
    InputStreamReader reader;
    String xmlString = null;
    try {
        reader = new InputStreamReader(templateStream);
        StringWriter out = new StringWriter();
        int c;

        while ((c = reader.read()) != -1) {
            out.write(c);
        }

        reader.close();
        xmlString = (String) out.toString();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return xmlString;

}

From source file:com.fujitsu.dc.test.utils.Http.java

/**
 * ????.//from   w  w  w  .  j a  v a 2 s  . c  o  m
 * @return TResponse
 */
public TResponse returns() {
    BufferedReader br = null;
    try {
        // ???
        InputStreamReader isr = new InputStreamReader(is, CharEncoding.UTF_8);
        br = new BufferedReader(isr);
        String firstLine = br.readLine();
        firstLine = this.processParams(firstLine);
        String[] l1 = firstLine.split(" ");
        this.method = l1[0];
        this.path = l1[1];
        String protoVersion = l1[2];

        // Open
        this.url = new URL(baseUrl + this.path);
        try {
            this.socket = createSocket(this.url);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } catch (KeyStoreException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (CertificateException e) {
            throw new RuntimeException(e);
        }
        this.sIn = this.socket.getInputStream();
        this.sOut = this.socket.getOutputStream();
        this.sReader = new BufferedReader(new InputStreamReader(this.sIn, CharEncoding.UTF_8));
        this.sWriter = new BufferedOutputStream(this.sOut);

        // ?
        StringBuilder sb = new StringBuilder();
        sb.append(this.method);
        sb.append(" ");
        sb.append(this.url.getPath());
        if (this.url.getQuery() != null) {
            sb.append("?");
            sb.append(this.url.getQuery());
        }
        sb.append(" ");
        sb.append(protoVersion);
        this.sWriter.write(sb.toString().getBytes(CharEncoding.UTF_8));
        this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
        log.debug("Req Start -------");
        log.debug(sb.toString());

        // Header
        String line = null;
        String lastLine = null;
        int contentLengthLineNum = -1;
        List<String> lines = new ArrayList<String>();
        int i = 0;
        while ((line = br.readLine()) != null) {
            if (line.length() == 0) {
                break;
            }
            line = this.processParams(line);
            if (line.toLowerCase().startsWith(HttpHeaders.CONTENT_LENGTH.toLowerCase())) {
                // Content-Length???????????????????
                contentLengthLineNum = i;
            } else if (line.toLowerCase().startsWith(HttpHeaders.HOST.toLowerCase())) {
                line = line.replaceAll("\\?", this.url.getAuthority());
            }
            lines.add(line + CRLF);
            lastLine = line;
            i++;
        }

        // Version?
        lines.add("X-Dc-Version: " + DcCoreTestConfig.getCoreVersion() + CRLF);
        String body = null;
        // ????Break??????Body?????
        if (line != null) {
            log.debug("Req Body-------");
            i = 1;
            StringWriter sw = new StringWriter();
            int chr;
            while ((chr = br.read()) != -1) {
                sw.write((char) chr);
            }
            body = sw.toString();
            body = this.processParams(body);
            // Content-Length?
            if (contentLengthLineNum != -1) {
                String contentLength = lines.get(contentLengthLineNum).replaceAll("\\?",
                        String.valueOf(body.getBytes().length));
                lines.set(contentLengthLineNum, contentLength);
            }
        } else {
            if (this.paraBody != null) {
                log.debug("Req Body-------");
                // ?Body??
                String contentLength = lines.get(contentLengthLineNum).replaceAll("\\?",
                        String.valueOf(this.paraBody.length));
                lines.set(contentLengthLineNum, contentLength);
            } else {
                // ??????.
                if (lastLine.length() > 0) {
                    log.debug("one more CRLF");
                    this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
                }
            }
        }
        // Header??
        for (String l : lines) {
            this.sWriter.write(l.getBytes(CharEncoding.UTF_8));
            if (log.isDebugEnabled()) {
                l.replaceAll(CRLF, "");
                log.debug(l);
            }
        }
        // 
        this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
        // Body??
        if (body != null) {
            this.sWriter.write(body.getBytes(CharEncoding.UTF_8));
            log.debug(body);
        }
        // ?Body??
        if (this.paraBody != null) {
            this.sWriter.write(this.paraBody);
            this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
        }
        this.sWriter.flush();
        // ??
        TResponse ret = new TResponse(this.sReader);
        return ret;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
            if (this.sWriter != null) {
                this.sWriter.close();
            }
            if (this.sReader != null) {
                this.sReader.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:io.personium.test.utils.Http.java

/**
 * ????.//from  w  ww.j a  v  a 2 s . c o  m
 * @return TResponse
 */
public TResponse returns() {
    BufferedReader br = null;
    try {
        // ???
        InputStreamReader isr = new InputStreamReader(is, CharEncoding.UTF_8);
        br = new BufferedReader(isr);
        String firstLine = br.readLine();
        firstLine = this.processParams(firstLine);
        String[] l1 = firstLine.split(" ");
        this.method = l1[0];
        this.path = l1[1];
        String protoVersion = l1[2];

        // Open
        this.url = new URL(baseUrl + this.path);
        try {
            this.socket = createSocket(this.url);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        } catch (KeyStoreException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (CertificateException e) {
            throw new RuntimeException(e);
        }
        this.sIn = this.socket.getInputStream();
        this.sOut = this.socket.getOutputStream();
        this.sReader = new BufferedReader(new InputStreamReader(this.sIn, CharEncoding.UTF_8));
        this.sWriter = new BufferedOutputStream(this.sOut);

        // ?
        StringBuilder sb = new StringBuilder();
        sb.append(this.method);
        sb.append(" ");
        sb.append(this.url.getPath());
        if (this.url.getQuery() != null) {
            sb.append("?");
            sb.append(this.url.getQuery());
        }
        sb.append(" ");
        sb.append(protoVersion);
        this.sWriter.write(sb.toString().getBytes(CharEncoding.UTF_8));
        this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
        log.debug("Req Start -------");
        log.debug(sb.toString());

        // Header
        String line = null;
        String lastLine = null;
        int contentLengthLineNum = -1;
        List<String> lines = new ArrayList<String>();
        int i = 0;
        while ((line = br.readLine()) != null) {
            if (line.length() == 0) {
                break;
            }
            line = this.processParams(line);
            if (line.toLowerCase().startsWith(HttpHeaders.CONTENT_LENGTH.toLowerCase())) {
                // Content-Length???????????????????
                contentLengthLineNum = i;
            } else if (line.toLowerCase().startsWith(HttpHeaders.HOST.toLowerCase())) {
                line = line.replaceAll("\\?", this.url.getAuthority());
            }
            lines.add(line + CRLF);
            lastLine = line;
            i++;
        }

        // Version?
        lines.add("X-Personium-Version: " + PersoniumCoreTestConfig.getCoreVersion() + CRLF);
        String body = null;
        // ????Break??????Body?????
        if (line != null) {
            log.debug("Req Body-------");
            i = 1;
            StringWriter sw = new StringWriter();
            int chr;
            while ((chr = br.read()) != -1) {
                sw.write((char) chr);
            }
            body = sw.toString();
            body = this.processParams(body);
            // Content-Length?
            if (contentLengthLineNum != -1) {
                String contentLength = lines.get(contentLengthLineNum).replaceAll("\\?",
                        String.valueOf(body.getBytes().length));
                lines.set(contentLengthLineNum, contentLength);
            }
        } else {
            if (this.paraBody != null) {
                log.debug("Req Body-------");
                // ?Body??
                String contentLength = lines.get(contentLengthLineNum).replaceAll("\\?",
                        String.valueOf(this.paraBody.length));
                lines.set(contentLengthLineNum, contentLength);
            } else {
                // ??????.
                if (lastLine.length() > 0) {
                    log.debug("one more CRLF");
                    this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
                }
            }
        }
        // Header??
        for (String l : lines) {
            this.sWriter.write(l.getBytes(CharEncoding.UTF_8));
            if (log.isDebugEnabled()) {
                l.replaceAll(CRLF, "");
                log.debug(l);
            }
        }
        // 
        this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
        // Body??
        if (body != null) {
            this.sWriter.write(body.getBytes(CharEncoding.UTF_8));
            log.debug(body);
        }
        // ?Body??
        if (this.paraBody != null) {
            this.sWriter.write(this.paraBody);
            this.sWriter.write(CRLF.getBytes(CharEncoding.UTF_8));
        }
        this.sWriter.flush();
        // ??
        TResponse ret = new TResponse(this.sReader);
        return ret;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
            if (this.sWriter != null) {
                this.sWriter.close();
            }
            if (this.sReader != null) {
                this.sReader.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:edu.cornell.mannlib.semservices.service.impl.GemetService.java

/**
 * @param url/*from w ww . ja v a 2 s .c  o  m*/
 * @return
 */
protected String getGemetResults(String url) throws Exception {
    String results = new String();
    //System.out.println("url: "+url);
    try {

        StringWriter sw = new StringWriter();
        URL serviceUrl = new URL(url);

        BufferedReader in = new BufferedReader(new InputStreamReader(serviceUrl.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            sw.write(inputLine);
        }
        in.close();

        results = sw.toString();

    } catch (Exception ex) {
        logger.error("error occurred in servlet", ex);
        ex.printStackTrace();
        throw ex;
    }
    return results;
}

From source file:com.zenika.doclipser.api.DockerClientJavaApi.java

@Override
public void defaultBuildCommand(String eclipseProjectName, String dockerBuildContext) {
    File baseDir = new File(dockerBuildContext);
    InputStream response = dockerClient.buildImageCmd(baseDir).exec();
    StringWriter logwriter = new StringWriter();
    messageConsole.getDockerConsoleOut()
            .println(">>> Building " + dockerBuildContext + "/Dockerfile with default options");
    messageConsole.getDockerConsoleOut().println("");

    try {//from   w  w w. j av a 2 s  .co m
        messageConsole.getDockerConsoleOut().flush();
        LineIterator itr = IOUtils.lineIterator(response, "UTF-8");
        while (itr.hasNext()) {
            String line = itr.next();
            logwriter.write(line);
            messageConsole.getDockerConsoleOut().println(line);
            messageConsole.getDockerConsoleOut().flush();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(response);
    }

    messageConsole.getDockerConsoleOut().println("");
    messageConsole.getDockerConsoleOut().println("<<< Build ended");
}

From source file:org.auraframework.http.AuraResourceServlet.java

/**
 * Write out the manifest./*from www .j a v  a  2s  . c  o  m*/
 * 
 * This writes out the full manifest for an application so that we can use the AppCache.
 * 
 * The manifest contains CSS and JavaScript URLs. These specified resources are copied into the AppCache with the
 * HTML template. When the page is reloaded, the existing manifest is compared to the new manifest. If they are
 * identical, the resources are served from the AppCache. Otherwise, the resources are requested from the server and
 * the AppCache is updated.
 * 
 * @param request the request
 * @param response the response
 * @throws IOException if unable to write out the response
 */
private void writeManifest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    AuraContext context = Aura.getContextService().getCurrentContext();

    setNoCache(response);

    try {
        //
        // First, we make sure that the manifest is enabled.
        //
        if (!ManifestUtil.isManifestEnabled(request)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //
        // Now we validate the cookie, which includes loop detection.
        // this routine sets the response code.
        //
        if (!ManifestUtil.checkManifestCookie(request, response)) {
            return;
        }

        boolean appOk = false;

        DefDescriptor<? extends BaseComponentDef> descr = null;
        try {
            descr = context.getApplicationDescriptor();

            if (descr != null) {
                Aura.getDefinitionService().updateLoaded(descr);
                appOk = true;
            }
        } catch (QuickFixException qfe) {
            //
            // ignore qfe, since we really don't care... the manifest will be 404ed.
            // This will eventually cause the browser to give up. Note that this case
            // should almost never occur, as it requires the qfe to be introduced between
            // the initial request (which will not set a manifest if it gets a qfe) and
            // the manifest request.
            //
        } catch (ClientOutOfSyncException coose) {
            //
            // In this case, we want to force a reload... A 404 on the manifest is
            // supposed to handle this. we hope that the client will do the right
            // thing, and reload everything. Note that this case really should only
            // happen if the client already has content, and thus should be refreshing
            // However, there are very odd edge cases that we probably can't detect
            // without keeping server side state, such as the case that something
            // is updated between the initial HTML request and the manifest request.
            // Not sure what browsers will do in this case.
            //
        }

        if (!appOk) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //
        // This writes both the app and framework signatures into
        // the manifest, so that if either one changes, the
        // manifest will change. Note that in most cases, we will
        // write these signatures in multiple places, but we just
        // need to make sure that they are in at least one place.
        //
        Map<String, Object> attribs = Maps.newHashMap();
        String appUid = getContextAppUid();
        attribs.put(LAST_MOD,
                String.format("app=%s, FW=%s", appUid, Aura.getConfigAdapter().getAuraFrameworkNonce()));
        attribs.put(UID, appUid);
        StringWriter sw = new StringWriter();

        for (String s : getStyles()) {
            sw.write(s);
            sw.write('\n');
        }

        for (String s : getScripts()) {
            sw.write(s);
            sw.write('\n');
        }

        // Add in any application specific resources
        if (descr != null && descr.getDefType().equals(DefType.APPLICATION)) {
            ApplicationDef def = (ApplicationDef) descr.getDef();
            for (String s : def.getAdditionalAppCacheURLs()) {
                sw.write(s);
                sw.write('\n');
            }
        }

        attribs.put(RESOURCE_URLS, sw.toString());

        DefinitionService definitionService = Aura.getDefinitionService();
        InstanceService instanceService = Aura.getInstanceService();
        DefDescriptor<ComponentDef> tmplDesc = definitionService.getDefDescriptor("ui:manifest",
                ComponentDef.class);
        Component tmpl = instanceService.getInstance(tmplDesc, attribs);
        Aura.getRenderingService().render(tmpl, response.getWriter());
    } catch (Exception e) {
        Aura.getExceptionAdapter().handleException(e);
        // Can't throw exception here: to set manifest OBSOLETE
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.quatico.base.aem.test.api.setup.Tags.java

@Override
public String renderTag(TagSupport tag, PageContext pageContext, String body) throws Exception {
    StringWriter strWriter = new StringWriter();
    HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(new PrintWriter(strWriter, true));

    if (!mockingDetails(pageContext).isSpy()) {
        pageContext = spy(pageContext);/*from www. j  a  va 2 s. com*/
    }

    JspWriter jspWriter = new JspWriterImpl(response);
    doReturn(jspWriter).when(pageContext).getOut();
    tag.setPageContext(pageContext);

    if (Tag.EVAL_BODY_INCLUDE == tag.doStartTag()) {
        jspWriter.flush();
        strWriter.write(body);
    }
    jspWriter.flush();
    tag.doEndTag();
    jspWriter.flush();
    tag.release();
    return strWriter.toString();
}