Example usage for javax.servlet ServletOutputStream write

List of usage examples for javax.servlet ServletOutputStream write

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream write.

Prototype

public abstract void write(int b) throws IOException;

Source Link

Document

Writes the specified byte to this output stream.

Usage

From source file:org.wso2.adminui.AdminUIServletFilter.java

private void initGlobalParams(HttpServletResponse response) throws IOException {
    String localContext = AdminUIServletContextListener.contextPath;

    String servletCtxPath = (String) servletContext.getAttribute(AdminUIConstants.SERVICE_CONTEXT_PATH);
    String httpPort = (String) servletContext.getAttribute(AdminUIConstants.HTTP_PORT);
    String httpsPort = (String) servletContext.getAttribute(AdminUIConstants.HTTPS_PORT);

    String globalParamString = "SERVICE_PATH = \"" + servletCtxPath + "\";\n" + "ROOT_CONTEXT = \""
            + localContext + "\";\n" + "HTTP_PORT = " + httpPort + ";\n" + "HTTPS_PORT = " + httpsPort + ";\n";
    ServletOutputStream op = response.getOutputStream();
    response.setContentType("text/html");
    response.setContentLength(globalParamString.getBytes().length);
    op.write(globalParamString.getBytes());

}

From source file:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping(value = "/read-byte", produces = MediaType.TEXT_PLAIN_VALUE)
public void readByte(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    final ServletInputStream input = request.getInputStream();
    final ServletOutputStream output = response.getOutputStream();

    while (true) {
        final int read = input.read();
        if (read == -1) {
            break;
        }//from  w w  w  . j a  v a  2  s .  c o  m
        output.write(read);
    }
}

From source file:org.waterforpeople.mapping.app.web.WaterForPeopleMappingGoogleServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String showKML = req.getParameter("showKML");
    @SuppressWarnings("unused")
    String processFile = req.getParameter("processFile");
    String showRegion = req.getParameter("showRegion");
    String action = req.getParameter("action");
    String countryCode = req.getParameter("countryCode");
    if (showKML != null) {
        Long kmlKey = null;/*from   w  ww .  ja va  2  s . c o  m*/
        if (req.getParameter("kmlID") != null) {
            kmlKey = Long.parseLong(req.getParameter("kmlID"));
        }
        if (kmlKey != null) {
            KMLDAO kmlDAO = new KMLDAO();
            String kmlString = kmlDAO.getKML(kmlKey);
            resp.setContentType("application/vnd.google-earth.kml+xml");
            resp.getWriter().println(kmlString);

        } else {
            KMLGenerator kmlGen = new KMLGenerator();
            String placemarksDocument = null;
            String timestamp = DateFormatUtils.formatUTC(new Date(),
                    DateFormatUtils.ISO_DATE_FORMAT.getPattern());
            if (countryCode != null) {
                placemarksDocument = kmlGen.generateDocument("PlacemarksNewLook.vm", countryCode);
                resp.setHeader("Content-Disposition",
                        "inline; filename=waterforpeoplemapping_" + countryCode + "_" + timestamp + ".kmz;");
            } else {
                placemarksDocument = kmlGen.generateDocument("PlacemarksNewLook.vm");
                resp.setHeader("Content-Disposition",
                        "inline; filename=waterforpeoplemapping_" + timestamp + "_.kmz;");
            }
            // ToDo implement kmz compression now that kmls are so big
            // application/vnd.google-earth.kmz
            resp.setContentType("application/vnd.google-earth.kmz+xml");
            ServletOutputStream out = resp.getOutputStream();

            ByteArrayOutputStream os = ZipUtil.generateZip(placemarksDocument, "waterforpeoplemapping.kml");
            out.write(os.toByteArray());
            out.flush();

        }
    } else if (showRegion != null) {
        KMLGenerator kmlGen = new KMLGenerator();
        String placemarksDocument = kmlGen.generateRegionDocumentString("Regions.vm");
        resp.setContentType("application/vnd.google-earth.kml+xml");
        resp.getWriter().println(placemarksDocument);

    } else if ("getLatestMap".equals(action)) {
        MapFragmentDao mfDao = new MapFragmentDao();
        List<MapFragment> mfList = mfDao.searchMapFragments(null, null, null,
                FRAGMENTTYPE.GLOBAL_ALL_PLACEMARKS, "all", "createdDateTime", "desc");
        Blob map = mfList.get(0).getBlob();
        resp.setContentType("application/vnd.google-earth.kmz+xml");
        ServletOutputStream out = resp.getOutputStream();
        resp.setHeader("Content-Disposition", "inline; filename=waterforpeoplemapping.kmz;");
        out.write(map.getBytes());
        out.flush();
    }
}

From source file:de.micromata.genome.logging.loghtmlwindow.LogHtmlWindowServlet.java

