Example usage for java.io OutputStreamWriter OutputStreamWriter

List of usage examples for java.io OutputStreamWriter OutputStreamWriter

Introduction

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

Prototype

public OutputStreamWriter(OutputStream out) 

Source Link

Document

Creates an OutputStreamWriter that uses the default character encoding.

Usage

From source file:edu.usu.sdl.openstorefront.report.generator.HtmlGenerator.java

@Override
public void init() {
    Objects.requireNonNull(report, "The generator requires the report to exist.");
    Objects.requireNonNull(report.getReportId(), "The report id is required.");
    try {/*w w w. ja v a2  s.  c  o  m*/
        writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(report.pathToReport().toFile())));
        writer.append("<html><body style='padding: 20px'>");
    } catch (IOException ex) {
        throw new OpenStorefrontRuntimeException("Unable to open file to write report.",
                "Check file system permissions", ex);
    }
}

From source file:de.hska.ld.core.config.LDLoggerConfig.java

@Autowired
private void init() throws IOException {
    File f = File.createTempFile("tinylog_conf", ".txt");
    FileOutputStream fos = new FileOutputStream(f);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
    try {//w w  w .  jav a 2  s .  co m
        String writer = env.getProperty("tinylog.writer");
        bw.write("tinylog.writer = " + writer);
        bw.newLine();
        /*String fileName = env.getProperty("tinylog.writer.filename");
        bw.write("tinylog.writer.filename = " + fileName);
        bw.newLine();
        String buffered = env.getProperty("tinylog.writer.buffered");
        bw.write("tinylog.writer.buffered = " + buffered);
        bw.newLine();
        String append = env.getProperty("tinylog.writer.append");
        bw.write("tinylog.writer.append = " + append);
        bw.newLine();*/
        String level = env.getProperty("tinylog.level");
        bw.write("tinylog.level = " + level);
        bw.newLine();
        String writerUrl = env.getProperty("tinylog.writer.url");
        bw.write("tinylog.writer.url = " + writerUrl);
        bw.newLine();
        String writerTable = env.getProperty("tinylog.writer.table");
        bw.write("tinylog.writer.table = " + writerTable);
        bw.newLine();
        String writerColumns = env.getProperty("tinylog.writer.columns");
        bw.write("tinylog.writer.columns = " + writerColumns);
        bw.newLine();
        String writerValues = env.getProperty("tinylog.writer.values");
        bw.write("tinylog.writer.values = " + writerValues);
        bw.newLine();
        String writerBatch = env.getProperty("tinylog.writer.batch");
        bw.write("tinylog.writer.batch = " + writerBatch);
        bw.newLine();
        String writerUsername = env.getProperty("tinylog.writer.username");
        bw.write("tinylog.writer.username = " + writerUsername);
        bw.newLine();
        String writerPassword = env.getProperty("tinylog.writer.password");
        bw.write("tinylog.writer.password = " + writerPassword);
        bw.newLine();
        String writingThread = env.getProperty("tinylog.writingthread");
        bw.write("tinylog.writingthread = " + writingThread);
        bw.newLine();
        String wTObserve = env.getProperty("tinylog.writingthread.observe");
        bw.write("tinylog.writingthread.observe = " + wTObserve);
        bw.newLine();
        String wTPriority = env.getProperty("tinylog.writingthread.priority");
        bw.write("writingthread.priority = " + wTPriority);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bw.close();
    }
    Configurator.fromFile(f).activate();
}

From source file:com.pcms.temp.generate.MarkeWrite.java

public void save(String savePath, String templateName, String templateEncoding, Map<?, ?> root) {
    String path = savePath + "/" + templateName + ".html";
    FileUtil.delete(path);//w  ww  .  j a va  2 s .  c  o  m

    try {
        File file = FileUtil.createFile(path);
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        this.processTemplate(templateName, templateEncoding, root, out);
    } catch (FileNotFoundException ex) {
        _log.error(ex.getMessage());
    } catch (IOException ex) {
        _log.error(ex.getMessage());
    }
}

From source file:jetbrains.exodus.util.Streamer.java

public Streamer(@NotNull InputStream socketInput, @NotNull OutputStream socketOutput) {
    this.socketInput = new BufferedReader(new InputStreamReader(socketInput), BUFFER_SIZE);
    this.socketOutput = new BufferedWriter(new OutputStreamWriter(socketOutput));
}

From source file:com.uksf.mf.core.utility.LogHandler.java

/**
 * Writes to file//w  w  w.j  a v a 2 s  . c o  m
 * @param log formatted message to write
 */
private static void toFile(String log) {
    try {
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile, true)));
        writer.append(log).append("\n");
        writer.close();
    } catch (IOException e) {
        error(e);
    }
}

From source file:Main.java

