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:net.solarnetwork.web.support.SimpleXmlView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Map<String, Object> finalModel = setupDateFormat(model);

    response.setContentType(getContentType());
    String charset = getResponseCharacterEncoding();
    OutputStreamWriter out;
    try {//from   w w w .  ja  v a2  s.  c o m
        out = new OutputStreamWriter(response.getOutputStream(), charset);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    // write XML start
    out.write("<?xml version=\"1.0\" encoding=\"");
    out.write(charset);
    out.write("\"?>\n");

    Object singleBean = finalModel.size() == 1 && this.singleBeanAsRoot ? finalModel.values().iterator().next()
            : null;

    if (singleBean != null) {
        outputObject(singleBean, finalModel.keySet().iterator().next().toString(), out, rootElementAugmentor);
    } else {
        writeElement(this.rootElementName, null, out, false, rootElementAugmentor);

        for (Map.Entry<String, Object> me : finalModel.entrySet()) {
            outputObject(me.getValue(), me.getKey(), out, null);
        }

        // end root element
        closeElement(this.rootElementName, out);
    }

    out.flush();
    SDF.remove();
}

From source file:cc.twittertools.download.AsyncEmbeddedJsonStatusBlockCrawler.java

public void fetch() throws IOException {
    long start = System.currentTimeMillis();
    LOG.info("Processing " + file);

    int cnt = 0;//w ww. j a  va 2 s . c o m
    BufferedReader data = null;
    try {
        data = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line;
        while ((line = data.readLine()) != null) {
            try {
                String[] arr = line.split("\t");
                long id = Long.parseLong(arr[0]);
                String username = (arr.length > 1) ? arr[1] : "a";
                String url = getUrl(id, username);

                connections.incrementAndGet();
                crawlURL(url, new TweetFetcherHandler(id, username, url, 0, !this.noFollow, line));

                cnt++;

                if (cnt % TWEET_BLOCK_SIZE == 0) {
                    LOG.info(cnt + " requests submitted");
                }
            } catch (NumberFormatException e) { // parseLong
                continue;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        data.close();
    }

    // Wait for the last requests to complete.
    LOG.info("Waiting for remaining requests (" + connections.get() + ") to finish!");
    for (int i = 0; i < 10; i++) {
        if (connections.get() == 0) {
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    asyncHttpClient.close();

    long end = System.currentTimeMillis();
    long duration = end - start;
    LOG.info("Total request submitted: " + cnt);
    LOG.info(crawl.size() + " tweets fetched in " + duration + "ms");

    LOG.info("Writing tweets...");
    int written = 0;

    OutputStreamWriter out = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(output)),
            "UTF-8");
    for (Map.Entry<Long, String> entry : crawl.entrySet()) {
        written++;
        out.write(entry.getValue() + "\n");
    }
    out.close();

    LOG.info(written + " statuses written.");

    if (this.repair != null) {
        LOG.info("Writing repair data file...");
        written = 0;
        out = new OutputStreamWriter(new FileOutputStream(repair), "UTF-8");
        for (Map.Entry<Long, String> entry : crawl_repair.entrySet()) {
            written++;
            out.write(entry.getValue() + "\n");
        }
        out.close();

        LOG.info(written + " statuses need repair.");
    }

    LOG.info("Done!");
}

From source file:com.d2dx.j2objc.TranslateMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {

    if (this.includeDependencySources) {

        //@formatter:off
        executeMojo(//  w  w  w.  j  a v  a 2s.  c o  m
                plugin(groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"),
                        version("2.8")),
                goal("unpack-dependencies"),
                configuration(element("classifier", "sources"),
                        element("failOnMissingClassifierArtifact", "false"),
                        element(name("outputDirectory"), "${project.build.directory}/j2objc-sources")),
                executionEnvironment(this.mavenProject, this.mavenSession, this.pluginManager));
    }

    /*
     * Extracts j2objc automagically 
     */
    //@formatter:off
    executeMojo(
            plugin(groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version("2.8")),
            goal("unpack"),
            configuration(
                    element("artifactItems", element("artifactItem", element("groupId", "com.d2dx.j2objc"),
                            element("artifactId", "j2objc-package"), element("version", this.j2objcVersion))),
                    element(name("outputDirectory"), "${project.build.directory}/j2objc-bin")),
            executionEnvironment(this.mavenProject, this.mavenSession, this.pluginManager));
    //@formatter:on

    /*
     * Time to do detection and run j2objc with proper parameters.
     */

    this.outputDirectory.mkdirs();

    // Gather the source paths
    // Right now, we limit to sources in two directories: project srcdir, and additional sources.
    // Later, we should add more.
    HashSet<String> srcPaths = new HashSet<String>();

    String srcDir = this.mavenSession.getCurrentProject().getBuild().getSourceDirectory();
    srcPaths.add(srcDir);

    String buildDir = this.mavenSession.getCurrentProject().getBuild().getDirectory();
    String addtlSrcDir = buildDir + "/j2objc-sources";
    srcPaths.add(addtlSrcDir);

    // Gather sources.
    HashSet<File> srcFiles = new HashSet<File>();

    for (String path : srcPaths) {
        File sdFile = new File(path);
        Collection<File> scanFiles = FileUtils.listFiles(sdFile, new String[] { "java" }, true);
        srcFiles.addAll(scanFiles);
    }

    // Gather prefixes into a file
    FileOutputStream fos;
    OutputStreamWriter out;

    if (this.prefixes != null) {
        try {
            fos = new FileOutputStream(new File(this.outputDirectory, "prefixes.properties"));
            out = new OutputStreamWriter(fos);

            for (Prefix p : this.prefixes) {
                out.write(p.javaPrefix);
                out.write(": ");
                out.write(p.objcPrefix);
                out.write("\n");
            }

            out.flush();
            out.close();
            fos.close();
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Could not create prefixes file");
        } catch (IOException e1) {
            throw new MojoExecutionException("Could not create prefixes file");
        }

    }
    // We now have:
    // Sources, source directories, and prefixes.
    // Call the maven-exec-plugin with the new environment!

    LinkedList<Element> args = new LinkedList<Element>();

    if (this.includeClasspath) {
        args.add(new Element("argument", "-cp"));
        args.add(new Element("classpath", ""));
    }

    String srcDirsArgument = "";

    for (String p : srcPaths)
        srcDirsArgument += ":" + p;

    // Crop the first colon
    if (srcDirsArgument.length() > 0)
        srcDirsArgument = srcDirsArgument.substring(1);

    args.add(new Element("argument", "-sourcepath"));
    args.add(new Element("argument", srcDirsArgument));

    if (this.prefixes != null) {
        args.add(new Element("argument", "--prefixes"));
        args.add(new Element("argument", this.outputDirectory.getAbsolutePath() + "/prefixes.properties"));
    }

    args.add(new Element("argument", "-d"));
    args.add(new Element("argument", this.outputDirectory.getAbsolutePath()));

    for (File f : srcFiles)
        args.add(new Element("argument", f.getAbsolutePath()));

    try {
        Runtime.getRuntime()
                .exec("chmod u+x " + this.mavenProject.getBuild().getDirectory() + "/j2objc-bin/j2objc");
    } catch (IOException e) {
        e.printStackTrace();
    }
    //@formatter:off
    executeMojo(plugin(groupId("org.codehaus.mojo"), artifactId("exec-maven-plugin"), version("1.3")),
            goal("exec"),
            configuration(element("arguments", args.toArray(new Element[0])),
                    element("executable", this.mavenProject.getBuild().getDirectory() + "/j2objc-bin/j2objc"),
                    element("workingDirectory", this.mavenProject.getBuild().getDirectory() + "/j2objc-bin/")),
            executionEnvironment(this.mavenProject, this.mavenSession, this.pluginManager));
    //@formatter:on

}

From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java

private void connectAndSend(String xml) throws ServerException {

    HttpURLConnection conn = null;
    OutputStreamWriter wr = null;

    try {/*from w  ww  . j  av a 2 s.c o  m*/
        LOGGER.debug("{} - Url: {}", instanceName, urlstr);
        String payload = cmd + xml;
        conn = createHTTPConnection(payload);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(payload);
        wr.flush();

        /*
         * Look for status != 0 by building a DOM to parse
         * <status>0</status> <message>OK</message>
         */

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGGER.error("{} - Could not get a doc builder", instanceName, e);
            return;
        }

        /*
         * Getting the value for status and message tags
         */
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));) {

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("NRDP return string - {}", convertStreamToString(is));
                is.reset();
            }

            Document doc = null;

            doc = dBuilder.parse(is);

            doc.getDocumentElement().normalize();
            String rootNode = doc.getDocumentElement().getNodeName();
            NodeList responselist = doc.getElementsByTagName(rootNode);
            String result = (String) ((Element) responselist.item(0)).getElementsByTagName("status").item(0)
                    .getChildNodes().item(0).getNodeValue().trim();

            LOGGER.debug("NRDP return status is: {}", result);

            if (!"0".equals(result)) {
                String message = (String) ((Element) responselist.item(0)).getElementsByTagName("message")
                        .item(0).getChildNodes().item(0).getNodeValue().trim();
                LOGGER.error("{} - nrdp returned message \"{}\" for xml: {}", instanceName, message, xml);
            }
        } catch (SAXException e) {
            LOGGER.error("{} - Could not parse response xml", instanceName, e);
        }

    } catch (IOException e) {
        LOGGER.error("{} - Network error - check nrdp server and that service is started", instanceName, e);
        throw new ServerException(e);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException ignore) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.example.kjpark.smartclass.NoticeTab.java

