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:org.opendatakit.odktables.entity.serialization.SimpleHTMLMessageWriter.java

@Override
public void writeTo(T o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> map, OutputStream rawStream)
        throws IOException, WebApplicationException {
    String encoding = getCharsetAsString(mediaType);
    try {/*  w w  w  .  java  2 s  .co  m*/
        if (!encoding.equalsIgnoreCase(DEFAULT_ENCODING)) {
            throw new IllegalArgumentException("charset for the response is not utf-8");
        }
        // write it to a byte array
        ByteArrayOutputStream bas = new ByteArrayOutputStream(8192);
        OutputStreamWriter w = new OutputStreamWriter(bas, Charset.forName(ApiConstants.UTF8_ENCODE));
        w.write("<html><head></head><body>");
        w.write(mapper.writeValueAsString(o));
        w.write("</body></html>");
        w.flush();
        w.close();
        // get the array
        byte[] bytes = bas.toByteArray();
        map.putSingle(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION);
        map.putSingle("Access-Control-Allow-Origin", "*");
        map.putSingle("Access-Control-Allow-Credentials", "true");

        rawStream.write(bytes);
        rawStream.flush();
        rawStream.close();

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:de.fabianonline.telegram_backup.exporter.HTMLExporter.java

public void export(UserManager user) {
    try {/*from w w  w .j a v  a2 s . c  o m*/
        Database db = new Database(user, null);

        // Create base dir
        logger.debug("Creating base dir");
        String base = user.getFileBase() + "files" + File.separatorChar;
        new File(base).mkdirs();
        new File(base + "dialogs").mkdirs();

        logger.debug("Fetching dialogs");
        LinkedList<Database.Dialog> dialogs = db.getListOfDialogsForExport();
        logger.trace("Got {} dialogs", dialogs.size());
        logger.debug("Fetching chats");
        LinkedList<Database.Chat> chats = db.getListOfChatsForExport();
        logger.trace("Got {} chats", chats.size());

        logger.debug("Generating index.html");
        HashMap<String, Object> scope = new HashMap<String, Object>();
        scope.put("user", user);
        scope.put("dialogs", dialogs);
        scope.put("chats", chats);

        // Collect stats data
        scope.put("count.chats", chats.size());
        scope.put("count.dialogs", dialogs.size());

        int count_messages_chats = 0;
        int count_messages_dialogs = 0;
        for (Database.Chat c : chats)
            count_messages_chats += c.count;
        for (Database.Dialog d : dialogs)
            count_messages_dialogs += d.count;

        scope.put("count.messages", count_messages_chats + count_messages_dialogs);
        scope.put("count.messages.chats", count_messages_chats);
        scope.put("count.messages.dialogs", count_messages_dialogs);

        scope.put("count.messages.from_me", db.getMessagesFromUserCount());

        scope.put("heatmap_data", intArrayToString(db.getMessageTimesMatrix()));

        scope.putAll(db.getMessageAuthorsWithCount());
        scope.putAll(db.getMessageTypesWithCount());
        scope.putAll(db.getMessageMediaTypesWithCount());

        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile("templates/html/index.mustache");
        OutputStreamWriter w = getWriter(base + "index.html");
        mustache.execute(w, scope);
        w.close();

        mustache = mf.compile("templates/html/chat.mustache");

        int i = 0;
        logger.debug("Generating {} dialog pages", dialogs.size());
        for (Database.Dialog d : dialogs) {
            i++;
            logger.trace("Dialog {}/{}: {}", i, dialogs.size(), Utils.anonymize("" + d.id));
            LinkedList<HashMap<String, Object>> messages = db.getMessagesForExport(d);
            scope.clear();
            scope.put("user", user);
            scope.put("dialog", d);
            scope.put("messages", messages);

            scope.putAll(db.getMessageAuthorsWithCount(d));
            scope.put("heatmap_data", intArrayToString(db.getMessageTimesMatrix(d)));
            scope.putAll(db.getMessageTypesWithCount(d));
            scope.putAll(db.getMessageMediaTypesWithCount(d));

            w = getWriter(base + "dialogs" + File.separatorChar + "user_" + d.id + ".html");
            mustache.execute(w, scope);
            w.close();
        }

        i = 0;
        logger.debug("Generating {} chat pages", chats.size());
        for (Database.Chat c : chats) {
            i++;
            logger.trace("Chat {}/{}: {}", i, chats.size(), Utils.anonymize("" + c.id));
            LinkedList<HashMap<String, Object>> messages = db.getMessagesForExport(c);
            scope.clear();
            scope.put("user", user);
            scope.put("chat", c);
            scope.put("messages", messages);

            scope.putAll(db.getMessageAuthorsWithCount(c));
            scope.put("heatmap_data", intArrayToString(db.getMessageTimesMatrix(c)));
            scope.putAll(db.getMessageTypesWithCount(c));
            scope.putAll(db.getMessageMediaTypesWithCount(c));

            w = getWriter(base + "dialogs" + File.separatorChar + "chat_" + c.id + ".html");
            mustache.execute(w, scope);
            w.close();
        }

        logger.debug("Generating additional files");
        // Copy CSS
        URL cssFile = getClass().getResource("/templates/html/style.css");
        File dest = new File(base + "style.css");
        FileUtils.copyURLToFile(cssFile, dest);
        logger.debug("Done exporting.");
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Exception above!");
    }
}

From source file:com.trafficspaces.api.controller.Connector.java

public String sendRequest(String path, String contentType, String method, String data)
        throws IOException, TrafficspacesAPIException {

    URL url = new URL(endPoint.baseURI + path);

    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);/* w  ww.j  a  va  2  s  . com*/
    httpCon.setRequestMethod(method.toUpperCase());

    String basicAuth = "Basic " + Base64.encodeBytes((endPoint.username + ":" + endPoint.password).getBytes());
    httpCon.setRequestProperty("Authorization", basicAuth);

    httpCon.setRequestProperty("Content-Type", contentType + "; charset=UTF-8");
    httpCon.setRequestProperty("Accept", contentType);

    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        httpCon.setRequestProperty("Content-Length", String.valueOf(data.length()));
        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write(data);
        out.close();
    } else {
        httpCon.connect();
    }

    char[] responseData = null;
    try {
        responseData = readResponseData(httpCon.getInputStream(), "UTF-8");
    } catch (FileNotFoundException fnfe) {
        // HTTP 404. Ignore and return null
    }
    String responseDataString = null;
    if (responseData != null) {
        int responseCode = httpCon.getResponseCode();
        String redirectURL = null;
        if ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                || responseCode == HttpURLConnection.HTTP_CREATED)
                && (redirectURL = httpCon.getHeaderField("Location")) != null) {
            //System.out.println("Response code = " +responseCode + ". Redirecting to " + redirectURL);
            return sendRequest(redirectURL, contentType);
        }
        if (responseCode != HttpURLConnection.HTTP_OK && responseCode != HttpURLConnection.HTTP_CREATED) {
            throw new TrafficspacesAPIException(
                    "HTTP Error: " + responseCode + "; Data: " + new String(responseData));
        }
        //System.out.println("Headers: " + httpCon.getHeaderFields());
        //System.out.println("Data: " + new String(responseData));
        responseDataString = new String(responseData);
    }
    return responseDataString;
}

