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.npower.cp.VelocityTemplateMerger.java

/**
 * @param templateID/*from  w  ww . j  a  va  2s  .c  o m*/
 * @param templateContent
 * @param settings
 * @return
 * @throws OTAException
 */
private ProvisioningDoc merge(String templateID, String templateContent, Object settings) throws OTAException {
    if (StringUtils.isEmpty(templateID)) {
        templateID = "Unknown";
    }
    try {
        //Velocity velocity = new Velocity();
        Velocity.init();
        // Any values specified before init() time will replace the default values.
        //velocity.setProperty("resource.loader", "file");
        //velocity.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
        //velocity.setProperty("file.resource.loader.path", System.getProperty("java.io.tmpdir"));

        VelocityContext context = new VelocityContext();
        if (settings != null) {
            context.put("profile", settings);
        }

        StringWriter out = new StringWriter();
        Velocity.evaluate(context, out, "OTATemplate ID:" + templateID, new StringReader(templateContent));
        // Pretty format XML document
        try {
            XMLPrettyFormatter formatter = new XMLPrettyFormatter(out.getBuffer().toString());
            out = new StringWriter();
            out.write(formatter.format());
        } catch (DocumentException ex) {
            // Ignore this error
            log.error("Error in pretty cp xml message: " + ex.getMessage(), ex);
        }

        //String templateFile = this.outputTmpFile(this.getContent());
        //Template veloTemplate = velocity.getTemplate(templateFile, "UTF-8");
        //veloTemplate.merge(context, out);
        ProvisioningDoc doc = new ProvisioningDocImpl(out);
        log.info("Merged CP Template: " + doc.getContent());
        return doc;
    } catch (ResourceNotFoundException e) {
        throw new OTAException(e);
    } catch (ParseErrorException e) {
        throw new OTAException(e);
    } catch (Exception e) {
        throw new OTAException(e);
    }
}

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

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;//from  w  w  w.  j a v  a2s.  c om
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // compression flag and session key as post vars
        buf.write(bdry + "\r\n");
        buf.write("Content-Disposition: form-data; name=\"c\"\r\n\r\n" + (comp != 0 ? 1 : 0) + "\r\n");
        if (hkey) {
            buf.write(bdry + "\r\n");
            buf.write("Content-Disposition: form-data; name=\"k\"\r\n\r\n" + mHKey + "\r\n");
        }
        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 = Collection.SYNC_URL;
        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 = url + "sync/" + 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-" + AnkiDroidApp.getPkgVersion());
        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);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

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

/**
 * If the word is profanity, map it to something less offensive.
 *//*from   w w  w  .  jav  a  2s.  c  om*/
public static String translateProfanity(String text) {
    if ((text == null) || text.isEmpty()) {
        return text;
    }
    String lowerText = text.toLowerCase();
    String translation = text;
    for (String profanity : profanityMap.keySet()) {
        if (lowerText.indexOf(profanity) != -1) {
            StringWriter writer = new StringWriter();
            TextStream stream = new TextStream(text);
            while (!stream.atEnd()) {
                writer.write(stream.nextWhitespace());
                String word = stream.nextWord();
                if (word != null) {
                    writer.write(mapProfanity(word));
                }
            }
            return writer.toString();
        }
    }
    return translation;
}

From source file:org.ballerinalang.composer.service.ballerina.launcher.service.LaunchManager.java

private String consumeStreamOutput(InputStream inputStream) throws IOException {
    StringWriter outputWriter = new StringWriter();
    boolean stop = false;
    while (!stop) {
        int rv;//from  w  w  w  .  ja v a 2  s . c om
        if (inputStream.available() > 0 && (rv = inputStream.read()) != -1) {
            outputWriter.write(rv);
        } else {
            stop = true;
        }
    }
    return outputWriter.toString();
}

From source file:edu.wisc.my.portlets.dmp.web.CachingXsltView.java

@SuppressWarnings("unchecked")
@Override/*w  w w. j av a2  s  .  c o m*/
protected void doTransform(Map model, Source source, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final Map parameters = getParameters(model, request);
    final Serializable cacheKey = this.getCacheKey(model, source, parameters);

    String cachedData;
    synchronized (this.xsltResultCache) {
        cachedData = this.xsltResultCache.get(cacheKey);
        if (cachedData == null) {
            final StringWriter writer = new StringWriter();

            final String encoding = response.getCharacterEncoding();
            this.doTransform(source, parameters, new StreamResult(writer), encoding);

            cachedData = writer.getBuffer().toString();
            this.xsltResultCache.put(cacheKey, cachedData);
        }
    }

    if (useWriter()) {
        final PrintWriter writer = response.getWriter();
        writer.write(cachedData);
        writer.flush();
    } else {
        final OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(cachedData.getBytes());
        outputStream.flush();
    }
}

