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:de.elggconnect.elggconnectclient.webservice.AuthGetToken.java

@Override
/**//from ww  w. j  ava 2  s  . c  o m
 * Run the AuthGetTokeb Web API Method
 */
public Long execute() {

    //Build url Parameter String
    String urlParameters = APIMETHOD + "&username=" + this.username + "&password=" + this.password;

    //Try to execute the API Method
    try {

        URL url = new URL(userAuthentication.getBaseURL());
        URLConnection conn = url.openConnection();

        //add user agent to the request header
        conn.setRequestProperty("User-Agent", USER_AGENT);

        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        //Read the response JSON
        StringBuilder text = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            text.append(line).append("\n");
        }

        JSONObject json = (JSONObject) new JSONParser().parse(text.toString());

        this.status = (Long) json.get("status");
        if (this.status != -1L) {
            this.authToken = (String) json.get("result");

            //Save the AuthToken
            userAuthentication.setAuthToken((String) json.get("result"));
        }

        writer.close();
        reader.close();

    } catch (Exception e) {
        System.err.println(e.getMessage());

    }

    return this.status;
}

From source file:io.lavagna.service.LavagnaExporter.java

private void exportFiles(ZipOutputStream zf, OutputStreamWriter osw) throws IOException {
    osw.flush();//from ww  w  .jav  a 2 s. c  om
    for (CardDataUploadContentInfo fileData : cardDataRepository.findAllDataUploadContentInfo()) {
        zf.putNextEntry(new ZipEntry("files/" + fileData.getDigest()));
        cardDataRepository.outputFileContent(fileData.getDigest(), zf);
        writeEntry("files/" + fileData.getDigest() + ".json", fileData, zf, osw);
    }
}

From source file:JLabelDragSource.java

public Object getTransferData(DataFlavor fl) {
    if (!isDataFlavorSupported(fl)) {
        return null;
    }/*from  ww w .j a  v a  2 s  .c o  m*/

    if (fl.equals(DataFlavor.stringFlavor)) {
        // String - return the text as a String
        return label.getText() + " (DataFlavor.stringFlavor)";
    } else if (fl.equals(jLabelFlavor)) {
        // The JLabel itself - just return the label.
        return label;
    } else {
        // Plain text - return an InputStream
        try {
            String targetText = label.getText() + " (plain text flavor)";
            int length = targetText.length();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            OutputStreamWriter w = new OutputStreamWriter(os);
            w.write(targetText, 0, length);
            w.flush();
            byte[] bytes = os.toByteArray();
            w.close();
            return new ByteArrayInputStream(bytes);
        } catch (IOException e) {
            return null;
        }
    }
}

From source file:edu.mayo.cts2.framework.webapp.rest.converter.MappingGsonHttpMessageConverter.java

