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.mindengine.oculus.frontend.web.controllers.SimpleAjaxController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    AjaxModel model = null;// w ww .  ja  v a 2s. c o m
    try {
        model = handleController(request);
        if (model == null)
            throw new Exception("The controller returned null model");
    } catch (Exception ex) {
        logger.error(ex, ex);
        model = new AjaxModel(ex);
    }

    OutputStream os = response.getOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(os);
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");

    JSONValue jsonValue = JSONMapper.toJSON(model);
    w.write(jsonValue.render(true));

    w.flush();
    os.flush();
    os.close();

    return null;
}

From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java

public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;/*from   w  ww  .j  a  v  a 2  s .  c  o m*/

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

From source file:net.facework.core.http.ModAssetServer.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;//from  w  ww  .java2s  .  c  o m

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

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);/*from w  w  w. j  a v  a 2s. c o  m*/
    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.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   w  ww  . j ava2s .  c o m*/
                }
            }
        }
    }

    // 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.kurento.kmf.content.internal.ControlProtocolManager.java

/**
 * Internal implementation for sending JSON (called from sendJsonAnswer and
 * sendJsonError methods)./*from   w  ww.  j a v a 2s. co m*/
 * 
 * @param asyncCtx
 *            Asynchronous context
 * @param message
 *            JSON message (as a Java class)
 * @throws IOException
 *             Exception while parsing operating with asynchronous context
 */
private void internalSendJsonAnswer(AsyncContext asyncCtx, JsonRpcResponse message) {
    try {
        if (asyncCtx == null) {
            throw new KurentoMediaFrameworkException("Null asyncCtx found", 20017);
        }

        synchronized (asyncCtx) {
            if (!asyncCtx.getRequest().isAsyncStarted()) {
                throw new KurentoMediaFrameworkException("Cannot send message in completed asyncCtx", 1); // TODO
            }

            HttpServletResponse response = (HttpServletResponse) asyncCtx.getResponse();
            response.setContentType("application/json");
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), UTF8);
            osw.write(gson.toJson(message));
            osw.flush();
            log.info("Sent JsonRpc answer ...\n" + message);
            asyncCtx.complete();
        }
    } catch (IOException ioe) {
        throw new KurentoMediaFrameworkException(ioe.getMessage(), ioe, 20018);
    }
}

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

/**
 * @param request/*from   w ww  .j a v  a  2 s  . c o m*/
 * @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.personalserver.DirCommandHandler.java

private HttpEntity getEntityFromUri(String uri, HttpResponse response) {
    String contentType = "text/html";
    String filepath = FOLDER_SHARE_PATH;

    if (uri.equalsIgnoreCase("/") || uri.length() <= 0) {
        filepath = FOLDER_SHARE_PATH + "/";
    } else {/*from www .j a  v  a  2s .c  o m*/
        filepath = FOLDER_SHARE_PATH + "/" + URLDecoder.decode(uri);
    }

    System.out.println("request uri : " + uri);
    System.out.println("FOLDER SHARE PATH : " + FOLDER_SHARE_PATH);
    System.out.println("filepath : " + filepath);

    final File file = new File(filepath);

    HttpEntity entity = null;

    if (file.isDirectory()) {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = getDirListingHTML(file);

                writer.write(resp);
                writer.flush();
            }
        });

        response.setHeader("Content-Type", contentType);
    } else if (file.exists()) {
        contentType = URLConnection.guessContentTypeFromName(file.getAbsolutePath());

        entity = new FileEntity(file, contentType);

        response.setHeader("Content-Type", contentType);
    } else {
        entity = new EntityTemplate(new ContentProducer() {
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = "<html>" + "<head><title>ERROR : NOT FOUND</title></head>" + "<body>"
                        + "<center><h1>FILE OR DIRECTORY NOT FOUND !</h1></center>"
                        + "<p>Sorry, file or directory you request not available<br />"
                        + "Contact your administrator<br />" + "</p>" + "</body></html>";

                writer.write(resp);
                writer.flush();
            }
        });
        response.setHeader("Content-Type", "text/html");
    }

    return entity;
}

