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:controllers.base.Application.java

public static Result login(String redirectTo, boolean isGuest) {
    if (isGuest) {
        createWebSession();/*from w w w. java 2  s  .  com*/
    } else {
        String token = request().body().asFormUrlEncoded().get("token")[0];
        String apiKey = Play.application().configuration().getString("rpx.apiKey");
        String data;
        String response = null;
        try {
            data = String.format("token=%s&apiKey=%s&format=json", URLEncoder.encode(token, "UTF-8"),
                    URLEncoder.encode(apiKey, "UTF-8"));
            URL url = new URL("https://rpxnow.com/api/v2/auth_info");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.connect();
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(data);
            osw.close();
            response = IOUtils.toString(conn.getInputStream());
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }

        JsonNode profile = Json.parse(response).path("profile");
        String identifier = profile.path("identifier").asText();

        WebUser user = WebUser.find.where().like("providerId", identifier).findUnique();

        if (user == null) {
            user = new WebUser().setProviderId(identifier).setProfile(Json.stringify(profile));
            user.save();
        }

        createWebSession(user);
    }

    return postLoginRedirect(redirectTo);
}

From source file:com.telefonica.iot.perseo.Utils.java

/**
 * Makes an HTTP POST to an URL sending an body. The URL and body are
 * represented as String.// ww w .j a  v a  2s  .  c  om
 *
 * @param urlStr String representation of the URL
 * @param content Styring representation of the body to post
 *
 * @return if the request has been accompished
 */

public static boolean DoHTTPPost(String urlStr, String content) {
    try {
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        urlConn.setRequestProperty(Constants.CORRELATOR_HEADER, MDC.get(Constants.CORRELATOR_ID));
        urlConn.setRequestProperty(Constants.SERVICE_HEADER, MDC.get(Constants.SERVICE_FIELD));
        urlConn.setRequestProperty(Constants.SUBSERVICE_HEADER, MDC.get(Constants.SUBSERVICE_FIELD));
        urlConn.setRequestProperty(Constants.REALIP_HEADER, MDC.get(Constants.REALIP_FIELD));

        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.info("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me);
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe);
        return false;
    }
}

From source file:de.akquinet.android.androlog.reporter.PostReporter.java

/**
 * Executes the given request as a HTTP POST action.
 *
 * @param url/* w  ww . ja  v a 2  s  . c o  m*/
 *            the url
 * @param params
 *            the parameter
 * @return the response as a String.
 * @throws IOException
 *             if the server cannot be reached
 */