@Override
protected void writeInternal(Object t, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    String json = this.jsonConverter.toJson(t);

    OutputStreamWriter writer = null;
    try {/*w  ww  . j a va 2 s  . com*/
        writer = new OutputStreamWriter(outputMessage.getBody());

        writer.write(json);

        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:GCS_Auth.java

public GCS_Auth(String client_id, String key) {
    String SCOPE = "https://www.googleapis.com/auth/shoppingapi";
    SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent";
    try {//from   w w w  .  j a  v  a  2s.c  o m
        String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";

        long now = System.currentTimeMillis() / 1000L;
        long exp = now + 3600;
        String iss = client_id;
        String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE
                + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now
                + "}";

        String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));

        byte[] jwt_data = jwt.getBytes("UTF8");

        Signature sig = Signature.getInstance("SHA256WithRSA");

        KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), "notasecret".toCharArray());

        sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray()));
        sig.update(jwt_data);
        byte[] signatureBytes = sig.sign();
        String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        String assertion = jwt + "." + b64sig;

        //System.out.println("Assertion: " + assertion);

        String data = "grant_type=assertion";
        data += "&" + "assertion_type" + "="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
        data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8");

        URLConnection conn = null;
        try {
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            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 line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            InputStream error = ((HttpURLConnection) conn).getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        //System.out.println(access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:com.irahul.worldclock.WorldClockData.java

private void writeToFile(String jsonString) {
    Log.d(TAG, "Writing JSON to file: " + jsonString);
    try {//from  w ww.  j  a  va 2  s .c o  m
        FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        OutputStreamWriter osw = new OutputStreamWriter(fos);

        osw.write(jsonString);
        osw.flush();
        osw.close();
        fos.close();

    } catch (FileNotFoundException e) {
        throw new WorldClockException(e);
    } catch (IOException e) {
        throw new WorldClockException(e);
    }
}

From source file:org.intermine.bio.web.logic.LiftOverService.java

/**
 * Send a HTTP POST request to liftOver service.
 *
 * @param grsc the Genomic Region Search constraint
 * @param org human or mouse//w  w  w  .  ja  va  2s.  co  m
 * @param genomeVersionSource older genome version
 * @param genomeVersionTarget intermine genome version
 * @param liftOverServerURL url
 * @return a list of GenomicRegion
 */
public String doLiftOver(GenomicRegionSearchConstraint grsc, String org, String genomeVersionSource,
        String genomeVersionTarget, String liftOverServerURL) {

    List<GenomicRegion> genomicRegionList = grsc.getGenomicRegionList();
    String liftOverResponse;

    String coords = converToBED(genomicRegionList);
    String organism = ORGANISM_COMMON_NAME_MAP.get(org);

    try {
        // Construct data
        String data = URLEncoder.encode("coords", "UTF-8") + "=" + URLEncoder.encode(coords, "UTF-8");
        data += "&" + URLEncoder.encode("source", "UTF-8") + "="
                + URLEncoder.encode(genomeVersionSource, "UTF-8");
        data += "&" + URLEncoder.encode("target", "UTF-8") + "="
                + URLEncoder.encode(genomeVersionTarget, "UTF-8");

        // Send data
        URL url;
        // liftOverServerURL ends with "/"
        if (!liftOverServerURL.endsWith("/")) {
            url = new URL(liftOverServerURL + "/" + organism);
        } else {
            url = new URL(liftOverServerURL + organism);
        }
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        wr.close();

        liftOverResponse = new String(IOUtils.toCharArray(conn.getInputStream()));

        LOG.info("LiftOver response message: \n" + liftOverResponse);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return liftOverResponse;
}

From source file:com.pinterest.deployservice.common.HTTPClient.java

private String internalCall(String url, String method, String payload, Map<String, String> headers, int retries)
        throws Exception {
    HttpURLConnection conn = null;
    Exception lastException = null;

    for (int i = 0; i < retries; i++) {
        try {/*from   w ww .jav  a 2 s .co m*/
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod(method);
            conn.setRequestProperty("Accept-Charset", "UTF-8");

            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            if (StringUtils.isNotEmpty(payload)) {
                conn.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                writer.write(payload);
                writer.flush();
                writer.close();
            }

            String ret = IOUtils.toString(conn.getInputStream(), "UTF-8");
            int responseCode = conn.getResponseCode();
            if (responseCode >= 400) {
                throw new DeployInternalException("HTTP request failed, status = {}, content = {}",
                        responseCode, ret);
            }
            LOG.info("HTTP Request returned with response code {} for URL {}", responseCode, url);
            return ret;
        } catch (Exception e) {
            lastException = e;
            LOG.error("Failed to send HTTP Request to {}, with payload {}, with headers {}", url, payload,
                    headers, e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
    throw lastException;
}

From source file:com.aoyetech.fee.commons.utils.IOUtils.java

/**
 * Copy chars from a <code>Reader</code> to bytes on an
 * <code>OutputStream</code> using the default character encoding of the
 * platform, and calling flush./*ww  w . j  a  v a  2 s.  c om*/
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 * <p>
 * Due to the implementation of OutputStreamWriter, this method performs a
 * flush.
 * <p>
 * This method uses {@link OutputStreamWriter}.
 * 
 * @param input the <code>Reader</code> to read from
 * @param output the <code>OutputStream</code> to write to
 * @throws NullPointerException if the input or output is null
 * @throws IOException if an I/O error occurs
 * @since Commons IO 1.1
 */
public static void copy(final Reader input, final OutputStream output) throws IOException {
    final OutputStreamWriter out = new OutputStreamWriter(output);
    copy(input, out);
    // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    // have to flush here.
    out.flush();
}

From source file:musite.io.xml.XMLEscapeWriter.java

public void write(OutputStream os, Object fieldValue) throws IOException {
    if (os == null || fieldValue == null)
        return;/*from ww  w  .  j a  va  2 s.co  m*/

    OutputStreamWriter osw = new OutputStreamWriter(os);

    String str = StringEscapeUtils.escapeXml(fieldValue.toString());

    for (int i = 0; i < getIndent(); i++)
        osw.write("\t");

    osw.write(str);
    osw.flush();
}