private void setSignatureLayout() {
    LayoutInflater dialogInflater = (LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    dialogView = dialogInflater.inflate(R.layout.dialog_signature, null);
    mSignaturePad = (SignaturePad) dialogView.findViewById(R.id.signature_pad);

    clearButton = (Button) dialogView.findViewById(R.id.clearButton);
    sendButton = (Button) dialogView.findViewById(R.id.sendButton);

    mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
        @Override//from  w w w . j  av a2  s.c  o  m
        public void onSigned() {
            clearButton.setEnabled(true);
            sendButton.setEnabled(true);
        }

        @Override
        public void onClear() {
            clearButton.setEnabled(false);
            sendButton.setEnabled(false);
        }
    });
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mSignaturePad.clear();
        }
    });
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //send sign image to server
            ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() {
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                private String num = Integer.toString(currentViewItem);

                @Override
                protected Boolean doInBackground(String... params) {
                    URL obj = null;
                    try {
                        obj = new URL("http://165.194.104.22:5000/enroll_sign");
                        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                        //implement below code if token is send to server
                        con = ConnectServer.getInstance().setHeader(con);

                        con.setDoOutput(true);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        signatureBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] b = baos.toByteArray();
                        String sign_image = Base64.encodeToString(b, Base64.DEFAULT);
                        Log.d(TAG, "sign_image: " + sign_image.length());

                        String parameter = URLEncoder.encode("num", "UTF-8") + "="
                                + URLEncoder.encode(num, "UTF-8");
                        parameter += "&" + URLEncoder.encode("sign_image", "UTF-8") + "="
                                + URLEncoder.encode(sign_image, "UTF-8");

                        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                        wr.write(parameter);
                        wr.flush();

                        BufferedReader rd = null;

                        if (con.getResponseCode() == 200) {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

                            Log.d("---- success ----", rd.toString());

                        } else {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                            Log.d("---- failed ----", String.valueOf(rd.readLine()));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Boolean aBoolean) {

                }
            });
            ConnectServer.getInstance().execute();
            signature_dialog.dismiss();
            loadBoards();
        }
    });
}