public static String[] execSQL(String dbName, String query) {
    Process process = null;/* ww w. ja va  2 s . c o  m*/
    Runtime runtime = Runtime.getRuntime();
    OutputStreamWriter outputStreamWriter;

    try {
        String command = dbName + " " + "'" + query + "'" + ";";
        process = runtime.exec("su");

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

        outputStreamWriter.write("sqlite3 " + command);

        outputStreamWriter.flush();
        outputStreamWriter.close();
        outputStreamWriter.close();

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

    final InputStreamReader errorStreamReader = new InputStreamReader(process.getErrorStream());

    (new Thread() {
        @Override
        public void run() {
            try {

                BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
                String s;
                while ((s = bufferedReader.readLine()) != null) {
                    Log.d("com.suraj.waext", "WhatsAppDBHelper:" + s);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }).start();

    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String s;
        StringBuilder op = new StringBuilder();

        while ((s = bufferedReader.readLine()) != null) {
            op.append(s).append("\n");
        }

        return op.toString().split("\n");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;

}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesRetriever.java

private static JSONArray retrieveTimeSeriesPOST(String urlString, long startEpoch, long endEpoch, String metric,
        HashMap<String, String> tags) throws OpenTSDBException {

    urlString = urlString + API_METHOD;/*from  w  w w  .j a  va2  s  . c o  m*/
    String result = "";

    try {
        HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString);
        OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream());

        JSONObject mainObject = new JSONObject();
        mainObject.put("start", startEpoch);
        mainObject.put("end", endEpoch);

        JSONArray queryArray = new JSONArray();

        JSONObject queryParams = new JSONObject();
        queryParams.put("aggregator", "sum");
        queryParams.put("metric", metric);

        queryArray.put(queryParams);

        if (tags != null) {
            JSONObject queryTags = new JSONObject();

            Iterator<Entry<String, String>> entries = tags.entrySet().iterator();
            while (entries.hasNext()) {
                @SuppressWarnings("rawtypes")
                Map.Entry entry = (Map.Entry) entries.next();
                queryTags.put((String) entry.getKey(), (String) entry.getValue());
            }

            queryParams.put("tags", queryTags);
        }

        mainObject.put("queries", queryArray);
        String queryString = mainObject.toString();

        wr.write(queryString);
        wr.flush();
        wr.close();

        result = TimeSeriesUtility.readHttpResponse(httpConnection);

    } catch (IOException e) {
        throw new OpenTSDBException("Unable to connect to server", e);
    } catch (JSONException e) {
        throw new OpenTSDBException("Error on request data", e);
    }

    return TimeSeriesUtility.makeResponseJSONArray(result);
}

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;//from  ww  w .  j a  va  2s.c  om
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java

public void run() {
    Socket socket;/* w  ww .j av a  2s . c  om*/
    BufferedReader input;
    BufferedWriter output;

    kuc_log.i("Connecting to server at " + server_ip);

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server_ip), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        kuc_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        kuc_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        kuc_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        kuc_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        kuc_log.i("Requesting a key update.");
        output.write("302 request key update");
        output.newLine();
        output.flush();

        kuc_log.i("Awaiting response from server.");
        String update = input.readLine();
        switch (update) {
        case "303 update":
            kuc_log.i("Server accepted update request, sending public key.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "304 no update":
            kuc_log.i("Server rejected update request, closing connection.");
            input.close();
            output.close();
            break;
        case "305 update unavailable":
            kuc_log.i("Server cannot update at this time, try again later.");
            input.close();
            output.close();
            break;
        default:
            kuc_log.i("Server sent back invalid response");
            input.close();
            output.close();
            break;
        }
    } catch (IOException e) {
        kuc_log.e("Error in key update request!");
        e.printStackTrace();
    }
}

From source file:matrix.TextUrlMatrix.java

public void textUrlMatrix()
        throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException {

    double a = 0.7;
    CosSim cossim = new CosSim();
    JSONParser jParser = new JSONParser();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweets.json"), "ISO-8859-9"));
    JSONArray jArray = (JSONArray) jParser.parse(in);
    BufferedReader in2 = new BufferedReader(new InputStreamReader(
            new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweetsUrls.json"), "ISO-8859-9"));
    JSONArray jArray2 = (JSONArray) jParser.parse(in2);
    File fout = new File("/Users/nSabri/Desktop/textUrlMatris.csv");
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    for (int i = 0; i < 100; i++) {

        for (int j = 0; j < 100; j++) {

            JSONObject tweet1text = (JSONObject) jArray.get(i);
            JSONObject tweet2text = (JSONObject) jArray.get(j);
            JSONObject tweet1url = (JSONObject) jArray2.get(i);
            JSONObject tweet2url = (JSONObject) jArray2.get(j);
            String tweetText1 = tweet1text.get("tweets").toString();
            String tweetText2 = tweet2text.get("tweets").toString();
            String tweetUrl1 = tweet1url.get("title").toString() + tweet1url.get("meta").toString();
            String tweetUrl2 = tweet2url.get("title").toString() + tweet1url.get("meta").toString();

            double CosSimValueText = cossim.Cosine_Similarity_Score(tweetText1, tweetText2);

            double CosSimValueUrl = cossim.Cosine_Similarity_Score(tweetUrl1, tweetUrl2);

            double TextUrlSimValue = (a * CosSimValueText) + ((1 - a) * CosSimValueUrl);

            TextUrlSimValue = Double.parseDouble(new DecimalFormat("##.###").format(TextUrlSimValue));

            bw.write(Double.toString(TextUrlSimValue) + ", ");

        }//w ww . j a  v  a  2  s . c  o  m
        bw.newLine();
    }
    bw.close();

}