From source file:com.noshufou.android.su.util.Util.java

private static boolean writeStoreFile(File storeFile, HashMap<String, String> cmds) {
    try {/*from www .  ja v  a2  s  .c o m*/
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(storeFile));
        if (cmds.containsKey("any")) {
            out.write(cmds.get("any") + '\n');
            out.write("any\n");
        } else {
            for (Map.Entry<String, String> entry : cmds.entrySet()) {
                out.write(entry.getValue() + '\n');
                out.write(entry.getKey() + '\n');
            }
        }
        out.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.adamrosenfield.wordswithcrosses.net.DerStandardDownloader.java

private HttpURLConnection getHttpPostConnection(String url, String postData)
        throws IOException, MalformedURLException {
    HttpURLConnection conn = getHttpConnection(url);

    conn.setRequestMethod("POST");
    conn.setDoOutput(true);/*ww  w .ja v  a2 s . co  m*/

    OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
    try {
        osw.append(postData);
    } finally {
        osw.close();
    }

    return conn;
}

From source file:com.commerce4j.storefront.controllers.CartController.java

@SuppressWarnings("unchecked")
public void update(HttpServletRequest request, HttpServletResponse response) {

    Gson gson = new GsonBuilder().create();
    List<Message> errors = new ArrayList<Message>();
    Map<String, Object> responseModel = new HashMap<String, Object>();

    List<CartDTO> cartEntries = getCart(request);
    Iterator inputSet = request.getParameterMap().keySet().iterator();
    while (inputSet.hasNext()) {
        String paramName = (String) inputSet.next();
        if (StringUtils.contains(paramName, "qty")) {
            String paramValue = request.getParameter(paramName);
            String paramId = StringUtils.substring(paramName, 4, paramName.length());
            if (paramId != null && StringUtils.isNumeric(paramId)) {
                for (CartDTO cartEntry : cartEntries) {
                    int entryId = cartEntry.getItem().getItemId().intValue();
                    int itemId = new Integer(paramId).intValue();
                    int cartQuantity = new Integer(paramValue).intValue();
                    if (entryId == itemId) {
                        cartEntry.setCartQuantity(cartQuantity);
                        cartEntry.setCartSubTotal(cartEntry.getItem().getItemPrice() * cartQuantity);
                        break;
                    }//from   ww  w  .j  av a  2 s.  c  om
                }
            }
        }
    }

    // fill response model
    if (errors.isEmpty()) {
        responseModel.put("responseCode", SUCCESS);
        responseModel.put("responseMessage", "Cart succesfully updated");
    } else {
        responseModel.put("responseCode", FAILURE);
        responseModel.put("responseMessage", "Error, Cart was not updated");
        responseModel.put("errors", errors);
    }

    // serialize output
    try {
        response.setContentType("application/json");
        OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream());
        String data = gson.toJson(responseModel);
        os.write(data);
        os.flush();
        os.close();
    } catch (IOException e) {
        logger.fatal(e);
    }

}