From source file:it.infn.ct.jsaga.adaptor.tosca.job.ToscaJobControlAdaptor.java

private String submitTosca() throws IOException, ParseException, BadResource, NoSuccessException {
    StringBuilder orchestrator_result = new StringBuilder("");
    StringBuilder postData = new StringBuilder();
    postData.append("{ \"template\": \"");
    String tosca_template_content = "";
    try {//from w  w  w.  j a  v  a2s .c om
        tosca_template_content = new String(Files.readAllBytes(Paths.get(tosca_template))).replace("\n", "\\n");
        postData.append(tosca_template_content);
    } catch (IOException ex) {
        log.error("Template '" + tosca_template + "'is not readable");
        throw new BadResource("Template '" + tosca_template + "'is not readable; template:" + LS + "'"
                + tosca_template_content + "'");
    }
    postData.append("\"  }");

    log.debug("JSON Data sent to the orchestrator: \n" + postData);
    HttpURLConnection conn;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(postData.toString());
        wr.flush();
        wr.close();
        log.debug("Orchestrator status code: " + conn.getResponseCode());
        log.debug("Orchestrator status message: " + conn.getResponseMessage());
        if (conn.getResponseCode() == 201) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            orchestrator_result = new StringBuilder();
            String ln;
            while ((ln = br.readLine()) != null) {
                orchestrator_result.append(ln);
            }

            log.debug("Orchestrator result: " + orchestrator_result);
            String orchestratorDoc = orchestrator_result.toString();
            tosca_UUID = getDocumentValue(orchestratorDoc, "uuid");
            log.debug("Created resource has UUID: '" + tosca_UUID + "'");
            return orchestratorDoc;

        }
    } catch (IOException ex) {
        log.error("Connection error with the service at " + endpoint.toString());
        log.error(ex);
        throw new NoSuccessException("Connection error with the service at " + endpoint.toString());
    } catch (ParseException ex) {
        log.error("Orchestrator response not parsable");
        throw new NoSuccessException(
                "Orchestrator response not parsable:" + LS + "'" + orchestrator_result.toString() + "'");
    }
    return tosca_UUID;
}

