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:com.wondershare.http.server.impl.HomePageServlet.java

@Override
protected void doGet(HttpRequest request, HttpResponse response, HttpContext context)
        throws IOException, ServletException {
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        @Override//ww  w .  j av  a2  s  . com
        public void writeTo(OutputStream outstream) throws IOException {
            OutputStreamWriter out = new OutputStreamWriter(outstream);
            out.write(Utils.openHTMLString(mContext, R.raw.home));
            out.flush();
        }
    });
    ((EntityTemplate) entity).setContentType("text/html");
    response.setEntity(entity);
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.SecureOutputRepresentation.java

@Override
public void write(OutputStream os) throws IOException {

    Writer out = new OutputStreamWriter(os);

    InputStream is = response.getEntity().getContent();

    BufferedInputStream buff = new BufferedInputStream(is);
    int i;//from  w  ww . j ava2s. com
    do {
        i = buff.read();
        out.write((char) i);
    } while (i != -1);

}

From source file:com.writewreckedsoftware.ullr.networking.UpdateMarker.java

@Override
protected String doInBackground(String... arg0) {
    String json = arg0[0];//from   w  ww . j av a  2 s .  c om
    JSONObject obj = null;
    String id = "";
    try {
        obj = new JSONObject(json);
        id = obj.getString("_id");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    URL url = null;
    String resultText = "";
    try {
        url = new URL("http://ullr.herokuapp.com/markers/" + id);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(json);
        out.close();
        InputStream response = connection.getInputStream();
        resultText = NetworkHelpers.getInstance(null).convertStreamToString(response);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    JSONObject result = null;
    try {
        result = new JSONObject(resultText);
        result.put("_id", id);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result.toString();
}

From source file:com.cloudera.sqoop.io.SplittableBufferedWriter.java

/** For testing. */
SplittableBufferedWriter(final SplittingOutputStream splitOutputStream, final boolean alwaysFlush) {
    super(new OutputStreamWriter(splitOutputStream));

    this.splitOutputStream = splitOutputStream;
    this.alwaysFlush = alwaysFlush;
}

From source file:com.theaigames.engine.io.IOPlayer.java

public IOPlayer(Process process, int index) {

    if (index == 0) {
        this.inputStream = new OutputStreamWriter(process.getOutputStream());
    } else {/*from w  w w . j a v a2 s  . c  om*/
        this.inputStream = new OutputStreamWriter(new TeeOutputStream(process.getOutputStream(), System.out));
    }
    this.outputGobbler = new InputStreamGobbler(process.getInputStream(), this, "output", index == 1);
    this.errorGobbler = new InputStreamGobbler(process.getErrorStream(), this, "error", index == 1);
    this.process = process;
    this.dump = new StringBuilder();
    this.errorCounter = 0;
    this.finished = false;
    this.playerIndex = index;
}

From source file:com.machinelinking.converter.ScriptableConverterTest.java

@Test
public void testConvert() throws IOException, ConverterException, ScriptableFactoryException {
    final String script = IOUtils
            .toString(this.getClass().getResourceAsStream("scriptable-converter-test1.py"));
    final ScriptableConverter converter = ScriptableConverterFactory.getInstance().createConverter(script);
    final ByteArrayOutputStream serializerBAOS = new ByteArrayOutputStream();
    final JSONSerializer serializer = new JSONSerializer(serializerBAOS);
    final ByteArrayOutputStream writerBAOS = new ByteArrayOutputStream();
    final Writer writer = new BufferedWriter(new OutputStreamWriter(writerBAOS));
    converter.convertData(JSONUtils/*from   ww  w.j a  va  2 s  .  c o m*/
            .parseJSONAsMap("{\"@type\":\"reference\",\"label\":\"List of Nobel laureates in Physics\","
                    + "\"content\":{\"@an0\":\"1921\"}}"),
            serializer, writer);
    serializer.close();
    writer.close();
    Assert.assertEquals(serializerBAOS.toString(), "{\"link\":\"List of Nobel laureates in Physics 1921\"}");
    Assert.assertEquals(writerBAOS.toString(), "<a href=\"List of Nobel laureates in Physics\">1921</a>");
}

From source file:Main.java

public static void exportXmlFile(ArrayList<?> listObject, String rootElement, String interfaceName,
        String pathSaveFile) {//from  ww  w . j  ava2 s. c  o  m
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
        // creating a new instance of a DOM to build a DOM tree.
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement(rootElement);
        // adding a node after the last child node of the specified node.
        doc.appendChild(root);

        Element interfaceElement = null;

        Element child = null;
        Text text;

        for (Object obj : listObject) {
            Class srcClass = obj.getClass();
            Field[] field = srcClass.getFields();
            interfaceElement = doc.createElement(interfaceName);
            for (int i = 0; i < field.length; i++) {
                // System.out.println(field[i].getName() + ":" +
                // field[i].get(obj));
                child = doc.createElement(field[i].getName());

                text = doc.createTextNode((field[i].get(obj)).toString());
                child.appendChild(text);

                interfaceElement.appendChild(child);
            }
            root.appendChild(interfaceElement);
        }

        // TransformerFactory instance is used to create Transformer
        // objects.
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();

        File file = new File(pathSaveFile);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        bw.write(xmlString);
        bw.flush();
        bw.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * //from  ww  w. j av a  2  s  .c  om
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    Loger.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    Loger.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        Loger.d(LOG_TAG, line);
    }
    rd.close();
}

From source file:edu.iu.kmeans.regroupallgather.KMUtil.java

/**
 * Generate centroids and upload to the cDir
 * /* ww  w. j  a v  a  2 s  .  c om*/
 * @param numCentroids
 * @param vectorSize
 * @param configuration
 * @param random
 * @param cenDir
 * @param fs
 * @throws IOException
 */
static void generateCentroids(int numCentroids, int vectorSize, Configuration configuration, Path cenDir,
        FileSystem fs) throws IOException {
    Random random = new Random();
    double[] data = null;
    if (fs.exists(cenDir))
        fs.delete(cenDir, true);
    if (!fs.mkdirs(cenDir)) {
        throw new IOException("Mkdirs failed to create " + cenDir.toString());
    }
    data = new double[numCentroids * vectorSize];
    for (int i = 0; i < data.length; i++) {
        // data[i] = 1000;
        data[i] = random.nextDouble() * 1000;
    }
    Path initClustersFile = new Path(cenDir, Constants.CENTROID_FILE_NAME);
    System.out.println("Generate centroid data." + initClustersFile.toString());
    FSDataOutputStream out = fs.create(initClustersFile, true);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
    for (int i = 0; i < data.length; i++) {
        if ((i % vectorSize) == (vectorSize - 1)) {
            bw.write(data[i] + "");
            bw.newLine();
        } else {
            bw.write(data[i] + " ");
        }
    }
    bw.flush();
    bw.close();
    System.out.println("Wrote centroids data to file");
}

From source file:de.elggconnect.elggconnectclient.webservice.AuthGetToken.java

@Override
/**//from  w ww .  j ava  2 s.  c om
 * 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;
}