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:com.otisbean.keyring.Ring.java

/**
 * Initialize the cipher object and create the key object.
 * /*from  w ww. j a  v a 2  s.com*/
 * @param password
 * @return A checkData string, which can be compared against the existing
 * one to determine if the password is valid.
 * @throws GeneralSecurityException
 */
private String initCipher(char[] password) throws GeneralSecurityException {
    log("initCipher()");
    String base64Key = null;
    try {
        // Convert a char array into a UTF-8 byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter out = new OutputStreamWriter(baos, "UTF-8");
        try {
            out.write(password);
            out.close();
        } catch (IOException e) {
            // the only reason this would throw is an encoding problem.
            throw new RuntimeException(e.getLocalizedMessage());
        }
        byte[] passwordBytes = baos.toByteArray();

        /* The following code looks like a lot of monkey-motion, but it yields
         * results compatible with the on-phone Keyring Javascript and Mojo code.
         * 
         * In newPassword() in ring.js, we have this (around line 165):
         * this._key = b64_sha256(this._salt + newPassword); */
        byte[] saltBytes = salt.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(saltBytes, 0, saltBytes.length);
        md.update(passwordBytes, 0, passwordBytes.length);
        byte[] keyHash = md.digest();
        String paddedBase64Key = Base64.encodeBytes(keyHash);
        /* The Javascript SHA-256 library used in Keyring doesn't pad base64 output,
         * so we need to trim off any trailing "=" signs. */
        base64Key = paddedBase64Key.replace("=", "");
        byte[] keyBytes = base64Key.getBytes("UTF-8");

        /* Keyring passes data to Mojo.Model.encrypt(key, data), which eventually
         * make a JNI call to OpenSSL's blowfish api.  The following is the
         * equivalent in straight up JCE. */
        key = new SecretKeySpec(keyBytes, "Blowfish");
        iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
    } catch (UnsupportedEncodingException e) {
        // This is a bit dodgy, but handling a UEE elsewhere is foolish
        throw new GeneralSecurityException(e.getLocalizedMessage());
    }
    return "{" + base64Key + "}";
}

From source file:com.ibm.BestSellerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from ww w .j  a  v  a  2  s  .co m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/json");
    response.setCharacterEncoding("UTF-8");

    OutputStream stream = response.getOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");

    String listName = request.getParameter("list");
    String date = request.getParameter("date");

    logger.debug("Requested list {} and requested date {}", listName, date);

    NewYorkTimes times = new NewYorkTimes(listName, date);

    try {
        BestSellerList bestSellers = times.getList();
        ObjectMapper mapper = new ObjectMapper();

        String listContents = mapper.writeValueAsString(bestSellers.getBooks());
        logger.debug("Booklist is {}", listContents);
        writer.write(listContents);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        logger.error("New York times list unavailable");
        throw new IOException("Could not get book list from ny times");
    }

}

From source file:com.techcavern.pircbotz.IdentServer.java

/**
 * Waits for a client to connect to the ident server before making an
 * appropriate response./*from   w  ww  .  ja v a2s  . c  o m*/
 */
public void run() {
    log.info("IdentServer running on port " + serverSocket.getLocalPort());
    //TODO: Multi-thread this
    while (!serverSocket.isClosed()) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), encoding));
            OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), encoding);
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();

            //Read first line and process
            String line = reader.readLine();
            String response = handleNextConnection(remoteAddress, line);
            if (response != null) {
                writer.write(response);
                writer.flush();
            }
        } catch (Exception e) {
            if (serverSocket.isClosed()) {
                log.debug("Server socket closed, exiting connection loop");
                return;
            } else
                //This is not from the server socket closing
                throw new RuntimeException("Exception encountered when opening user socket");
        } finally {
            //Close user socket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Exception encountered when closing user socket");
            }
        }
    }

    //Done with connection loop, can safely close the socket now
    if (!serverSocket.isClosed())
        try {
            close();
        } catch (IOException e) {
            log.error("Cannot close IdentServer socket", e);
        }
}

From source file:compiler.downloader.MegaHandler.java

private String api_request(String data) {
    HttpURLConnection connection = null;
    try {/*ww w.  j  a va  2s  .  c  o m*/
        String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number;
        if (sid != null) {
            urlString += "&sid=" + sid;
        }

        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST"); //use post method
        connection.setDoOutput(true); //we will send stuff
        connection.setDoInput(true); //we want feedback
        connection.setUseCaches(false); //no caches
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Content-Type", "text/xml");

        OutputStream out = connection.getOutputStream();
        try {
            OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write("[" + data + "]"); //data is JSON object containing the api commands
            wr.flush();
            wr.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the output stream
            if (out != null) {
                out.close();
            }
        }

        InputStream in = connection.getInputStream();
        StringBuffer response = new StringBuffer();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
            }
            rd.close(); //close the reader
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the input stream
            if (in != null) {
                in.close();
            }
        }

        return response.toString().substring(1, response.toString().length() - 1);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.globalsight.everest.tda.TdaHelper.java

private void writeXlfHeader(OutputStreamWriter m_outputStream) throws IOException {
    String m_strEOL = "\r\n";
    m_outputStream.write("<?xml version=\"1.0\"?>");
    m_outputStream.write(m_strEOL);//from   ww w  . ja v  a 2  s .  com
    m_outputStream.write("<xliff version=\"1.2\">");
    m_outputStream.write(m_strEOL);
}

