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, int off, int len) 

Source Link

Document

Write a portion of a string.

Usage

From source file:es.eucm.eadventure.editor.plugin.vignette.ServerProxy.java

public String getJson() {
    String json = null;/*from w  ww.  j  ava2 s .  c  o m*/
    try {
        HttpClient httpclient = getProxiedHttpClient();
        String url = serviceURL + "/load.php?" + "m=" + getMac() + "&f=" + userPath;

        HttpGet hg = new HttpGet(url);
        HttpResponse response;
        response = httpclient.execute(hg);
        if (Integer.toString(response.getStatusLine().getStatusCode()).startsWith("2")) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();

                StringWriter strWriter = new StringWriter();

                char[] buffer = new char[1024];
                try {
                    Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        strWriter.write(buffer, 0, n);
                    }
                } finally {
                    instream.close();
                }
                json = strWriter.toString();
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}

From source file:com.microsoft.tfs.core.internal.db.DBStatement.java

private String clobToString(final Clob clob) throws SQLException, IOException {
    final StringWriter writer = new StringWriter();
    final Reader reader = clob.getCharacterStream();
    final char[] buf = new char[2048];
    int len;/*from  w w  w. ja  v a 2 s  .  com*/
    while ((len = reader.read(buf)) != -1) {
        writer.write(buf, 0, len);
    }

    return writer.toString();
}

From source file:com.comcast.cqs.util.Util.java

public static String decompress(String compressed) throws IOException {
    if (compressed == null || compressed.equals("")) {
        return compressed;
    }//from  w  ww. j a v  a 2 s .  c  o m
    Reader reader = null;
    StringWriter writer = null;
    try {
        if (!compressed.startsWith("H4sIA")) {
            String prefix = compressed;
            if (compressed.length() > 100) {
                prefix = prefix.substring(0, 99);
            }
            logger.warn("event=content_does_not_appear_to_be_zipped message=" + prefix);
            return compressed;
        }
        byte[] unencodedEncrypted = Base64.decodeBase64(compressed);
        ByteArrayInputStream in = new ByteArrayInputStream(unencodedEncrypted);
        GZIPInputStream gzip = new GZIPInputStream(in);
        reader = new InputStreamReader(gzip, "UTF-8");
        writer = new StringWriter();
        char[] buffer = new char[10240];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            writer.write(buffer, 0, length);
        }
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
    String decompressed = writer.toString();
    logger.info("event=decompressed from=" + compressed.length() + " to=" + decompressed.length());
    return decompressed;
}

From source file:tpt.dbweb.cat.evaluation.ReferenceEvaluator.java

/**
 * Call external command//from   www. java  2  s . c o m
 * @param cmd
 * @return its std output as a string
 */