From source file:com.commerce4j.storefront.controllers.CartController.java

/**
 * @param request/*from   ww w.j  a v a2s .c  om*/
 * @param response
 */
public void add(HttpServletRequest request, HttpServletResponse response) {

    Gson gson = new GsonBuilder().create();
    List<Message> errors = new ArrayList<Message>();
    Map<String, Object> responseModel = new HashMap<String, Object>();

    String item = request.getParameter("item");
    String quantity = request.getParameter("quantity");

    if (StringUtils.isEmpty(item)) {
        errors.add(newError("item", getString("errors.notEmpty"), new Object[] { "item" }));
    }

    // find item
    ItemDTO itemDTO = getItemDSO().findById(new Integer(item));
    if (item == null)
        errors.add(newError("item", getString("errors.notEmpty"), new Object[] { "item" }));

    // check cart in session
    List<CartDTO> cartEntries = getCart(request);

    // create cart entry
    String cartId = request.getSession().getId();
    Integer iQuantity = new Integer(quantity);
    Double subtotal = itemDTO.getItemPrice() * iQuantity;
    CartDTO cartDTO = new CartDTO(cartId, itemDTO, iQuantity, subtotal);
    cartEntries.add(cartDTO);

    // persist session
    request.getSession().setAttribute("cart", cartEntries);

    // fill response model
    if (errors.isEmpty()) {
        responseModel.put("responseCode", SUCCESS);
        responseModel.put("responseMessage", "Item Added to Cart");
    } else {
        responseModel.put("responseCode", FAILURE);
        responseModel.put("responseMessage", "Error, item was not added");
        responseModel.put("errors", errors);
    }

    // serialize output
    try {
        response.setContentType("application/json");
        OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream());
        String data = gson.toJson(responseModel);
        os.write(data);
        os.flush();
        os.close();
    } catch (IOException e) {
        logger.fatal(e);
    }
}

From source file:com.culvereq.vimp.networking.ConnectionHandler.java

public String login(String username, String password) throws IOException {
    URL requestURL = new URL(loginURL);
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
    connection.setDoInput(true);//  w  ww  . j  ava 2s  .com
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    String urlParameters = "";
    urlParameters += "username=" + username;
    urlParameters += "&password=" + password;

    connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length);
    connection.setUseCaches(false);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(urlParameters);
    writer.flush();
    writer.close();

    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString().trim();
    } else {
        return null;
    }
}

From source file:com.garethahealy.quotalimitsgenerator.cli.parsers.YamlTemplateProcessor.java

public void process(QuotaLimitModel quotaLimitModel) throws IOException, TemplateException {
    Map<String, QuotaLimitModel> root = new HashMap<String, QuotaLimitModel>();
    root.put("model", quotaLimitModel);

    if (!new File(quotaLimitModel.getOutputPath().toString()).mkdirs()) {
        throw new IOException("Failed to create directory for; " + quotaLimitModel.getOutputPath().toString());
    }// w w  w  . ja  v  a 2 s  .  c  o m

    for (Pair<String, Template> current : templates) {
        LOG.info("{}/{}.yaml", quotaLimitModel.getOutputPath().toString(), current.getKey());

        File yamlFile = new File(quotaLimitModel.getOutputPath().toString() + "/" + current.getKey() + ".yaml");
        if (!yamlFile.createNewFile()) {
            throw new IOException("Failed to create file for; " + current.getKey());
        }

        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(yamlFile), Charset.forName("UTF-8"));
            current.getValue().process(root, writer);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}