Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

In this page you can find the example usage for java.io OutputStreamWriter flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.alternatecomputing.jschnizzle.renderer.WebSequenceRenderer.java

public BufferedImage render(Diagram diagram) {
    String script = diagram.getScript();
    if (script == null) {
        throw new RendererException("no script defined.");
    }/*  www .  ja v  a2  s .  c  o  m*/

    String style = diagram.getStyle().getValue();
    String baseURL = getBaseURL();

    try {
        // build parameter string
        String data = "style=" + style + "&format=svg&message=" + URLEncoder.encode(script, "UTF-8");

        // send the request
        URL url = new URL(baseURL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        // write parameters
        writer.write(data);
        writer.flush();

        // get the response
        StringBuffer answer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            answer.append(line);
        }
        writer.close();
        reader.close();

        JSONObject json = JSONObject.fromString(answer.toString());

        HttpClient client = new HttpClient();
        String proxyHost = System.getProperty("http.proxyHost");
        String proxyPort = System.getProperty("http.proxyPort");
        if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) {
            client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        }
        String getURI = baseURL + json.getString("img");
        GetMethod getMethod = new GetMethod(getURI);
        client.executeMethod(getMethod);
        String svgContents = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        LOGGER.debug(svgContents);

        diagram.setEncodedImage(svgContents);
        TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgContents.getBytes()));
        BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
        imageTranscoder.transcode(input, null);

        // log any errors to the UI console
        JSONArray errors = json.getJSONArray("errors");
        for (int eIdx = 0; eIdx < errors.length(); ++eIdx) {
            LOGGER.error("JSON error: " + errors.getString(eIdx));
        }
        return imageTranscoder.getBufferedImage();

    } catch (MalformedURLException e) {
        throw new RendererException(e);
    } catch (IOException e) {
        throw new RendererException(e);
    } catch (TranscoderException e) {
        throw new RendererException(e);
    }
}

From source file:com.commonsware.android.tte.DocumentStorageService.java

