Example usage for javax.servlet ServletOutputStream close

List of usage examples for javax.servlet ServletOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:com.seer.datacruncher.spring.ConnectionsFileDownloadController.java

public ModelAndView checkValidity(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long connId = Long.parseLong(request.getParameter("connId"));
    ConnectionsEntity connectionEntity = connectionsDao.find(connId);

    keptXSD = getFileContent(connId, connectionEntity);
    Validate result = new Validate();
    if (keptXSD == null || keptXSD.trim().length() == 0) {
        result.setSuccess(false);//from   w w w.j  av  a  2 s  . c om
    } else {
        result.setSuccess(true);
    }
    ServletOutputStream out = null;
    response.setContentType("application/json");
    out = response.getOutputStream();
    out.write(new ObjectMapper().writeValueAsBytes(result));
    out.flush();
    out.close();

    return null;
}

From source file:com.example.cognitive.personality.DemoServlet.java

/**
 * Create and POST a request to the Personality Insights service
 * /*from w ww. j  a  v a  2 s .com*/
 * @param req
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet pesponse
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    logger.info("doPost");

    req.setCharacterEncoding("UTF-8");
    // create the request
    String text = req.getParameter("text");

    try {
        URI profileURI = new URI(baseURL + "/v2/profile").normalize();

        Request profileRequest = Request.Post(profileURI).addHeader("Accept", "application/json")
                .bodyString(text, ContentType.TEXT_PLAIN);

        Executor executor = Executor.newInstance().auth(username, password);
        Response response = executor.execute(profileRequest);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Service error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:org.sakaiproject.signup.tool.downloadEvents.DownloadEventBean.java

private void closeStream(ServletOutputStream out) {
    try {/*from   w w  w. ja v a2  s  .c o  m*/
        out.close();
    } catch (IOException e) {
        log.warn("Error closing the output stream: " + e.getMessage());
    }
}

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);// w w  w . ja v  a  2s  .co m
        out.flush();
        out.close();
    }
}

From source file:com.smartgwt.extensions.fileuploader.server.DownloadServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    // url: /thinkspace/download/project/2/.....
    String path = request.getPathInfo();
    String[] items = path.split("/");
    if (items.length < 3 || !items[1].equals("project")) {
        // if no path info then nothing can be downloaded
        reportError(response);/*  w ww . j a  v a2s. c o  m*/
        return;
    }
    InputStream in = null;
    try {
        int pid = Integer.parseInt(items[2]);
        /*           Project project = ProjectService.get().getProjectById(pid);
                   String contextName = project.getContext();
                 ProjectState state = (ProjectState) request.getSession().getAttribute(contextName);
                 if (state == null) {
                    // if no state then user has not authenticated
                    reportError(response);
                    return;
                 }
        */
        // only files in lib directories can be downloaded
        boolean hasPermission = false;
        for (int i = items.length - 1; i > 2; i--) {
            if (items[i].equals("lib")) {
                hasPermission = true;
                break;
            }
        }
        if (!hasPermission) {
            reportError(response);
            return;
        }
        /*          File f = state.getFileManager().getFile(path);
                  String type = ContentService.get().getContentType(path);
                  response.setContentType(type);
                  response.setContentLength((int)f.length());
                  response.setHeader("Content-Disposition", "inline; filename="+Util.encode(f.getName()));
                  response.setHeader("Last-Modified",hdf.format(new Date(f.lastModified())));
                  in = new BufferedInputStream(new FileInputStream(f));
        */ ServletOutputStream out = response.getOutputStream();
        byte[] buf = new byte[8192];
        int len = 0;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.close();
        out.flush();
    } catch (Exception e) {
        reportError(response);
        log.error(e);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
        ;
    }
}

From source file:sf.net.experimaestro.server.JsonRPCServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {// w  w  w . j a v a2s.co m
        JsonCallHandler handler = new JsonCallHandler(req, resp);
        final String queryString = req.getQueryString();
        if (queryString == null) {
            ServletOutputStream outputStream = resp.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            writer.write("Error");
            outputStream.close();
            return;
        }
        Object message = JSONValue.parse(queryString);
        handler.handleJSON((JSONObject) message);
    } catch (RuntimeException e) {
        LOGGER.error(e, "Error while handling request");
    } finally {
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.flush();
        outputStream.close();
    }
}

From source file:jetbrains.buildServer.torrent.web.DownloadTorrentController.java