public static void post(URL url, String params) throws IOException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpURLConnection) {
        ((HttpURLConnection) conn).setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
    }
    OutputStreamWriter writer = null;
    try {
        conn.setDoOutput(true);
        writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8"));
        // write parameters
        writer.write(params);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:Main.java

public static String[] execSQL(String dbName, String query) {
    Process process = null;/*from ww  w .  ja v a  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:com.pa165.ddtroops.console.client.Application.java

/**
 * Create new hero in database/*from  w w  w .  ja v a  2 s.  c om*/
 * @param name  hero name
 * @param race  hero race
 * @param xp    hero experience
 */
private static void createHero(String name, String race, String xp) {
    try {
        HeroDTO h = new HeroDTO();
        h.setName(name);
        h.setRace(race);
        h.setXp(Integer.parseInt(xp));
        JSONObject jsonObject = new JSONObject(h);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero/post");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

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

        while (in.readLine() != null) {
        }
        System.out.println("New hero " + h.getName() + " was created.");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when creating new hero");
        System.out.println(e);
    }
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Update hero in database/*w ww  .  ja  v  a 2s. c  o m*/
 * @param id    hero id
 * @param name  hero name
 * @param race  hero race
 * @param xp    hero experience
 */
private static void updateHero(String id, String name, String race, String xp) {
    try {
        HeroDTO h = new HeroDTO();
        h.setId(Long.parseLong(id));
        h.setName(name);
        h.setRace(race);
        h.setXp(Integer.parseInt(xp));
        JSONObject jsonObject = new JSONObject(h);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero/put");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while (in.readLine() != null) {
        }
        System.out.println("Updated hero with id: " + h.getId());
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when updating hero");
        System.out.println(e);
    }
}

From source file:com.amalto.workbench.utils.FileProvider.java

public static IFile createdTempFile(String templateString, String fileNameWithExtension, String charSet) {
    IFile file = null;//from  w  w w  .  j  av a  2  s . c  o  m
    if (templateString != null) {
        try {
            Project project = ProjectManager.getInstance().getCurrentProject();
            IProject prj = ResourceUtils.getProject(project);
            file = prj.getFile(new Path("temp/" + fileNameWithExtension)); //$NON-NLS-1$

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStreamWriter outputStreamWriter = null;
            if ((charSet == null) || (charSet.trim().isEmpty())) {
                outputStreamWriter = new OutputStreamWriter(outputStream);
            } else {
                outputStreamWriter = new OutputStreamWriter(outputStream, charSet);
            }

            outputStreamWriter.write(templateString);
            outputStreamWriter.flush();
            outputStreamWriter.close();

            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            if (file.exists()) {
                file.setContents(inputStream, true, false, null);
            } else {
                file.create(inputStream, true, null);
            }

            inputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Create new role in database//from   w w w. j  a  va 2 s.  c o m
 * @param name  role id
 * @param description   role desc
 * @param energy    role energy
 * @param attack    role attack
 * @param defense   role defense
 */
private static void createRole(String name, String description, String energy, String attack, String defense) {
    try {
        RoleDTO r = new RoleDTO();
        r.setName(name);
        r.setDescription(description);
        r.setEnergy(Integer.parseInt(energy));
        r.setAttack(Integer.parseInt(attack));
        r.setDefense(Integer.parseInt(defense));
        JSONObject jsonObject = new JSONObject(r);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/post");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

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

        while (in.readLine() != null) {
        }
        System.out.println("New role " + r.getName() + " was created.");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when creating new role");
        System.out.println(e);
    }
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Update role in database//from ww w  . j  av  a  2 s .  c o m
 * @param id    role id
 * @param name  role name
 * @param description   role desc
 * @param energy    role energy
 * @param attack    role attack
 * @param defense   role defense
 */
private static void updateRole(String id, String name, String description, String energy, String attack,
        String defense) {
    try {
        RoleDTO r = new RoleDTO();
        r.setId(Long.parseLong(id));
        r.setName(name);
        r.setDescription(description);
        r.setEnergy(Integer.parseInt(energy));
        r.setAttack(Integer.parseInt(attack));
        r.setDefense(Integer.parseInt(defense));
        JSONObject jsonObject = new JSONObject(r);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/put");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while (in.readLine() != null) {
        }
        System.out.println("Updated role with id: " + r.getId());
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when updating role");
        System.out.println(e);
    }
}

From source file:Main.java

public static void writeXMLDocToFile(Document outputDoc, String outFileName) {
    try {//  w w w.ja v  a 2 s .c o  m
        //FileWriter writer = new FileWriter( outFileName );
        final String encoding = "UTF-8";
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFileName), encoding);
        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(outputDoc);
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Could not create output XML file: " + outFileName);
    } catch (TransformerConfigurationException tce) {
        // Error generated by the parser
        System.out.println("* Transformer Factory error");
        System.out.println("  " + tce.getMessage());

        // Use the contained exception, if any
        Throwable x = tce;
        if (tce.getException() != null)
            x = tce.getException();
        x.printStackTrace();
    } catch (TransformerException te) {
        // Error generated by the parser
        System.out.println("* Transformation error");
        System.out.println("  " + te.getMessage());

        // Use the contained exception, if any
        Throwable x = te;
        if (te.getException() != null)
            x = te.getException();
        x.printStackTrace();
    }
}