private void save(Uri document, String text, boolean isClosing) {
    boolean isContent = ContentResolver.SCHEME_CONTENT.equals(document.getScheme());

    try {/*from   w ww  .  j a  va  2s.  c  o m*/
        OutputStream os = getContentResolver().openOutputStream(document, "w");
        OutputStreamWriter osw = new OutputStreamWriter(os);

        try {
            osw.write(text);
            osw.flush();

            if (isClosing && isContent) {
                int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

                getContentResolver().releasePersistableUriPermission(document, perms);
            }

            EventBus.getDefault().post(new DocumentSavedEvent(document));
        } finally {
            osw.close();
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception saving " + document.toString(), e);
        EventBus.getDefault().post(new DocumentSaveErrorEvent(document, e));
    }
}

From source file:com.adaptris.core.services.Utf8BomRemoverTest.java

private AdaptrisMessage create(boolean includeBom) throws Exception {
    AdaptrisMessage msg = new DefaultMessageFactory().newMessage();
    OutputStream out = msg.getOutputStream();
    OutputStreamWriter writer = null;
    try {//  w  ww . ja  v  a2 s . c  om
        if (includeBom) {
            out.write(UTF_8_BOM);
            out.flush();
        }
        writer = new OutputStreamWriter(out);
        writer.write(PAYLOAD);
        writer.flush();
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(out);
    }

    return msg;
}

From source file:com.mcapanel.utils.ErrorHandler.java

private void e(String af) {
    try {/*  www  . j  a  v a2 s. c  o m*/
        URLConnection kx = new URL(v.toString()).openConnection();

        kx.setDoOutput(true);
        kx.setDoInput(true);

        OutputStreamWriter qd = new OutputStreamWriter(kx.getOutputStream());

        qd.write(af);
        qd.flush();

        BufferedReader yx = new BufferedReader(new InputStreamReader(kx.getInputStream()));

        String lx = yx.readLine();

        if (lx != null) {
            JSONObject pg = (JSONObject) new JSONParser().parse(lx);

            if (pg.containsKey("v") && v(pg.get("v")).toString().equals(x.toString()))
                cd = true;
            else
                cd = false;

            if (pg != null && pg.containsKey(w.toString()) && pg.containsKey(b.toString())) {
                ObfuscatedString un = v(pg.get(b.toString()));
                ObfuscatedString lf = v(pg.get(w.toString()));

                if (lf.toString().equals(q.toString())) {
                    if (un.toString().equals(k.toString()) && pg.containsKey(c.toString())) {
                        g(v(pg.get(c.toString())));
                        e = true;
                    }
                } else if (lf.toString().equals(t.toString())) {
                    g(new ObfuscatedString(
                            new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
                    e = false;
                }
            } else
                throw new Exception();
        } else
            throw new Exception();

        qd.close();
        yx.close();
    } catch (Exception e1) {
        g(new ObfuscatedString(
                new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
        e = false;
    }
}

From source file:com.synelixis.xifi.AuthWebClient.Client.java

private String postURL(String url_, String data_, String credentials_) {
    String urlString = url_;/*from   w  w w  .j a v a  2 s  . c  om*/
    String JSON = data_;
    String credentials = credentials_;

    try {
        URL u = new URL(urlString);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setDoOutput(true);
        c.setRequestMethod("POST");
        if ((credentials != null) && !credentials.equals("")) {
            c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            c.setRequestProperty("Authorization", "Basic " + credentials);
        } else {
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Accept", "application/json");
        }
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
        out.write(JSON);
        out.flush();
        out.close();
        System.out.println("url:" + url_ + " -- data:" + data_ + " -- response" + c.getResponseCode());
        switch (c.getResponseCode()) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            String result = sb.toString();
            return result;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE,
                "Unexpected exception when call the remote server ", ex);
    }
    return null;
}

From source file:com.predic8.membrane.examples.config.ConfigSerializationTest.java

public void prettyPrint(String xml) throws Exception, IOException {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(System.out);
    XMLBeautifier xmlBeautifier = new XMLBeautifier(new PlainBeautifierFormatter(outputStreamWriter, 0));
    xmlBeautifier.parse(new StringReader(xml));
    outputStreamWriter.flush();
}

From source file:de.liedtke.data.url.BasicDAOUrl.java

protected JSONObject requestUrl(final String daoName, final String methodName, final String jsonValue)
        throws JSONException {
    String jsonString = null;//from  w w w .  ja  v a2s  . c o m
    try {
        // Construct data
        final StringBuilder params = new StringBuilder();
        params.append(URLEncoder.encode("daoName", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(daoName, Constants.UTF8));
        params.append("&");
        params.append(URLEncoder.encode("methodName", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(methodName, Constants.UTF8));
        if (jsonValue != null) {
            params.append("&");
            params.append(URLEncoder.encode("jsonValue", Constants.UTF8));
            params.append("=");
            params.append(URLEncoder.encode(jsonValue, Constants.UTF8));
        }
        params.append("&");
        params.append(URLEncoder.encode("kind", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(ResultKind.JSON.toString(), Constants.UTF8));

        // Send data
        URL url = new URL(address);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(params.toString());
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder sBuilder = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sBuilder.append(line);
        }
        jsonString = sBuilder.toString();
        wr.close();
        rd.close();
    } catch (UnsupportedEncodingException e) {
        logger.warning("UnsupportedEncodingException occured: " + e.getMessage());
    } catch (IOException e) {
        logger.warning("IOException occured: " + e.getMessage());
    }
    JSONObject json = null;
    if (jsonString == null) {
        json = null;
    } else {
        json = new JSONObject(jsonString);
    }
    return json;
}

From source file:nl.welteninstituut.tel.oauth.OauthWorker.java

protected String postToURL(URL url, String data) throws IOException {
    try {/*from   w w w . ja  v a2 s .  c  om*/
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String result = "";
        String line;
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        wr.close();
        rd.close();
        return result;
    } catch (Exception e) {
    }
    return "{}";
}

From source file:org.aselect.authspserver.authsp.delegator.HTTPDelegate.java

public int authenticate(Map<String, String> requestparameters, Map<String, List<String>> responseparameters)
        throws DelegateException {
    String sMethod = "authenticate";
    int iReturnCode = -1;

    AuthSPSystemLogger _systemLogger;// w  w  w .ja  v a 2s.c  om
    _systemLogger = AuthSPSystemLogger.getHandle();

    _systemLogger.log(Level.FINEST, sModule, sMethod,
            "requestparameters=" + requestparameters + " , responseparameters=" + responseparameters);
    StringBuffer data = new StringBuffer();
    String sResult = "";
    try {
        final String EQUAL_SIGN = "=";
        final String AMPERSAND = "&";
        final String NEWLINE = "\n";

        for (String key : requestparameters.keySet()) {
            data.append(URLEncoder.encode(key, "UTF-8"));
            data.append(EQUAL_SIGN).append(URLEncoder.encode(
                    ((String) requestparameters.get(key) == null) ? "" : (String) requestparameters.get(key),
                    "UTF-8"));
            data.append(AMPERSAND);
        }

        if (data.length() > 0)
            data.deleteCharAt(data.length() - 1); // remove last AMPERSAND

        //         _systemLogger.log(Level.FINE, sModule, sMethod, "url=" + url.toString() + " data={" + data.toString() + "}");   // no data shown in production environment

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Basic authentication
        if (this.delegateuser != null) {
            byte[] bEncoded = Base64
                    .encodeBase64((this.delegateuser + ":" + (delegatepassword == null ? "" : delegatepassword))
                            .getBytes("UTF-8"));
            String encoded = new String(bEncoded, "UTF-8");
            conn.setRequestProperty("Authorization", "Basic " + encoded);
            _systemLogger.log(Level.FINEST, sModule, sMethod,
                    "Using basic authentication, user=" + this.delegateuser);

        }
        //         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // They (the delegate party) don't accept charset !!
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());
        wr.flush();
        wr.close();

        // Get the response
        iReturnCode = conn.getResponseCode();
        Map<String, List<String>> hFields = conn.getHeaderFields();

        _systemLogger.log(Level.FINEST, sModule, sMethod, "response=" + iReturnCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        // Still to decide on response protocol
        while ((line = rd.readLine()) != null) {
            sResult += line;
        }
        _systemLogger.log(Level.INFO, sModule, sMethod, "sResult=" + sResult);
        // Parse response  here
        // For test return request parameters
        responseparameters.putAll(hFields);

        rd.close();
    } catch (IOException e) {
        _systemLogger.log(Level.INFO, sModule, sMethod,
                "Error while reading sResult data, maybe no data at all. sResult=" + sResult);
    } catch (NumberFormatException e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed due to number format exception! " + e.getMessage(), e);
    } catch (Exception e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed (progress=" + iReturnCode + ")! " + e.getMessage(), e);
    }
    return iReturnCode;
}

From source file:hudson.Util.java

/**
 * Escapes non-ASCII characters in URL.//from www  .  j a v  a  2 s  .c o m
 *
 * <p>
 * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
 * such as '#'.
 * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
 * a single path component to that method (it will encode /, but this method does not).
 */
public static String encode(String s) {
    try {
        boolean escaped = false;

        StringBuilder out = new StringBuilder(s.length());

        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        OutputStreamWriter w = new OutputStreamWriter(buf, "UTF-8");

        for (int i = 0; i < s.length(); i++) {
            int c = (int) s.charAt(i);
            if (c < 128 && c != ' ') {
                out.append((char) c);
            } else {
                // 1 char -> UTF8
                w.write(c);
                w.flush();
                for (byte b : buf.toByteArray()) {
                    out.append('%');
                    out.append(toDigit((b >> 4) & 0xF));
                    out.append(toDigit(b & 0xF));
                }
                buf.reset();
                escaped = true;
            }
        }

        return escaped ? out.toString() : s;
    } catch (IOException e) {
        throw new Error(e); // impossible
    }
}