From source file:eu.comvantage.dataintegration.SparulSimulationServlet.java

private void simulateEvent(String eventID, String endpoint) {
    //container for the final SPARUL update command including header information
    String body = "";
    //additional body information for the SPARUL update command

    //try to encode the SPARUL update command string with UTF-8
    String temp = "";
    Gson gson = new Gson();

    //simulation of a correct request
    if (eventID.equalsIgnoreCase("sparul1")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket0070071239swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn00110011\"}]" + "}";
    }/*w w w. jav a  2 s . co m*/
    //simulation of invalid template id for client
    else if (eventID.equalsIgnoreCase("sparul2")) {
        temp = "{ " + "\"Template\" : 8, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket008008123swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn1234567\"}]" + "}";
    }
    //simulation of invalid client id
    else if (eventID.equalsIgnoreCase("sparul3")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 3, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket000000000swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn55555\"}]" + "}";
    }
    //simulation of invalid parameter for specified template
    else if (eventID.equalsIgnoreCase("sparul4")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}";
    }
    //simulation of invalid parameter for specified template
    else if (eventID.equalsIgnoreCase("sparul5")) {
        temp = "{ " + "\"Templates\" : 1, " + "\"Clients\" : 1, "
                + "\"Param\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}";
    }
    //malformed json
    else if (eventID.equalsIgnoreCase("sparul6")) {
        temp = "blabla";
    }
    //simulation of a correct request
    else if (eventID.equalsIgnoreCase("sparul7")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:Ticket0070071239swd\"}], " + "}";
        //test of the long statement parameters of file client1_test0
    } else if (eventID.equalsIgnoreCase("sparul8")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:test1\"}, "
                + "{\"name\":\"reportId\", \"value\":\"1\"},"
                + "{\"name\":\"device1\", \"value\":\"tee:test2\"},"
                + "{\"name\":\"device2\", \"value\":\"tee:test3\"},"
                + "{\"name\":\"device3\", \"value\":\"tee:test4\"}]" + "}";

    }
    //body = gson.toJson(temp);
    body = temp;

    //try to execute the SPARUL update command
    try {
        //insertion is done by a manual HTTP post
        HttpPost httpPost = new HttpPost(endpoint);

        //put SPARUL update command to output stream
        ByteArrayOutputStream b_out = new ByteArrayOutputStream();
        OutputStreamWriter wr = new OutputStreamWriter(b_out);
        wr.write(body);
        wr.flush();

        //transform output stream and modify header information for HTTP post             
        byte[] bytes = b_out.toByteArray();
        AbstractHttpEntity reqEntity = new ByteArrayEntity(bytes);
        reqEntity.setContentType("application/x-www-form-urlencoded");
        reqEntity.setContentEncoding(HTTP.UTF_8);
        httpPost.setEntity(reqEntity);
        httpPost.setHeader("role", "http://www.comvantage.eu/ontologies/ac-schema/cv_wp6_comau_employee");

        HttpClient httpclient = new DefaultHttpClient();

        //          //set proxy if defined
        //            if(System.getProperty("http.proxyHost") != null) {
        //               HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), Integer.valueOf(System.getProperty("http.proxyPort")), "http");
        //                httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        //            }

        try {
            //execute the HTTP put
            System.out.println(
                    "SparulSimulationServlet: Event '" + eventID + "' simulated at endpoint " + endpoint);
            HttpResponse response = httpclient.execute(httpPost);

            //handle different server responses and failures
            int responseCode = response.getStatusLine().getStatusCode();
            String responseMessage = response.getStatusLine().getReasonPhrase();
            System.out.println("SparulSimulationServlet: Response = " + responseCode + ", " + responseMessage);
            //close the output stream
            wr.close();
        } catch (IOException ex) {
            throw new Exception(ex);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}