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:edu.cornell.mannlib.semservices.service.impl.UMLSService.java

@Override
public List<Concept> getConcepts(String term) throws Exception {
    List<Concept> conceptList = new ArrayList<Concept>();

    String results = null;//from w ww  .  j  ava  2  s. c o  m
    String dataUrl = submissionUrl + "textToProcess=" + URLEncoder.encode(term, "UTF-8") + "&format=json";

    try {

        StringWriter sw = new StringWriter();
        URL rss = new URL(dataUrl);

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

        results = sw.toString();
        //System.out.println("results before processing: "+results);
        conceptList = processOutput(results);
        return conceptList;

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

From source file:org.jboss.test.cluster.classloader.leak.test.ClassloaderLeakTestBase.java

/**
 * FIXME Comment this/* w  w  w . ja v a2 s .  c  om*/
 * 
 * @param client
 * @param method
 * @param url
 * @param responseContent
 */
private void checkWebRequest(HttpClient client, GetMethod method, String url, String responseContent) {
    int responseCode = 0;
    try {
        responseCode = client.executeMethod(method);

        assertTrue("Get OK with url: " + url + " responseCode: " + responseCode,
                responseCode == HttpURLConnection.HTTP_OK);

        InputStream rs = method.getResponseBodyAsStream();
        InputStreamReader reader = new InputStreamReader(rs);
        StringWriter writer = new StringWriter();
        int c;
        while ((c = reader.read()) != -1)
            writer.write(c);

        String rsp = writer.toString();

        assertTrue("Response contains " + responseContent, rsp.indexOf(responseContent) >= 0);
    } catch (IOException e) {
        e.printStackTrace();
        fail("HttpClient executeMethod fails." + e.toString());
    } finally {
        method.releaseConnection();
    }
}

From source file:dk.clarin.tools.workflow.java

public static void got200(String result, bracmat BracMat, String filename, String jobID, InputStream input) {
    logger.debug("got200");
    /**/*from  w w  w.  j  a va  2 s  .  c  o  m*/
     * toolsdata$
     *
     * Return the full file system path to Tool's staging area.
     * The input can be a file name: this name is appended to the returned value.
     */
    String destdir = BracMat.Eval("toolsdata$");
    /**
     * toolsdataURL$
     *
     * Return the full URL to Tool's staging area.
     * The input can be a file name: this name is appended to the returned value.
     */
    //String toolsdataURL = BracMat.Eval("toolsdataURL$");
    try {
        byte[] buffer = new byte[4096];
        int n = -1;
        int N = 0;
        //int Nbuf = 0;
        OutputStream outputF = new FileOutputStream(destdir + FilenameNoMetadata(filename));
        StringWriter outputM = new StringWriter();

        boolean isTextual = false;
        String textable = BracMat.Eval("getJobArg$(" + result + "." + jobID + ".isText)");
        if (textable.equals("y"))
            isTextual = true;
        logger.debug("textable:" + (isTextual ? "ja" : "nej"));

        while ((n = input.read(buffer)) != -1) {
            if (n > 0) {
                N = N + n;
                //++Nbuf;
                outputF.write(buffer, 0, n);
                if (isTextual) {
                    String toWrite = new String(buffer, 0, n);
                    try {
                        outputM.write(toWrite);
                    } catch (Exception e) {
                        logger.error("Could not write to StringWriter. Reason:" + e.getMessage());
                    }
                }
            }
        }
        outputF.close();
        String requestResult = outputM.toString();

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(cal.getTime());
        logger.debug("Calling doneJob(" + result + "," + jobID + "," + date + ")");
        /**
         * doneJob$
         *
         * Marks a job as 'done' in jobs.table in jboss/server/default/data/tools
         * Constructs a CTBID from date, JobNr and jobID
         * Makes sure there is a row in table CTBs connecting
         *      JobNr, jobID, email and CTBID
         * Creates isDependentOf and isAnnotationOf relations
         * Affected tables:
         *      jobs.table
         *      CTBs.table
         *      relations.table
         * Arguments: jobNR, JobID, spangroup with annotation and date. 
         *
         * Notice that this function currently only can generate output of type 
         * TEIDKCLARIN_ANNO
         */
        String newResource = BracMat.Eval(
                "doneJob$(" + result + "." + jobID + "." + quote(requestResult) + "." + quote(date) + ")");
        // Create file plus metadata
        logger.debug("Going to write {}", destdir + Filename(filename));
        FileWriter fstream = new FileWriter(destdir + Filename(filename));
        BufferedWriter Out = new BufferedWriter(fstream);
        Out.write(newResource);
        Out.close();
        /**
         * relationFile$
         *
         * Create a relation file ready for deposition together with an annotation.
         *
         * Input: JobNr and jobID
         * Output: String that can be saved as a semicolon separated file.
         * Consulted tables:
         *      relations.table     (for relation type, ctb and ctbid
         *      CTBs.table          (for ContentProvider and CTBID)
         */
        String relations = BracMat.Eval("relationFile$(" + result + "." + jobID + ")");
        // Create relation file
        fstream = new FileWriter(destdir + FilenameRelations(filename));
        Out = new BufferedWriter(fstream);
        Out.write(relations);
        Out.close();
    } catch (Exception e) {//Catch exception if any
        logger.error("Could not write result to file. Aborting job " + jobID + ". Reason:" + e.getMessage());
        /**
         * abortJob$
         *
         * Abort, given a JobNr and a jobID, the specified job and all
         * pending jobs that depend on the output from the (now aborted) job.
         * Rather than removing the aborted jobs from the jobs.table list, they are
         * marked 'aborted'.
         * Result (as XML): a list of (JobNr, jobID, toolName, items)
         */
        /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
    }
}

From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java

/**
 * Parse string from input stream//from  ww w. j  a v  a  2s  .c  om
 * @param in
 * @return
 */
public String parseStringFromInputStream(InputStream in) {
    String output = null;
    try {
        // WORKAROUND cut the parameter name "request" of the stream
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringWriter sw = new StringWriter();
        int k;
        while ((k = br.read()) != -1) {
            sw.write(k);
        }
        output = sw.toString();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    return output;
}

From source file:org.jpublish.repository.web.WebRepository.java

/** Get the content from the given path.  Implementations of this method
should NOT merge the content using view renderer.
        //w ww. j ava2 s  .co m
@param path The relative content path
@return The content as a String
@throws Exception Any Exception
*/

public String get(String path) throws Exception {
    InputStream in = null;
    StringWriter out = null;
    try {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        in = conn.getInputStream();
        out = new StringWriter();

        int c = -1;
        while ((c = in.read()) != -1) {
            out.write((char) c);
        }

        return out.toString();
    } finally {
        IOUtilities.close(in);
        IOUtilities.close(out);
    }
}

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

@Override
public List<Concept> getConcepts(String term) throws Exception {
    List<Concept> conceptList = new ArrayList<Concept>();
    String results = null;/*from   w  w  w  .j a v a2 s  .  c o m*/
    String dataUrl = baseUri + "?q=" + URLEncoder.encode(term, "UTF-8")
            + "&q=cs%3Ahttp%3A%2F%2Fid.loc.gov%2Fauthorities%2Fsubjects" + "&format=XML";
    log.debug("dataURL " + dataUrl);

    try {

        StringWriter sw = new StringWriter();
        URL rss = new URL(dataUrl);

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

        results = sw.toString();
        log.debug(results);
    } catch (Exception ex) {
        log.error("error occurred in servlet", ex);
        return null;
    }

    if (StringUtils.isEmpty(results)) {
        return conceptList;
    }

    conceptList = processOutput(results);

    return conceptList;
}

From source file:org.botlibre.util.Utils.java

public static String displayTime(Date date) {
    if (date == null) {
        return "";
    }//from w w  w.j  a v a 2s.c o  m
    StringWriter writer = new StringWriter();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    writer.write(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)));
    writer.write(":");
    if (calendar.get(Calendar.MINUTE) < 10) {
        writer.write("0");
    }
    writer.write(String.valueOf(calendar.get(Calendar.MINUTE)));
    writer.write(":");
    if (calendar.get(Calendar.SECOND) < 10) {
        writer.write("0");
    }
    writer.write(String.valueOf(calendar.get(Calendar.SECOND)));

    return writer.toString();
}

From source file:edu.cornell.mannlib.vitro.webapp.search.externallookup.impl.SolrLookup.java

private String getSolrResults(String term) {
    String results = null;//w  ww.  ja  v  a2s.co m
    String queryTerm = this.getNameQuery(term);
    String solrURL = solrAPI + "q=" + queryTerm + "&" + jsonFormatParameter;
    try {

        StringWriter sw = new StringWriter();
        URL rss = new URL(solrURL);

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

        results = sw.toString();
        log.debug("Results string is " + results);
        // System.out.println("results before processing: "+results);

    } catch (Exception ex) {
        log.error("Exception occurred in retrieving results", ex);
        //ex.printStackTrace();
        return null;
    }
    return results;

}

From source file:org.josso.util.config.XUpdateConfigurationHandler.java

/**
 * This will scape all spetial chars like <, >, &, \, " and unicode chars.
 *///from w ww .j  a v  a2 s .  c o  m
public String unicodeEscape(String v) {

    StringWriter w = new StringWriter();

    int len = v.length();
    for (int j = 0; j < len; j++) {
        char c = v.charAt(j);
        switch (c) {
        case '&':
            w.write("&amp;");
            break;
        case '<':
            w.write("&lt;");
            break;
        case '>':
            w.write("&gt;");
            break;
        case '\'':
            w.write("&apos;");
            break;
        case '"':
            w.write("&quot;");
            break;
        default:
            if (canEncode(c)) {
                w.write(c);
            } else {
                w.write("&#");
                w.write(Integer.toString(c));
                w.write(';');
            }
            break;
        }
    }
    ByteArrayInputStream d;
    return w.toString();
}

From source file:org.springmodules.validation.valang.javascript.ValangJavaScriptTranslatorTests.java

protected boolean validate(Object target, String text, MessageSourceAccessor messageSource) {
    try {/*from ww w .j a  v a  2  s  . c o  m*/
        Collection rules = parseRules(text);
        StringWriter code = new StringWriter();
        new ValangJavaScriptTranslator().writeJavaScriptValangValidator(code, "someName", false, rules,
                messageSource);
        code.write(".validate()");
        ScriptableObject.putProperty(scope, "formObject", Context.javaToJS(target, scope));
        System.out.println(code.toString());
        Object evaluateString = cx.evaluateString(scope, code.toString(), "code", 1, null);
        Boolean result = (Boolean) cx.jsToJava(evaluateString, Boolean.class);
        return result.booleanValue();
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage());
    }
}