Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:technology.tikal.accounts.dao.rest.SessionDaoRest.java

private void guardar(UserSession objeto, int intento) {
    //basic auth string
    String basicAuthString = config.getUser() + ":" + config.getPassword();
    basicAuthString = new String(Base64.encodeBase64(basicAuthString.getBytes()));
    basicAuthString = "Basic " + basicAuthString;

    //mensaje remoto
    try {/*from ww w .  j av  a 2s .co m*/
        //config
        URL url = new URL(config.getUrl());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(config.getMethod());
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", basicAuthString);
        connection.setInstanceFollowRedirects(false);
        //write
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(mapper.writeValueAsString(objeto));
        //close
        writer.close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            return;
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationRefused.SessionDaoRest.guardar" },
                    new String[] { connection.getResponseCode() + "" }, ""));
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        if (intento <= maxRetry) {
            this.guardar(objeto, intento + 1);
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationError.SessionDaoRest.guardar" },
                    new String[] { e.getMessage() }, ""));
        }
    }
}

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   ww w  .j  a  va2 s.  c  o  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: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 {//from w w w .  j  av  a2s.  co m
        writer = new OutputStreamWriter(outputMessage.getBody());

        writer.write(json);

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

From source file:com.example.user.rideshareapp1.MyGcmListenerService.java

/**
 * Called when message is received./*from w  ww.j a  v a 2  s  .  co  m*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {

    //TODO find a way to find if it is chat and store it in the file, create a notification
    if (android.os.Debug.isDebuggerConnected())
        android.os.Debug.waitForDebugger();

    String message = data.getString("message");

    String id;

    if (data.containsKey("topic")) {

        id = data.getString("ride");

        try (FileOutputStream fOut = openFileOutput("chat_" + id + ".txt", MODE_WORLD_READABLE | MODE_APPEND)) {

            OutputStreamWriter osw = new OutputStreamWriter(fOut);

            osw.write(data.getString("name") + ":" + data.getString("message") + "`");
            osw.flush();
            osw.close();

        } catch (IOException e) {
            Toast.makeText(this, "Failed to open chat file from notification", Toast.LENGTH_LONG).show();
        }

    } else {

        sendNotification(
                data.getString("title") + "`" + data.getString("name") + "`" + data.getString("message"));
    }

    Log.i(TAG, "From: " + from);
    Log.i(TAG, "Message: " + message);

    // [START_EXCLUDE]
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */

    // [END_EXCLUDE]
}

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 {//w  w  w. ja  v a 2 s .  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  ww w  .j a v  a 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.talend.components.webtest.JsonIo2HttpMessageConverter.java

/**
 * Serializes specified Object and writes JSON to HTTP message body 
 * //w w w.j  a  v a  2s . c  om
 * @param t Object to serialize
 * @param outputMessage the HTTP output message to write to
 */
@Override
protected void writeInternal(Object t, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody());
    String objectToJson = JsonWriter.objectToJson(t);
    outputStreamWriter.write(objectToJson);
    outputStreamWriter.flush();
    outputStreamWriter.close();
}

From source file:edu.illinois.cs.cogcomp.pipeline.server.ServerClientAnnotator.java

/**
 * The method is synchronized since the caching seems to have issues upon mult-threaded caching
 * @param overwrite if true, it would overwrite the values on cache
 *///  w w  w .ja  v a  2  s .c  o  m
public synchronized TextAnnotation annotate(String str, boolean overwrite) throws Exception {
    String viewsConnected = Arrays.toString(viewsToAdd);
    String views = viewsConnected.substring(1, viewsConnected.length() - 1).replace(" ", "");
    ConcurrentMap<String, byte[]> concurrentMap = (db != null)
            ? db.hashMap(viewName, Serializer.STRING, Serializer.BYTE_ARRAY).createOrOpen()
            : null;
    String key = DigestUtils.sha1Hex(str + views);
    if (!overwrite && concurrentMap != null && concurrentMap.containsKey(key)) {
        byte[] taByte = concurrentMap.get(key);
        return SerializationHelper.deserializeTextAnnotationFromBytes(taByte);
    } else {
        URL obj = new URL(url + ":" + port + "/annotate");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

        con.setDoOutput(true);
        con.setUseCaches(false);

        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write("text=" + URLEncoder.encode(str, "UTF-8") + "&views=" + views);
        wr.flush();

        InputStreamReader reader = new InputStreamReader(con.getInputStream());
        BufferedReader in = new BufferedReader(reader);
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        reader.close();
        wr.close();
        con.disconnect();
        TextAnnotation ta = SerializationHelper.deserializeFromJson(response.toString());
        if (concurrentMap != null) {
            concurrentMap.put(key, SerializationHelper.serializeTextAnnotationToBytes(ta));
            this.db.commit();
        }
        return ta;
    }
}

From source file:net.noday.cat.web.admin.DwzManager.java

@RequestMapping(method = RequestMethod.POST)
public Model gen(@RequestParam("url") String url, @RequestParam("alias") String alias, Model m) {
    try {//ww w.jav  a2 s  .  c o m
        String urlstr = "http://dwz.cn/create.php";
        URL requrl = new URL(urlstr);
        URLConnection conn = requrl.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        String param = String.format(Locale.CHINA, "url=%s&alias=%s", url, alias);
        out.write(param);
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        //{"longurl":"http:\/\/www.hao123.com\/","status":0,"tinyurl":"http:\/\/dwz.cn\/1RIKG"}
        ObjectMapper mapper = new ObjectMapper();
        Dwz dwz = mapper.readValue(line, Dwz.class);
        if (dwz.getStatus() == 0) {
            responseData(m, dwz.getTinyurl());
        } else {
            responseMsg(m, false, dwz.getErr_msg());
        }
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        responseMsg(m, false, e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        responseMsg(m, false, e.getMessage());
    }
    return m;
}

From source file:net.sf.zekr.engine.template.ThemeTemplate.java

/**
 * Transforms and persists all the theme CSS files if doesn't exists in the cache (
 * <tt>Naming.CACHE_DIR</tt>).
 * /*from w w w  . j ava  2s. co  m*/
 * @return result CSS, or null if no transformation done
 */
public String doTransform() {
    String retStr = null;
    String[] cssFileNames = resource.getStrings("theme.css.fileName");
    for (int i = 0; i < cssFileNames.length; i++) {
        File destFile = new File(Naming.getViewCacheDir() + "/" + cssFileNames[i]);

        // create destination CSS file if it doesn't exist
        if (!destFile.exists() || destFile.length() == 0) {
            logger.debug("Theme CSS doesn't exist, will create it: " + cssFileNames[i]);
            File srcFile = new File(
                    themeData.getPath() + "/" + resource.getString("theme.cssDir") + "/" + cssFileNames[i]);
            if (config.getTranslation().getDefault() != null) {
                themeData.process(config.getTranslation().getDefault().locale.getLanguage());
            } else {
                themeData.process("en");
            }
            engine.putAll(themeData.processedProps);

            try {
                OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile));
                retStr = engine.getUpdated(srcFile.getPath());
                osw.write(retStr);
                IOUtils.closeQuietly(osw);
            } catch (Exception e) {
                Logger.getLogger(this.getClass()).log(e);
            }
        }
    }
    return retStr;
}