private void sendResponse(HttpServletResponse resp, JsonValue val) throws IOException {
    resp.setContentType("application/json");
    String sr = val.toString();
    ServletOutputStream os = resp.getOutputStream();
    os.write(sr.getBytes("UTF-8"));
    os.flush();//from   ww w . j ava 2s.c  o m
}

From source file:com.mobicage.rogerthat.CallbackApiServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json-rpc; charset=utf-8");

    // Validate incomming request
    final String contentType = req.getHeader("Content-type");
    if (contentType == null || !contentType.startsWith("application/json-rpc")) {
        resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        return;//from   w  w w. j a va 2  s.co m
    }
    final String sikKey = req.getHeader("X-Nuntiuz-Service-Key");
    if (!validateSIK(sikKey)) {
        resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
        return;
    }

    // Parse
    final InputStream is = req.getInputStream();
    final JSONObject request;
    try {
        request = (JSONObject) JSONValue.parse(new BufferedReader(new InputStreamReader(is, "UTF-8")));
    } finally {
        is.close();
    }

    if (logTraffic)
        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sikKey,
                request.toJSONString()));

    final String id = (String) request.get("id");

    if (callbackDedup != null) {
        byte[] response = callbackDedup.getResponse(id);
        if (response != null) {
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.write(response);
            outputStream.flush();
            return;
        }
    }

    final JSONObject result = new JSONObject();
    final RequestContext requestContext = new RequestContext(id, sikKey);
    try {
        processor.process(request, result, requestContext);
    } finally {
        String jsonString = result.toJSONString();
        if (logTraffic)
            log.info("Returning result:\n" + jsonString);

        byte[] response = jsonString.getBytes("UTF-8");
        if (callbackDedup != null) {
            callbackDedup.storeResponse(id, response);
        }

        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(response);
        outputStream.flush();
    }
}

From source file:org.loklak.api.cms.ProxyServlet.java

protected void process(HttpServletRequest request, HttpServletResponse response, Query post)
        throws ServletException, IOException {

    // parse arguments
    String url = post.get("url", "");
    String screen_name = post.get("screen_name", "");
    DAO.log("PROXY: called with screen_name=" + screen_name + ", url=" + url);

    if (screen_name.length() == 0 && (url.length() == 0 || screen_name.indexOf("twimg.com") < 0)) {
        response.sendError(503, "either attributes url or screen_name or both must be submitted");
        return;//from  w w w. j  av  a2  s  . co m
    }

    byte[] buffer = url.length() == 0 ? null : cache.get(url);
    if (buffer != null)
        DAO.log("PROXY: got url=" + url + " content from ram cache!");
    UserEntry user = null;

    if (buffer == null && screen_name.length() > 0) {
        if (buffer == null && (url.length() == 0 || isProfileImage(url))) {
            // try to read it from the user profiles
            user = DAO.searchLocalUserByScreenName(screen_name);
            if (user != null) {
                buffer = user.getProfileImage();
                if (buffer != null)
                    DAO.log("PROXY: got url=" + url + " content from user profile bas64 cache!");
                if (url.length() == 0)
                    url = user.getProfileImageUrl();
                cache.put(user.getProfileImageUrl(), buffer);
            }
        }
    }

    if (buffer == null && url.length() > 0) {
        // try to download the image
        buffer = ClientConnection.download(url);
        String newUrl = user == null ? null : user.getProfileImageUrl();
        if (buffer != null) {
            DAO.log("PROXY: downloaded given url=" + url + " successfully!");
        } else if (newUrl != null && !newUrl.equalsIgnoreCase(url)) {
            // if this fails, then check if the stored url is different.
            // That may happen because new user avatar images get new urls
            buffer = ClientConnection.download(newUrl);
            if (buffer != null)
                DAO.log("PROXY: downloaded url=" + url + " from old user setting successfully!");
        }
        if (buffer == null) {
            // ask the Twitter API for new user data
            try {
                JSONObject usermap = TwitterAPI.getUser(screen_name, true);
                newUrl = usermap.has("profile_image_url") ? (String) usermap.get("profile_image_url") : null;
                if (newUrl != null && newUrl.length() > 0 && !newUrl.startsWith("http:")
                        && usermap.has("profile_image_url_https"))
                    newUrl = (String) usermap.get("profile_image_url_https");
                if (newUrl != null && newUrl.length() > 0)
                    buffer = ClientConnection.download(newUrl);
                if (buffer != null)
                    DAO.log("PROXY: downloaded url=" + url
                            + " from recently downloaded user setting successfully!");
            } catch (TwitterException e) {
                DAO.log("ProxyServlet: call to twitter api failed: " + e.getMessage());
            }
        }
        if (buffer != null) {
            // write the buffer
            if (user != null) {
                user.setProfileImageUrl(newUrl);
                user.setProfileImage(buffer);
                try {
                    // record user into search index
                    DAO.users.writeEntry(new IndexEntry<UserEntry>(user.getScreenName(), user.getType(), user));
                } catch (IOException e) {
                    Log.getLog().warn(e);
                }
                if (!cache.full())
                    cache.put(url, buffer);
            } else {
                cache.put(url, buffer);
            }
        }
    }

    if (buffer == null) {
        if (screen_name.length() == 0) {
            response.sendError(503, "url cannot be loaded");
            return;
        }
        if (url.length() == 0) {
            response.sendError(503, "user cannot be found");
            return;
        }
        response.sendError(503, "url cannot be loaded and user cannot be found");
        return;
    }

    if (url.endsWith(".png") || (url.length() == 0 && request.getServletPath().endsWith(".png")))
        post.setResponse(response, "image/png");
    else if (url.endsWith(".gif") || (url.length() == 0 && request.getServletPath().endsWith(".gif")))
        post.setResponse(response, "image/gif");
    else if (url.endsWith(".jpg") || url.endsWith(".jpeg")
            || (url.length() == 0 && request.getServletPath().endsWith(".jpg")))
        post.setResponse(response, "image/jpeg");
    else
        post.setResponse(response, "application/octet-stream");

    ServletOutputStream sos = response.getOutputStream();
    sos.write(buffer);
    post.finalize();
}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

