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:com.norconex.collector.core.crawler.AbstractCrawlerConfig.java

protected void writeObject(Writer out, String tagName, Object object, boolean ignore) throws IOException {
    out.flush();//from   w  ww.  j  a  v a 2 s .  c om
    if (object == null) {
        if (ignore) {
            out.write("<" + tagName + " ignore=\"" + ignore + "\" />");
        }
        return;
    }
    StringWriter w = new StringWriter();
    if (object instanceof IXMLConfigurable) {
        ((IXMLConfigurable) object).saveToXML(w);
    } else {
        w.write("<" + tagName + " class=\"" + object.getClass().getCanonicalName() + "\" />");
    }
    String xml = w.toString();
    if (ignore) {
        xml = xml.replace("<" + tagName + " class=\"", "<" + tagName + " ignore=\"true\" class=\"");
    }
    out.write(xml);
    out.flush();
}

From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java

public void sendSubtitleSegment(HttpServletResponse response) throws IOException {
    List<String> segment = new ArrayList<>();
    segment.add("WEBVTT");

    // Write segment to buffer so we can get the content length
    StringWriter segmentWriter = new StringWriter();
    for (String line : segment) {
        segmentWriter.write(line + "\n");
    }//from  ww  w  .  j a  va2s .c om

    // Set Header Parameters
    response.reset();
    response.setContentType("text/vtt");
    response.setContentLength(segmentWriter.toString().length());

    // Enable CORS
    response.setHeader(("Access-Control-Allow-Origin"), "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setIntHeader("Access-Control-Max-Age", 3600);

    // Write segment out to the client
    response.getWriter().write(segmentWriter.toString());
}

From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java

/**
 * @param command/*  w w  w  . j av  a2 s  .  c  o m*/
 * @throws IOException
 * @throws InterruptedException
 */
private void executeCommand(String command) throws IOException, InterruptedException {

    log.info("Command command[" + command + "]");

    ProcessBuilder processBuilder = new ProcessBuilder(command.split("\\s"));

    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();

    StringWriter output = new StringWriter();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    try {
        int ch;
        while ((ch = reader.read()) != -1) {
            output.write(ch);
        }
    } finally {
        reader.close();
    }

    int result = process.waitFor();

    log.info("Command returnCode[" + result + "] output[" + output.toString() + "]");

    if (result != 0) {
        throw new IOException("Execute command Error command[" + command + "] returnCode[" + result
                + "] output[" + output.toString() + "]");
    }
}

From source file:com.espertech.esper.dataflow.ops.LogSink.java

private void getEventOut(int port, Object theEvent, StringWriter writer) {

    if (theEvent instanceof EventBean) {
        renderer.render((EventBean) theEvent, writer);
        return;//from  w  w  w. j  av  a2  s.  c  om
    }

    if (shellPerStream[port] != null) {
        synchronized (this) {
            shellPerStream[port].setUnderlying(theEvent);
            renderer.render(shellPerStream[port], writer);
        }
        return;
    }

    writer.write("Unrecognized underlying: ");
    writer.write(theEvent.toString());
}

From source file:org.beangle.struts2.view.BeangleTagLibrary.java

/**
 * query string and form control//from  w  w w .  j a  v a 2 s  .  c o m
 * 
 * @return
 */
public String getParamstring() {
    StringWriter sw = new StringWriter();
    Enumeration<?> em = req.getParameterNames();
    while (em.hasMoreElements()) {
        String attr = (String) em.nextElement();
        String value = req.getParameter(attr);
        if (attr.equals("x-requested-with")) {
            continue;
        }
        sw.write(attr);
        sw.write('=');
        try {
            StringEscapeUtils.escapeJavaScript(sw, value);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (em.hasMoreElements()) {
            sw.write('&');
        }
    }
    return sw.toString();
}

From source file:com.ichi2.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;/*from   w  ww . java  2s  .c o  m*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:website.openeng.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;//ww w .ja va  2  s  . c  om
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(KanjiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "KanjiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java

public void sendHLSPlaylist(UUID id, String type, Integer extra, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // Get the request base URL so we can use it in our playlist
    String baseUrl = request.getRequestURL().toString().replaceFirst("/stream(.*)", "");

    List<String> playlist;

    // Get playlist as a string array
    if (type == null) {
        playlist = generateHLSVariantPlaylist(id, baseUrl);
    } else {/*from w  w w  .  j a  va 2 s. com*/
        playlist = generateHLSPlaylist(id, baseUrl, type, extra);
    }

    if (playlist == null) {
        LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME,
                "Unable to generate HLS playlist.", null);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to generate HLS playlist.");
        return;
    }

    // Write playlist to buffer so we can get the content length
    StringWriter playlistWriter = new StringWriter();
    for (String line : playlist) {
        playlistWriter.write(line + "\n");
    }

    // Set Header Parameters
    response.reset();
    response.setContentType("application/x-mpegurl");
    response.setContentLength(playlistWriter.toString().length());

    // Enable CORS
    response.setHeader(("Access-Control-Allow-Origin"), "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setIntHeader("Access-Control-Max-Age", 3600);

    // Write playlist out to the client
    response.getWriter().write(playlistWriter.toString());

    /*********************** DEBUG: Response Headers *********************************/
    String requestHeader = "\n***************\nResponse Header:\n***************\n";
    Collection<String> responseHeaderNames = response.getHeaderNames();

    for (int i = 0; i < responseHeaderNames.size(); i++) {
        String header = (String) responseHeaderNames.toArray()[i];
        String value = response.getHeader(header);
        requestHeader += header + ": " + value + "\n";
    }

    // Log Headers
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, requestHeader, null);

    /********************************************************************************/

    // Log playlist
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME,
            "\n************\nHLS Playlist\n************\n" + playlistWriter.toString(), null);
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.sensitivity.ResultFileReader.java

