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.betaconceptframework.astroboa.resourceapi.filter.CmsDefinitionFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    String repositoryId = null;// w  w  w.j av a2s  .c o  m
    String definitionFullPath = null;

    String requiredURIRegularExpression = "^" + httpServletRequest.getContextPath()
            + CONTENT_OBJECT_TYPE_DEFINITION_FILTER_PREFIX + "/" + "repository/(.+)" + // group 1
            "/" + "definitionFullPath/(.+{1,300})" // group 2
    ;

    Pattern requiredURIPattern = Pattern.compile(requiredURIRegularExpression);
    Matcher uriMatcher = requiredURIPattern.matcher(httpServletRequest.getRequestURI());

    if (!uriMatcher.matches()) {
        logger.warn("Invalid request " + httpServletRequest.getRequestURI());
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        repositoryId = uriMatcher.group(1);

        definitionFullPath = uriMatcher.group(2);

        if (StringUtils.isBlank(definitionFullPath)) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        String filename = (definitionFullPath.endsWith(".xsd") ? definitionFullPath
                : definitionFullPath + ".xsd");

        repositoryService.loginAsAnonymous(repositoryId);

        String definitionSchema = definitionService.getCmsDefinition(definitionFullPath,
                ResourceRepresentationType.XSD, true);

        if (definitionSchema == null) {
            logger.warn("Definition service retuned null for " + httpServletRequest.getRequestURI());
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {

            try {

                ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("text/xml");
                httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + filename);

                servletOutputStream.write(definitionSchema.getBytes());

                servletOutputStream.flush();

            } catch (Exception e) {
                logger.error("", e);
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
    }

}

From source file:com.jd.survey.web.settings.DataSetController.java

/**
 * exports a dataset to a comma delimited file
 * @param dataSetId//from  ww w.j  a  v a  2  s .  c o  m
 * @param principal
 * @param response
 */

@RequestMapping(value = "/{id}", params = "export", produces = "text/html")
public void export(@PathVariable("id") Long dataSetId, Principal principal, HttpServletResponse response) {
    try {

        String commaDelimtedString = surveySettingsService.exportDatasetItemsToCommaDelimited(dataSetId);
        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=dataSetItems" + dataSetId + ".csv");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(commaDelimtedString.getBytes("UTF-8"));
        servletOutputStream.flush();

    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.eucalyptus.www.X509Download.java

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String code = request.getParameter(PARAMETER_CODE);
    String userName = request.getParameter(PARAMETER_USERNAME);
    String accountName = request.getParameter(PARAMETER_ACCOUNTNAME);
    String mimetype = "application/zip";
    if (accountName == null || "".equals(accountName)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "No account name provided", response);
        return;//from  w  ww .  ja va2s. co  m
    }
    if (userName == null || "".equals(userName)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "No user name provided", response);
        return;
    }
    if (code == null || "".equals(code)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "Wrong user security code", response);
        return;
    }

    User user = null;
    try {
        Account account = Accounts.lookupAccountByName(accountName);
        user = account.lookupUserByName(userName);
        if (!user.isEnabled() || !RegistrationStatus.CONFIRMED.equals(user.getRegistrationStatus())) {
            hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response);
            return;
        }
    } catch (AuthException e) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "User does not exist", response);
        return;
    } catch (Exception e) {
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to retrieve user data", response);
        return;
    }
    try {
        if (!code.equals(user.resetToken())) {
            hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response);
            return;
        }
    } catch (Exception e) {
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can not reset user security code", response);
        return;
    }
    response.setContentType(mimetype);
    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + X509Download.NAME_SHORT + "-" + userName + "-x509.zip\"");
    LOG.info("pushing out the X509 certificate for user " + userName);

    byte[] x509zip = null;
    try {
        x509zip = getX509Zip(user);
    } catch (Exception e) {
        LOG.debug(e, e);
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to return user credentials", response);
        return;
    }
    try {
        ServletOutputStream op = response.getOutputStream();

        response.setContentLength(x509zip.length);

        op.write(x509zip);
        op.flush();

    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:org.wso2.carbon.identity.certificateauthority.ui.client.CAAdminServiceClient.java

/**
 * Downloading a certificate file with a given serial number
 *
 * @param certificate//w ww. j av  a2s . c  om
 * @param response
 * @throws AxisFault
 */

public void downloadServiceArchive(String certificate, HttpServletResponse response) throws AxisFault {
    try {
        ServletOutputStream out = response.getOutputStream();
        response.setHeader("Content-Disposition", "fileName=certificate.key");
        response.setContentType("application/octet-string");
        out.write(certificate.getBytes());
        out.flush();
    } catch (RemoteException e) {
        handleException("error.downloading.service", e);
    } catch (IOException e) {
        handleException("error.downloading.service", e);
    }
}

From source file:org.wings.recorder.Recorder.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    try {//from  w w  w.  j  a v a2s . c o  m
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            Map map = servletRequest.getParameterMap();
            if (map.containsKey(RECORDER_SCRIPT)) {
                log.info("recorder_script " + map.get(RECORDER_SCRIPT));
                String[] values = (String[]) map.get(RECORDER_SCRIPT);
                scriptName = values[0];
            }
            if (map.containsKey(RECORDER_START)) {
                if (list != null)
                    return;
                log.info(RECORDER_START);
                list = new LinkedList();
            } else if (map.containsKey(RECORDER_STOP)) {
                if (list == null)
                    return;
                log.info(RECORDER_STOP);
                writeCode();
                list = null;
            } else if (list != null) {
                String resource = httpServletRequest.getPathInfo();
                log.debug("PATH_INFO: " + resource);

                Request record;
                if ("GET".equalsIgnoreCase(httpServletRequest.getMethod()))
                    record = new GET(resource);
                else
                    record = new POST(resource);

                Enumeration parameterNames = httpServletRequest.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String name = (String) parameterNames.nextElement();
                    String[] values = httpServletRequest.getParameterValues(name);
                    addEvent(record, name, values);
                }
                Enumeration headerNames = httpServletRequest.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String name = (String) headerNames.nextElement();
                    if (name.equalsIgnoreCase("cookie") || name.equalsIgnoreCase("referer"))
                        continue;
                    addHeader(record, name, httpServletRequest.getHeader(name));
                }
                list.add(record);
            }
        }
    } finally {
        if (servletResponse instanceof HttpServletResponse) {
            filterChain.doFilter(servletRequest,
                    new HttpServletResponseWrapper((HttpServletResponse) servletResponse) {
                        public ServletOutputStream getOutputStream() throws IOException {
                            final ServletOutputStream out = super.getOutputStream();
                            return new ServletOutputStream() {
                                public void write(int b) throws IOException {
                                    out.write(b);
                                }

                                public void close() throws IOException {
                                    super.println("<hr/><div align=\"center\">");
                                    super.println("<form method=\"get\" action=\"\">");
                                    super.println("<input type=\"text\" name=\"recorder_script\" value=\""
                                            + scriptName + "\">");
                                    super.println(
                                            "<input type=\"submit\" name=\"recorder_start\" value=\"start\">");
                                    super.println(
                                            "<input type=\"submit\" name=\"recorder_stop\" value=\"stop\">");
                                    super.println("</div></form>");
                                    super.close();
                                }
                            };
                        }
                    });
        } else
            filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:com.jd.survey.web.settings.DataSetController.java

/**
 * exports a sample dataset items a comma delimited file
 * @param dataSetId//  ww  w  .ja va2s  .c o  m
 * @param principal
 * @param response
 */

@RequestMapping(value = "/example", produces = "text/html")
public void getExampleCsvFile(Principal principal, HttpServletResponse response) {
    try {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(messageSource
                .getMessage(VALUE_FIELD_NAME_MESSAGE, null, LocaleContextHolder.getLocale()).replace(",", ""));
        stringBuilder.append(",");
        stringBuilder.append(messageSource
                .getMessage(TEXT_FIELD_NAME_MESSAGE, null, LocaleContextHolder.getLocale()).replace(",", ""));
        stringBuilder.append("\n");
        stringBuilder.append("B,Boston\n");
        stringBuilder.append("N,New York\n");
        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=datasetExample.csv");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.flush();

    }

    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

From source file:net.sf.appstatus.web.pages.StatusPage.java

public void doGetJSON(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
        throws UnsupportedEncodingException, IOException {

    setup(resp, "application/json");

    ServletOutputStream os = resp.getOutputStream();
    int statusCode = 200;
    List<ICheckResult> results = webHandler.getAppStatus().checkAll(req.getLocale());
    for (ICheckResult r : results) {
        if (r.isFatal()) {
            resp.setStatus(500);//from  ww  w. j  a v  a  2  s  .  c om
            statusCode = 500;
            break;
        }
    }

    os.write("{".getBytes(ENCODING));

    os.write(("\"code\" : " + statusCode + ",").getBytes(ENCODING));
    os.write(("\"status\" : {").getBytes(ENCODING));

    boolean first = true;
    for (ICheckResult r : results) {
        if (!first) {
            os.write((",").getBytes(ENCODING));
        }

        os.write(("\"" + r.getProbeName() + "\" : " + r.getCode()).getBytes(ENCODING));

        if (first) {
            first = false;
        }
    }

    os.write("}".getBytes(ENCODING));
    os.write("}".getBytes(ENCODING));

}

From source file:com.openkm.servlet.admin.StampServlet.java

/**
 * View image stamp// www  .  j av  a  2s .c o m
 */
private void imageView(Session session, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("imageView({}, {}, {})", new Object[] { session, request, response });
    int siId = WebUtils.getInt(request, "si_id");
    StampImage si = StampImageDAO.findByPk(siId);
    response.setContentType(si.getImageMime());
    ServletOutputStream sos = response.getOutputStream();
    sos.write(SecureStore.b64Decode(si.getImageContent()));
    sos.flush();
    sos.close();
    log.debug("imageView: void");
}

From source file:web.CuidadorManager.java

public void download(String url) {
    String filename = FilenameUtils.getName(url);
    File file = new File(url);

    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();//from   ww  w . ja va  2s. co m

    response.setHeader("Content-Disposition", "attachment;filename=" + filename);
    response.setContentLength((int) file.length());
    ServletOutputStream out = null;
    try {
        FileInputStream input = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        out = response.getOutputStream();
        int i = 0;
        while ((i = input.read(buffer)) != -1) {
            out.write(buffer);
            out.flush();
        }
        FacesContext.getCurrentInstance().getResponseComplete();
    } catch (IOException err) {
        err.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException err) {
            err.printStackTrace();
        }
    }

}

From source file:annis.gui.servlets.BinaryServlet.java

private void writeStepByStep(int offset, int completeLength, WebResource binaryRes, ServletOutputStream out)
        throws IOException {
    int remaining = completeLength;
    while (remaining > 0) {
        int stepLength = Math.min(MAX_LENGTH, remaining);

        AnnisBinary bin = binaryRes.path("" + offset).path("" + stepLength).get(AnnisBinary.class);
        Validate.isTrue(bin.getLength() == stepLength);

        out.write(bin.getBytes());
        out.flush();/*from ww  w  .  java2 s .  c o  m*/

        offset += stepLength;
        remaining = remaining - stepLength;
    }
}