Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

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

private void saveToFile(File f) throws LevelSavingException {
    OutputStream output;// ww w  .jav  a2 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.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));//from w w  w  . ja v  a2  s.c  om
    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.thoughtworks.go.server.dashboard.AbstractDashboardGroup.java

protected String digest(String permissionsSegment) {
    try {/*ww w  . j a  va 2 s. co  m*/
        MessageDigest digest = DigestUtils.getSha256Digest();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                new DigestOutputStream(new NullOutputStream(), digest));
        outputStreamWriter.write(getClass().getSimpleName());
        outputStreamWriter.write("$");
        outputStreamWriter.write(name());
        outputStreamWriter.write("/");
        outputStreamWriter.write(permissionsSegment);
        outputStreamWriter.write("[");

        for (GoDashboardPipeline pipeline : allPipelines()) {
            outputStreamWriter.write(pipeline.cacheSegment());
            outputStreamWriter.write(",");
        }

        outputStreamWriter.write("]");
        outputStreamWriter.flush();

        return Hex.encodeHexString(digest.digest());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

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
 *//* w  w  w  .java  2 s. c  o 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;
}

From source file:compiler.downloader.MegaHandler.java

private String api_request(String data) {
    HttpURLConnection connection = null;
    try {/*from ww  w.  java2  s  .c  om*/
        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.predic8.membrane.core.interceptor.statistics.StatisticsCSVInterceptor.java

private void writeHeaders() throws Exception {
    synchronized (fileName) {
        FileOutputStream fos = new FileOutputStream(fileName, true);
        try {/*w ww  .  j ava 2  s  . c om*/
            OutputStreamWriter w = new OutputStreamWriter(fos, Constants.UTF_8_CHARSET);

            writeCSV("Status Code", w);
            writeCSV("Time", w);
            writeCSV("Rule", w);
            writeCSV("Method", w);
            writeCSV("Path", w);
            writeCSV("Client", w);
            writeCSV("Server", w);
            writeCSV("Request Content-Type", w);
            writeCSV("Request Content Length", w);
            writeCSV("Response Content-Type", w);
            writeCSV("Response Content Length", w);
            writeCSV("Duration", w);
            writeNewLine(w);
            w.flush();
        } finally {
            fos.close();
        }
    }
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass,
        Object object, HashMap<String, String> headers) throws IOException {
    URL serverAddress;//from  w ww. j  a v  a  2s. com
    HttpURLConnection connection;
    BufferedReader br;
    String result = "";
    try {
        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setInstanceFollowRedirects(false);
        boolean doOutput = doOutput(verb);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method(verb));
        connection.setRequestProperty("Authorization", headers.get("authorization"));
        connection.addRequestProperty("Accept", "application/json");

        if (doOutput) {
            connection.addRequestProperty("Content-Length", "0");
            OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
            os.write("");
            os.flush();
            os.close();
        }
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER
                || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            Link location = parseLocationLinkFromString(connection.getHeaderField("Location"));
            Link l = new Link("self", "/tokens", "GET", "", true);
            ArrayList<Link> links = new ArrayList<Link>();
            links.add(l);
            links.add(location);
            ResponseData data = new ResponseData();
            data.setLocation(location);
            data.setLinks(links);
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println("Authentication expired: " + connection.getResponseMessage());
            if (retry && this.tokenData != null) {
                retry = false;
                this.tokenData = null;
                if (authenticate()) {
                    System.out.println(
                            "Reauthentication success, will continue with " + verb + " request on " + url);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + verb);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Server responded with internal server error, trying again in "
                        + RETRY_WAIT_TIME + " msec.");
                try {
                    retry = false;
                    Thread.sleep(RETRY_WAIT_TIME);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println("Server responded with internal server error, please contact dev@nfleet.fi");
            }

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw new IOException(errorString);
        }

        result = readDataFromConnection(connection);
    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return (T) gson.fromJson(result, tClass);
}

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

public void execute() throws MojoExecutionException, MojoFailureException {

    if (this.includeDependencySources) {

        //@formatter:off
        executeMojo(/*from   w  ww . j  a v  a 2 s .  c  om*/
                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.mycompany.grupo6ti.GenericResource.java

@POST
@Produces("application/json")
@Path("/cancelarFactura/{id}/{motivo}")
public String anularFactura(@PathParam("id") String id, @PathParam("motivo") String motivo) {
    try {//from   w ww .  ja v  a2s. c  o m
        URL url = new URL("http://localhost:85/cancel/");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream is;
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setUseCaches(true);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        String idJson = "{\n" + "  \"id\": \"" + id + "\",\n" + "  \"motivo\": \"" + motivo + "\"\n" + "}";
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(idJson);
        out.flush();
        out.close();

        if (conn.getResponseCode() >= 400) {
            is = conn.getErrorStream();
        } else {
            is = conn.getInputStream();
        }
        String result2 = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            result2 += line;
        }
        rd.close();
        return result2;

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

    return ("[\"Test\", \"Funcionando Bien\"]");

}

From source file:com.mycompany.grupo6ti.GenericResource.java

@PUT
@Produces("application/json")
@Path("emitirFactura/{id_oC}")
public String emitirFactura(@PathParam("id_oC") String id_oC) {
    try {/*  ww w . j  a v a  2  s  . c o m*/
        URL url = new URL("http://localhost:85/");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream is;
        conn.setRequestProperty("Accept-Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setUseCaches(true);
        conn.setRequestMethod("PUT");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        String idJson = "{\n" + "  \"oc\": \"" + id_oC + "\"\n" + "}";
        //String idJson2 = "[\"Test\", \"Funcionando Bien\"]";
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(idJson);
        out.flush();
        out.close();

        if (conn.getResponseCode() >= 400) {
            is = conn.getErrorStream();
        } else {
            is = conn.getInputStream();
        }
        String result2 = "";
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            result2 += line;
        }
        rd.close();
        return result2;

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

    return ("[\"Test\", \"Funcionando Bien\"]");

}