/**
 * Returns the next population in the file; or {@code null} if the end of
 * the file is reached. If the last entry in the file is incomplete,
 * {@code null} is returned.//from w  w w .j  ava  2s .co  m
 * 
 * @return the next population in the file; or {@code null} if the end of
 *         the file is reached
 * @throws NumberFormatException if an error occurred parsing the objectives
 * @throws IOException if an I/O error occurred
 */
private ResultEntry readNextEntry() throws NumberFormatException, IOException {
    NondominatedPopulation population = new NondominatedPopulation();
    StringWriter stringBuffer = new StringWriter();

    // ignore any comment lines separating entries
    while ((line != null) && line.startsWith("#")) {
        line = reader.readLine();
    }

    // read next entry, terminated by #
    while ((line != null) && !line.startsWith("#")) {
        if (line.startsWith("//")) {
            stringBuffer.write(line.substring(2));
            stringBuffer.write('\n');
        } else {
            Solution solution = parseSolution(line);

            if (solution == null) {
                System.err.println("unable to parse solution, ignoring remaining entries in the file");
                return null;
            } else {
                population.add(solution);
            }
        }

        line = reader.readLine();
    }

    Properties properties = new Properties();
    properties.load(new StringReader(stringBuffer.toString()));

    // return population only if non-empty and terminated by a #
    if ((line == null) || !line.startsWith("#")) {
        return null;
    } else {
        return new ResultEntry(population, properties);
    }
}

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

/**
 * Compress the text to be a proper identifier within the size limit.
 * Replace space with '-' and remove any non alpha numerics.
 */// w w  w.j  a v  a2 s .  c o  m
public static String compress(String text, int size) {
    TextStream stream = new TextStream(text);
    StringWriter writer = new StringWriter(text.length());
    int count = 0;
    while (!stream.atEnd()) {
        if (count >= size) {
            break;
        }
        char next = stream.next();
        if (Character.isLetter(next) || Character.isDigit(next) || (next == '_')) {
            writer.write(next);
        } else {
            writer.write('_');
        }
        count++;
    }
    return writer.toString();
}