private String execExternalCommand(String cmd) {
    log.debug("executing command: {}", cmd);
    Process p = null;
    try {
        p = Runtime.getRuntime().exec(cmd);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    InputStream is = p.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringWriter sw = new StringWriter();
    try {
        while (p.isAlive()) {
            try {
                char[] buffer = new char[1024 * 4];
                int n = 0;
                while (-1 != (n = br.read(buffer))) {
                    sw.write(buffer, 0, n);
                }
                if (p.isAlive()) {
                    Thread.sleep(10);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } catch (InterruptedException e1) {
        Thread.currentThread().interrupt();
    }
    String str = sw.toString();
    return str;
}

From source file:org.bankinterface.config.JsonBankConfig.java

/**
 * ??/*from   ww  w  . j a v  a  2 s .  co  m*/
 * 
 * @param configName
 * @return
 * @throws IOException
 */
private String getContent(String configName) throws IOException {
    InputStreamReader in = null;
    String content = null;
    try {
        in = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(configName), "UTF-8");
        StringWriter out = new StringWriter();
        int n = 0;
        char[] buffer = new char[4096];
        while (-1 != (n = in.read(buffer))) {
            out.write(buffer, 0, n);
        }
        content = out.toString();
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return content;
}

From source file:apps101.example.json.ItemListLoader.java

@Override
public List<Item> loadInBackground() {
    InputStream inputStream = null;
    try {/*from w w w.  ja  va  2  s  .  com*/
        URL url = new URL("http://d28rh4a8wq0iu5.cloudfront.net/androidapps101/example-data/shopping.txt");
        inputStream = url.openStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
        StringWriter stringWriter = new StringWriter();
        char[] buffer = new char[8192];
        // Yes this is an 'Unnecessary buffer' (=twice the memory movement) but Java Streams need an intermediate array
        // to bulk copy bytes& chars
        // Cant glue InputStreamReader directly to a StringWriter unless you want to move 1 char at a time :-(
        int count;
        while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
            stringWriter.write(buffer, 0, count);
        }
        JSONArray jsonArray = new JSONArray(stringWriter.toString());
        List<Item> result = new ArrayList<Item>();
        for (int i = 0; i < jsonArray.length(); i++) {
            Item item = new Item(jsonArray.getJSONObject(i));
            result.add(item);
        }
        return result;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception ignored) {
        }
    }
    return null;
}

From source file:siddur.solidtrust.insurancehelper.InsuranceService.java

public int saveRecordsFromFile(File file, boolean replace, List<String> exceptions) throws Exception {
    if (replace) {
        //delete old ones
        String ql = "truncate table InsuranceCar";
        int rows = persister.executeNativeQuery(ql);
        log4j.info("clean " + rows + " overdue rows");
    }//from  w  ww.  j a  v a  2s .  c o  m

    InputStream is = new FileInputStream(file);
    Reader br = new InputStreamReader(is);
    StringWriter ws = new StringWriter((int) file.length());

    int bufSize = 1024 * 8;
    char[] buf = new char[bufSize];
    int len = 0;
    while ((len = br.read(buf)) > 0) {
        ws.write(buf, 0, len);
    }

    br.close();
    ws.close();

    int batch = 5000;
    List<InsuranceCar> cars = new ArrayList<InsuranceCar>(batch);
    int i = 0;
    StringTokenizer st = new StringTokenizer(ws.toString());
    while (st.hasMoreTokens()) {
        String s = st.nextToken().trim();
        if (s.length() != 6) {
            exceptions.add(s);
            continue;
        }
        i++;
        InsuranceCar car = new InsuranceCar();
        car.setLicensePlate(s);
        car.setTableName(tables[0]); // Marktplaats
        cars.add(car);
        if (i % batch == 0) {
            if (replace) {
                persister.persist(cars);
            } else {
                persister.merge(cars);
            }
            log4j.info("Saved " + cars.size() + " records");
            cars = new ArrayList<InsuranceCar>(batch);
        }
    }

    if (replace) {
        persister.persist(cars);
    } else {
        persister.merge(cars);
    }
    log4j.info("Saved " + cars.size() + " records");
    log4j.info("Totally saved " + i + " records");

    log4j.info("Save parralel records of other tables");
    for (int j = 1; j < tables.length; j++) {
        String table = tables[j];
        String ql = "insert into InsuranceCar(licensePlate, tableName, stadagen, status)"
                + " select licensePlate, '" + table + "', 0, 0 from InsuranceCar" + " where tableName='"
                + tables[0] + "'";
        int rows = persister.executeNativeQuery(ql);
        log4j.info("Duplicate '" + table + "' from '" + tables[0] + "': " + rows);
    }
    return i;
}

From source file:com.xerox.amazonws.common.AWSQueryConnection.java

private String getStringFromStream(InputStream iStr) throws IOException {
    InputStreamReader rdr = new InputStreamReader(iStr, "UTF-8");
    StringWriter wtr = new StringWriter();
    char[] buf = new char[1024];
    int bytes;/* w  w w  .j  ava  2 s  .  co m*/
    while ((bytes = rdr.read(buf)) > -1) {
        if (bytes > 0) {
            wtr.write(buf, 0, bytes);
        }
    }
    iStr.close();
    return wtr.toString();
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

private void initialize() {
    this.init = true;

    try {/*from   w  ww  .j  av  a 2s . c o  m*/
        InputStream in = new FileInputStream(getSourceFile());
        ArrayList<String> itemList = new ArrayList<String>();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        String item = null;
        final int bufLength = 1024;
        char[] buffer = new char[bufLength];
        int readReturn;
        int count = 0;

        ZipEntry zipentry;
        ZipInputStream zipinputstream = new ZipInputStream(in);

        while ((zipentry = zipinputstream.getNextEntry()) != null) {
            count++;
            StringWriter sw = new StringWriter();
            Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8"));

            while ((readReturn = reader.read(buffer)) != -1) {
                sw.write(buffer, 0, readReturn);
            }

            item = new String(sw.toString());
            itemList.add(item);
            this.fileNames.add(zipentry.getName());

            reader.close();
            zipinputstream.closeEntry();

        }

        this.logger.debug("Zip file contains " + count + "elements");
        zipinputstream.close();
        this.counter = 0;

        this.originalData = byteArrayOutputStream.toByteArray();
        this.items = itemList.toArray(new String[] {});
        this.length = this.items.length;
    } catch (Exception e) {
        this.logger.error("Could not read zip File: " + e.getMessage());
        throw new RuntimeException("Error reading input stream", e);
    }
}

From source file:com.silverpeas.jcrutil.BetterRepositoryFactoryBean.java

/**
 * Load a Resource as a String./*from  w  w w .  j a v  a 2  s.  c o m*/
 *
 * @param config the resource
 * @return the String filled with the content of the Resource
 * @throws IOException
 */
protected String getConfiguration(Resource config) throws IOException {
    StringWriter out = new StringWriter();
    Reader reader = null;
    try {
        reader = new InputStreamReader(config.getInputStream(), Charsets.UTF_8);
        char[] buffer = new char[8];
        int c;
        while ((c = reader.read(buffer)) > 0) {
            out.write(buffer, 0, c);
        }
        return out.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}