Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:orca.ndllib.ndl.RequestSaver.java

/**
 * Save to file/*  w w  w .  j ava  2s  .  c o m*/
 * @param f
 * @param g
 * @param nsGuid
 * @return
 */
public boolean saveNewRequest(File f) {
    assert (f != null);

    String ndl = convertGraphToNdl();
    if (ndl == null) {
        return false;
    }

    try {
        FileOutputStream fsw = new FileOutputStream(f);
        OutputStreamWriter out = new OutputStreamWriter(fsw, "UTF-8");
        out.write(ndl);
        out.close();
        return true;
    } catch (FileNotFoundException e) {
        request.logger().debug("saveGraph: FileNotFoundException");
        ;
    } catch (UnsupportedEncodingException ex) {
        request.logger().debug("saveGraph: UnsupportedEncodingException");
        ;
    } catch (IOException ey) {
        request.logger().debug("saveGraph: IOException");
        ;
    }
    return false;
}

From source file:compiler.downloader.MegaHandler.java

private String api_request(String data) {
    HttpURLConnection connection = null;
    try {//w  w  w. j  a v a2s. 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.lhtechnologies.DoorApp.AuthenticatorService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();/*  ww  w . j ava2  s  . c  o  m*/
    } else if (intent.getAction().equals(authenticateAction)) {
        //Check if we want to open the front door or flat door
        String doorToOpen = FrontDoor;
        String authCode = null;
        if (intent.hasExtra(FlatDoor)) {
            doorToOpen = FlatDoor;
            authCode = intent.getCharSequenceExtra(FlatDoor).toString();
        }

        if (intent.hasExtra(LetIn)) {
            doorToOpen = LetIn;
        }

        //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES
        urlConnection = null;
        URL url;

        //Prepare the return intent
        Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast);

        try {
            //Try to create the URL, return an error if it fails
            url = new URL(address);

            if (!url.getProtocol().equals("https")) {
                throw new MalformedURLException("Please only use https protocol!");
            }

            String password = "password";
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"),
                    password.toCharArray());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(context.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");

            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);

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

            //Write our stuff to the output stream;
            out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion="
                    + clientVersion + "&doorToOpen=" + doorToOpen);
            if (doorToOpen.equals(FlatDoor)) {
                out.write("&authCode=" + authCode);
                //Put an extra in so the return knows we opened the flat door
                broadcastIntent.putExtra(FlatDoor, FlatDoor);
            }

            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            //Read the answer
            String decodedString;
            String returnString = "";
            while ((decodedString = in.readLine()) != null) {
                returnString += decodedString;
            }
            in.close();

            broadcastIntent.putExtra(AuthenticatorReturnCode, returnString);

        } catch (MalformedURLException e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL);
        } catch (Exception e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined);
            broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage());
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
            //Now send a broadcast with the result
            sendOrderedBroadcast(broadcastIntent, null);
            Log.e(this.getClass().getSimpleName(), "Send Broadcast!");
        }
    }

}

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;// w w w  .  jav a  2  s .c o m
    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:cn.edu.henu.rjxy.lms.controller.Tea_Controller.java

@RequestMapping(value = "saveTree", method = RequestMethod.POST)
public @ResponseBody String saveTree(HttpServletRequest request, @RequestBody Tree3[] users) throws Exception {
    String sn = getCurrentUsername();
    Teacher tec = TeacherDao.getTeacherBySn(sn);
    String tec_sn = tec.getTeacherSn();
    String tec_name = tec.getTeacherName();
    String collage = tec.getTeacherCollege();
    String term = request.getParameter("term");
    String courseName = request.getParameter("courseName");
    // ...//???????? //
    File f = new File(getFileFolder(request) + term + "/" + collage + "/" + tec_sn + "/" + tec_name + "/"
            + courseName + "/" + "" + "/");
    //??//  w w w . j a v a2 s. c  o  m
    if (!f.exists() && !f.isDirectory()) {
        System.out.println("?");
        f.mkdirs();
    } else {
        System.out.println("");
    }
    String ff = getFileFolder(request) + term + "/" + collage + "/" + tec_sn + "/" + tec_name + "/" + courseName
            + "/" + "" + "/";
    List list = new LinkedList();
    String ss = "", aa;
    for (int i = 0; i < users.length - 1; i++) {
        list.add(users[i]);
        aa = JSONObject.fromObject(users[i]) + "";
        ss += aa + ',';
    }
    aa = JSONObject.fromObject(users[3]) + "";
    ss = ss + aa;
    ss = '[' + ss + ']';
    System.out.println(ss);
    PrintStream ps = null;
    OutputStreamWriter pw = null;//?
    pw = new OutputStreamWriter(new FileOutputStream(new File(ff + File.separator + "test.json")), "GBK");
    pw.write(ss);
    pw.close();
    return "1";
}

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

public void execute() throws MojoExecutionException, MojoFailureException {

    if (this.includeDependencySources) {

        //@formatter:off
        executeMojo(//from ww w. j  ava  2  s  . 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:minikbextractor.SparqlProxy.java

public boolean storeData(StringBuilder query, boolean makeQuery) {
    boolean ret = true;
    if (makeQuery)
        query = SparqlProxy.makeQuery(query);
    HttpURLConnection connection = null;
    try {/*from  w w  w .  jav a2s .  c  o m*/
        String urlParameters = "update=" + URLEncoder.encode(query.toString(), "UTF-8");
        URL url = new URL(this.urlServer + "update");
        //Create connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rep = "";
        while ((line = reader.readLine()) != null) {
            rep += line;
        }
        writer.close();
        reader.close();
    } catch (Exception e) {
        System.err.println("ERROR UPDATE : " + e);
        SparqlProxy.saveQueryOnFile("Query.sparql", query.toString());
        ret = false;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return ret;
}

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  .  j  a v a2 s  .c  om
        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 {//from www .  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\"]");

}

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

@PUT
@Produces("application/json")
@Path("/nuevaOc/{canal}/{cant}/{sku}/{proveedor}/{cliente}/{precio}/{fechae}")
public String hacerOrdenCompra(@PathParam("canal") String canal, @PathParam("cant") String cant,
        @PathParam("sku") String sku, @PathParam("proveedor") String proveedor,
        @PathParam("cliente") String cliente, @PathParam("precio") String precio,
        @PathParam("fechae") String fechae) throws MalformedURLException, IOException {
    try {/*from  w  w  w . ja  v  a  2  s .  c  o m*/
        URL url = new URL("http://localhost:83/crear");

        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 sss = "{\n" + "  \"cliente\": \"" + cliente + "\",\n" + "  \"proveedor\": \"" + proveedor
                + "\",\n" + "  \"sku\": \"" + sku + "\",\n" + "  \"fechaEntrega\": \"" + fechae + "\",\n"
                + "  \"precioUnitario\": \"" + precio + "\",\n" + "  \"cantidad\": \"" + cant + "\",\n"
                + "  \"canal\": \"" + canal + "\"\n" + "}";

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(sss);
        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\"]");

}