/**
 * This method is used to download files from specified path
 * @param response/*from ww w .  jav  a2s .  c o  m*/
 * @param archiveFile
 */
public static void downloadArchiveFile(HttpServletResponse response, File archiveFile) {
    if (archiveFile.isFile()) {
        response.reset();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + archiveFile.getName() + "\"");
        FileInputStream is = null;
        ServletOutputStream op = null;
        try {
            op = response.getOutputStream();
            double dLength = archiveFile.length();
            int iLength = 0;
            int num_read = 0;

            if (dLength >= Integer.MIN_VALUE && dLength <= Integer.MAX_VALUE) {
                iLength = (int) dLength;
            }
            byte[] arBytes = new byte[iLength];
            is = new FileInputStream(archiveFile);

            while (num_read < iLength) {
                int count = is.read(arBytes, num_read, iLength - num_read);
                if (count < 0) {
                    throw new IOException("end of stream reached");
                }
                num_read += count;
            }
            op.write(arBytes);
            op.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (null != op) {
                try {
                    op.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:com.edgenius.wiki.webapp.action.RSSFeedAction.java

public String execute() {
    Space space;//w  w  w  .  ja v  a  2  s  .  c o  m
    if (NumberUtils.toInt(suid, -1) != -1) {
        int spaceUid = NumberUtils.toInt(suid);
        space = spaceService.getSpace(spaceUid);
    } else {
        space = spaceService.getSpaceByUname(s);
    }
    if (space == null)
        return ERROR;

    User user = WikiUtil.getUser();
    String out = null;
    try {
        out = rssService.outputFeed(space.getUid(), space.getUnixName(), user);
    } catch (FeedException e) {
        log.error("Read feed error ", e);
    }
    try {
        ServletOutputStream writer = getResponse().getOutputStream();
        if (out != null) {
            //out must XML format
            getResponse().setContentType("text/xml");
            writer.write(out.getBytes(Constants.UTF8));
        } else {
            //feed does not exist for some reason, try to re-generate
            writer.write(("Please wait a while for RSS feed generating in system. Refresh later.")
                    .getBytes(Constants.UTF8));
            writer.flush();
            rssService.createFeed(space.getUnixName());
        }
    } catch (IOException e) {
        log.error("unable write out feed", e);
        return ERROR;
    }
    return null;
}

From source file:org.apache.nifi.remote.client.http.TestHttpClient.java

private static void respondWithText(HttpServletResponse resp, String result, int statusCode)
        throws IOException {
    resp.setContentType("text/plain");
    resp.setStatus(statusCode);/*from  www  .j  av a 2  s.c  o m*/
    final ServletOutputStream out = resp.getOutputStream();
    out.write(result.getBytes());
    out.flush();
}

From source file:fast.servicescreen.server.RequestServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //get the URL out of the requests parameter and form escape codes back to a real URL
    String url = req.getParameter("url");

    if (url != null && !"".equals(url)) {
        //execute a GET call with the params URL
        String value = sendHttpRequest_GET(url);

        // to facilitate debugging strip xslt tag
        // value = value.replaceFirst("<\\?xml-stylesheet type=\"text/xsl\" href=\"http://ergast.com/schemas/mrd-1.1.xsl\"\\?>", "");

        //attach the responses output stream
        ServletOutputStream out = resp.getOutputStream();

        //write the GET result into the response (this will trigger
        //the forward to the original transmitter)
        byte[] outByte = value.getBytes("utf-8");
        out.write(outByte);
        out.flush();/*from   w ww.j av  a  2  s  .  co  m*/
        out.close();
    }
}