From source file:com.mitre.holdshort.AlertLogger.java

public void logOldAlerts() {
    try {//from   w  ww .  ja  va2 s  .  co m
        // check for old alerts
        File oldAlerts = new File(ctx.getFilesDir() + "/oldAlerts.dat");

        if (oldAlerts.length() > 0) {

            alertFTPClient.changeWorkingDirectory("/data");
            OutputStream os = alertFTPClient
                    .storeFileStream(airport + "_" + System.currentTimeMillis() + ".dat");
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedReader br = new BufferedReader(new FileReader(oldAlerts));
            String line;
            while ((line = br.readLine()) != null) {
                osw.write(line);
                osw.write("\n");
            }

            // clear oldAlerts.dat
            FileWriter clearOldAlerts = new FileWriter(oldAlerts, false);
            clearOldAlerts.write("");
            clearOldAlerts.close();
            osw.close();
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.pixmob.appengine.client.AppEngineClient.java

private void writeAuthenticationCookie() {
    OutputStreamWriter out = null;
    try {// w w w.ja  v  a 2  s  .c om
        out = new OutputStreamWriter(
                context.openFileOutput(AUTH_COOKIE_FILE + account.name, Context.MODE_PRIVATE), "UTF-8");

        if (authenticationCookie != null) {
            out.write(authenticationCookie);
        }
        out.write("\n");
    } catch (IOException e) {
        Log.i(TAG, "Failed to store authentication cookie", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:org.guanxi.sp.engine.service.shibboleth.AuthConsumerServiceThread.java

/**
 * This opens the connection to the guard, sends the SOAP request, and reads the response.
 * /*from   www .j  a  v a2  s. com*/
 * @param acsURL              The URL of the Guard Attribute Consumer Service
 * @param entityID            The entity ID of the Guard
 * @param keystoreFile        The location of the keystore to use to identify the engine to the guard
 * @param keystorePassword    The password for the keystore
 * @param truststoreFile      The location of the truststore to use to verify the guard
 * @param truststorePassword  The password for the truststore
 * @param soapRequest         The request that will be sent to the Guard
 * @param guardSession        The Guard's session ID
 * @return                    A string containing the response from the guard
 * @throws GuanxiException    If there is a problem creating the EntityConnection or setting the attributes on it
 * @throws IOException        If there is a problem using the EntityConnection to read or write data
 */
private String processGuardConnection(String acsURL, String entityID, String keystoreFile,
        String keystorePassword, String truststoreFile, String truststorePassword, EnvelopeDocument soapRequest,
        String guardSession) throws GuanxiException, IOException {
    ResponseDocument responseDoc = unmarshallSAML(soapRequest);
    Bag bag = getBag(responseDoc, guardSession);

    // Initialise the connection to the Guard's attribute consumer service
    EntityConnection connection = new EntityConnection(acsURL, entityID, keystoreFile, keystorePassword,
            truststoreFile, truststorePassword, EntityConnection.PROBING_OFF);
    connection.setDoOutput(true);
    connection.connect();

    // Send the data to the Guard in an explicit POST variable
    String json = URLEncoder.encode(Guanxi.REQUEST_PARAMETER_SAML_ATTRIBUTES, "UTF-8") + "="
            + URLEncoder.encode(bag.toJSON(), "UTF-8");

    OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
    wr.write(json);
    wr.flush();
    wr.close();

    // ...and read the response from the Guard
    return new String(Utils.read(connection.getInputStream()));
}

From source file:org.spiffyui.server.AuthServlet.java

private void doLogout(HttpServletRequest request, HttpServletResponse response, String token, String tsUrl)
        throws ServletException, IOException {
    if (token == null || tsUrl == null) {
        returnError(response, "Logout requires a token and a token server URL",
                RESTAuthConstants.INVALID_LOGOUT_REQUEST);
        return;/*from   w w w.ja v a  2 s  .c  o m*/
    }

    LOGGER.info("Making logout request for " + token + " to server " + tsUrl);

    try {
        validateURI(request, tsUrl);
    } catch (IllegalArgumentException iae) {
        returnError(response, iae.getMessage(), RESTAuthConstants.INVALID_TS_URL);
        return;
    }

    HttpClient httpclient = new DefaultHttpClient();

    URI.create(tsUrl);
    URL url = new URL(tsUrl);

    LOGGER.info("url: " + url);

    if (url.getProtocol() != null && url.getProtocol().equalsIgnoreCase("https")) {
        setupClientSSL(httpclient, url.getPort());
    }

    HttpDelete httpdel = new HttpDelete(tsUrl + "/" + URLEncoder.encode(token, "UTF-8"));

    httpdel.setHeader("Accept", "application/json");
    httpdel.setHeader("Accept-Charset", "UTF-8");
    httpdel.setHeader("Authorization", request.getHeader("Authorization"));
    httpdel.setHeader("TS-URL", request.getHeader("TS-URL"));

    // Execute the request
    HttpResponse authResponse = httpclient.execute(httpdel);

    int status = authResponse.getStatusLine().getStatusCode();
    if (status == 404) {
        LOGGER.info("The authentication server " + tsUrl + " was not found.");
        returnError(response, "The token server URL was not found", RESTAuthConstants.NOTFOUND_TS_URL);
        return;
    }

    // Get hold of the response entity
    HttpEntity entity = authResponse.getEntity();

    StringBuffer authResponseData = new StringBuffer();

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = entity.getContent();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(instream));

            // do something useful with the response
            authResponseData.append(reader.readLine());
        } catch (RuntimeException ex) {
            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            httpdel.abort();
            LOGGER.throwing(AuthServlet.class.getName(), "doLogout", ex);
            throw ex;
        } finally {
            // Closing the input stream will trigger connection release
            if (reader != null) {
                reader.close();
            }
        }

        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    //Now we write the response back to our client.
    response.setStatus(status);
    OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
    out.write(authResponseData.toString());

    out.flush();
    out.close();
}