From source file:com.ericsson.research.trap.spi.transports.ApacheClientHttpTransport.java

@Override
protected void internalConnect() throws TrapException {

    this.updateConfig();

    // Make a request to get a new TransportID
    if (!this.isClientConfigured()) {
        this.logger.debug(
                "HTTP Transport not properly configured... Unless autoconfigure is enabled (and another transport succeeds) this transport will not be available.");
        this.setState(TrapTransportState.ERROR);
        return;// w w  w  .j a v  a2s.  c o  m
    }

    try {
        this.running = true;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = this.openGet(this.connectUrl);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                isr = new InputStreamReader(is, Charset.forName("UTF-8"));

                StringWriter sr = new StringWriter();
                int ch = 0;

                while ((ch = isr.read()) != -1)
                    sr.write(ch);

                String rawUrl = sr.toString();

                String urlBase = this.connectUrl.toString();

                if (urlBase.endsWith("/"))
                    urlBase += rawUrl;
                else
                    urlBase += "/" + rawUrl;

                this.activeUrl = URI.create(urlBase);

                // Start a new thread for polling
                Thread t = new Thread(this);
                t.setDaemon(true);
                t.start();

                this.postclient = new DefaultHttpClient();

                // Change state to connected
                this.setState(TrapTransportState.CONNECTED);
            } finally {
                if (is != null)
                    is.close();

                if (isr != null)
                    isr.close();
            }
        }

    } catch (Exception e) {
        this.setState(TrapTransportState.ERROR);
        throw new TrapException(e);
    }

}

From source file:net.sf.farrago.namespace.sfdc.SfdcNameDirectory.java

Pattern getPattern(String likePattern) {
    Pattern pattern = patternMap.get(likePattern);
    if (pattern == null) {
        StringWriter regex = new StringWriter();
        int n = likePattern.length();
        for (int i = 0; i < n; ++i) {
            char c = likePattern.charAt(i);
            switch (c) {
            case '%':
                regex.write(".*");
                break;
            case '_':
                regex.write(".");
                break;
            default:
                regex.write((int) c);
                break;
            }/*  w  w w  .j  a  v  a2  s .c  om*/
        }
        pattern = Pattern.compile(regex.toString());
        patternMap.put(likePattern, pattern);
    }
    return pattern;
}

From source file:com.sangupta.shire.tools.ShireBlogImporter.java

/**
 * Append a line with the given prefix and the list of string values that need to be separated
 * by the given character./* w w  w.j av a2 s  . co  m*/
 * 
 * @param writer to which the text is appended
 * 
 * @param prefix the prefix to append
 * 
 * @param values the list of values that need to be added
 * 
 * @param separator the separator to be used between values
 * 
 */
protected void appendLine(StringWriter writer, String prefix, List<String> values, char separator) {
    writer.append(prefix);
    for (int index = 0; index < values.size(); index++) {
        String value = values.get(index);

        if (index > 0) {
            writer.write(separator);
        }
        writer.write(value);
    }

    writer.append(NEW_LINE);
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageCheckerWithStubs.java

protected String loadHtml() throws IOException {
    StringWriter buffer = null;
    BufferedReader reader = null;
    try {/*  w w w  .  j  a  v  a  2s .  c  o  m*/
        buffer = new StringWriter();
        reader = new BufferedReader(new InputStreamReader(
                TestMessageCheckerWithStubs.class.getResourceAsStream("lemonde.html"), CharEncoding.UTF_8));
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.write(line);
        }
        return buffer.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (buffer != null) {
            buffer.close();
        }
    }
}

From source file:org.jpublish.repository.servletcontext.ServletContextRepository.java

/** Get the content from the given path.  Implementations of this method
should NOT merge the content using view renderer.
        /*  w w  w . jav a2 s .  c o  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 {
        String root = PathUtilities.toResourcePath(getRoot());
        String relativePath = PathUtilities.toResourcePath(path);

        in = siteContext.getServletContext().getResourceAsStream(root + relativePath);
        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);
    }
}