@Override
protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws Exception {
    String buildIdParam = request.getParameter("buildId");
    String path = request.getParameter("file");
    String torrentPath = path + TorrentUtil.TORRENT_FILE_SUFFIX;

    File torrentFile = null;//from w  w w.ja va  2  s.  c o  m
    long buildId = Long.parseLong(buildIdParam);
    SBuild build = myBuildsManager.findBuildInstanceById(buildId);
    if (build != null) {
        torrentFile = myTorrentsManager.getTorrentFile(build, torrentPath);
        if (!torrentFile.isFile()) {
            torrentFile = null;
        }
    }

    if (torrentFile == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
        response.setContentType(WebUtil.getMimeType(request, torrentFile.getName()));
        // force set content-disposition to attachment
        WebUtil.setContentDisposition(request, response, torrentFile.getName(), false);
        ServletOutputStream output = response.getOutputStream();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(torrentFile);
            StreamUtil.copyStreamContent(fis, output);
        } finally {
            FileUtil.close(fis);
            output.close();
        }
    }

    return null;
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateGatewayReceiverController.java

@RequestMapping(value = "/creategatewayreceiver", method = RequestMethod.POST)
public String createGatewayReceiverAction(
        @ModelAttribute("gatewayReceiverAttribute") NewGatewayReceiver gatewayReceiverAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from  ww  w .jav a2  s.  c  om
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Gateway Receiver");

    String gatewayReceiverName = gatewayReceiverAttribute.getGatewayReceiverName();

    logger.debug("New Gateway Receiver Name = " + gatewayReceiverName);

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");
    boolean needCloseBracket = false;

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createGatewayReceiver = new StringBuffer();

        createGatewayReceiver.append("CREATE GATEWAYRECEIVER " + gatewayReceiverName + " (\n");

        if (!checkIfParameterEmpty(request, "bindAddress")) {
            createGatewayReceiver.append("BINDADDRESS '" + gatewayReceiverAttribute.getBindAddress() + "' \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "startPort")) {
            createGatewayReceiver.append("STARTPORT " + gatewayReceiverAttribute.getStartPort() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "endPort")) {
            createGatewayReceiver.append("ENDPORT " + gatewayReceiverAttribute.getEndPort() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "socketBufferSize")) {
            createGatewayReceiver
                    .append("SOCKETBUFFERSIZE " + gatewayReceiverAttribute.getSocketBufferSize() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "maxTimeBetweenPings")) {
            createGatewayReceiver
                    .append("MAXTIMEBETWEENPINGS " + gatewayReceiverAttribute.getMaxTimeBetweenPings() + " \n");
            needCloseBracket = true;
        }

        if (needCloseBracket) {
            createGatewayReceiver.append(") ");
        }

        if (!checkIfParameterEmpty(request, "serverGroups")) {
            createGatewayReceiver
                    .append("SERVER GROUPS (" + gatewayReceiverAttribute.getServerGroups() + ") \n");
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating gateway receiver as -> " + createGatewayReceiver.toString());

            result = GemFireXDWebDAOUtil.runCommand(createGatewayReceiver.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Async SQL as follows as -> " + createGatewayReceiver.toString());
            model.addAttribute("sql", createGatewayReceiver.toString());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, gatewayReceiverName));

            ServletOutputStream out = response.getOutputStream();
            out.println(createGatewayReceiver.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/create-gatewayreceiver.jsp
    return "create-gatewayreceiver";
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

public static void callCtl(String class_method) throws RuntimeException {
    try {//ww w. j  a va2 s  .  com
        HttpServletRequest req = ActionContext.getReq();
        HttpServletResponse resp = ActionContext.getResp();
        if (StringUtils.isNotBlank(class_method)) {
            Cache cache = SshConstant.CACHE_MAP.get(class_method);
            if (null != cache && !SshConstant.DEBUG_MODE) {
                // long begin = System.currentTimeMillis();
                cache.getMethod().invoke(cache.getObject(), req, resp);
                // long end = System.currentTimeMillis();
                // //System.out.println("" + (end - begin));
            } else {
                // long begin = System.currentTimeMillis();
                int lastIndex = class_method.lastIndexOf(".");
                String clazzTemp = class_method.substring(0, lastIndex);
                // 
                Class<?> ctlClazz = null;
                for (String packageName : SshConstant.PACKAGE_NAME) {
                    try {
                        String clazz = (clazzTemp.indexOf(".") == clazzTemp.lastIndexOf("."))
                                ? (packageName + "." + clazzTemp)
                                : clazzTemp;
                        ctlClazz = Class.forName(clazz);
                    } catch (Exception e) {
                    }
                    if (ctlClazz != null)
                        break;
                }
                Object ctlObj = ctlClazz.newInstance();
                String method = class_method.substring(++lastIndex);
                // Method ctlMet = ctlClazz.getMethod(method,
                // HttpServletRequest.class, HttpServletResponse.class);
                Method ctlMet = ctlClazz.getMethod(method);
                SshConstant.CACHE_MAP.put(class_method, new Cache(ctlObj, ctlMet));// put
                // cache

                // ctlMet.invoke(ctlObj, req, resp);
                ctlMet.invoke(ctlObj);
                // long end = System.currentTimeMillis();
                // //System.out.println("" + (end - begin));
            }
        } else {
            ServletOutputStream out = resp.getOutputStream();
            out.print("error");
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}