From source file:com.globalsight.everest.tda.TdaHelper.java

private void writeXlfEnd(OutputStreamWriter m_outputStream) throws IOException {
    String m_strEOL = "\r\n";
    m_outputStream.write("</body>");
    m_outputStream.write(m_strEOL);//from   ww  w  .  j  a v a 2s.c o m
    m_outputStream.write("</file>");
    m_outputStream.write(m_strEOL);
    m_outputStream.write("</xliff>");
}

From source file:com.smartmarmot.orabbix.Sender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    //message.append(Base64.encode(key));
    message.append(base64Encode(key));/* w  w  w . java 2 s  .com*/
    message.append(middle);
    //message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    if (log.isDebugEnabled()) {
        SmartLogger.logThis(Level.DEBUG, "sending " + message);
    }

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    Enumeration<String> serverlist = zabbixServers.keys();

    while (serverlist.hasMoreElements()) {
        String zabbixServer = serverlist.nextElement();
        try {
            zabbix = new Socket(zabbixServer, zabbixServers.get(zabbixServer).intValue());
            zabbix.setSoTimeout(TIMEOUT);

            out = new OutputStreamWriter(zabbix.getOutputStream());
            out.write(message.toString());
            out.flush();

            in = zabbix.getInputStream();
            final int read = in.read(response);
            if (log.isDebugEnabled()) {
                SmartLogger.logThis(Level.DEBUG, "received " + new String(response));
            }
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                SmartLogger.logThis(Level.WARN,
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            SmartLogger.logThis(Level.ERROR, "Error contacting Zabbix server " + zabbixServer + "  on port "
                    + zabbixServers.get(zabbixServer));
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}

From source file:com.galactogolf.genericobjectmodel.levelloader.LevelSet.java

private void saveToFile(File f) throws LevelSavingException {
    OutputStream output;/*from  w ww .j a  v  a 2  s . c o m*/
    try {
        output = new FileOutputStream(f);
    } catch (FileNotFoundException e) {
        Log.e("File saving error", e.getMessage());
        throw new LevelSavingException(e.getMessage());
    }
    OutputStreamWriter writer = new OutputStreamWriter(output);

    String data;
    try {
        data = JSONSerializer.toJSON(this).toString(2);
    } catch (JSONException e) {
        Log.e("File saving error", e.getMessage());
        throw new LevelSavingException(e.getMessage());
    }

    try {
        writer.write(data);
        writer.flush();
        writer.close();

        output.close();

    } catch (IOException e) {
        Log.e("Exception", e.getMessage());
    }
}

From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java

/**
 * Get the request token//from   w  ww  .  j  av  a  2 s  . c o  m
 * 
 * @param callbackUrl
 *            HTTP callback URL for handling the user authorization
 * @return
 * @throws Exception
 */
public Map<String, String> getRequestToken(String callbackUrl) throws Exception {
    Log.d(LOG_TAG, "getRequestToken");
    URLConnection urlConnection = getUrlConnection(API_URL_BASE + REQUEST_TOKEN_PATH, true);

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());

    Request request = new Request(POST);
    request.addParameter(OAUTH_CONSUMER_KEY, consumerKey);
    request.addParameter(OAUTH_CALLBACK, callbackUrl);
    request.sign(API_URL_BASE + REQUEST_TOKEN_PATH, consumerSecret, null);
    outputStreamWriter.write(request.toString());
    outputStreamWriter.close();

    return readParams(urlConnection.getInputStream());
}

From source file:com.geodan.ngr.serviceintegration.CSWTransformer.java

/**
 * POSTs the xml request to the given url and returns a String representation of the response.
 *
 * @param xml_request   the request contains the search criteria
 * @param url         the url to POST the request to
 * @return            returns a String representation of the response
 * @throws IOException in case of exception
 *///from  w  ww. j ava 2 s  .  co  m
private String post(String xml_request, String url) throws IOException {
    // Create an URL object
    log.debug("creating request to URL: " + url);
    URL csUrl = new URL(url);

    // Create an HttpURLConnection and use the URL object to POST the request
    HttpURLConnection csUrlConn = (HttpURLConnection) csUrl.openConnection();
    csUrlConn.setDoOutput(true);
    csUrlConn.setDoInput(true);
    csUrlConn.setRequestMethod("POST");
    csUrlConn.setRequestProperty("Content-Type", "text/xml");

    // Create a OutputStream to actually send the request and close the streams
    OutputStream out = csUrlConn.getOutputStream();
    OutputStreamWriter wout = new OutputStreamWriter(out, "UTF-8");
    wout.write(xml_request);
    wout.flush();
    out.close();

    // Get a InputStream and parse it in the parse method
    InputStream is = csUrlConn.getInputStream();
    String response = "";
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            is.close();
        }
        response = sb.toString();
    }
    // Close Streams and connections
    out.close();
    csUrlConn.disconnect();

    if (response != null && response.length() > 0) {
        log.debug("GetRecords response:\n" + response);
    } else {
        log.debug("GetRecords response empty");
    }

    // Returns response
    return response;
}