Example usage for javax.servlet.http HttpServletResponse SC_OK

List of usage examples for javax.servlet.http HttpServletResponse SC_OK

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_OK.

Prototype

int SC_OK

To view the source code for javax.servlet.http HttpServletResponse SC_OK.

Click Source Link

Document

Status code (200) indicating the request succeeded normally.

Usage

From source file:com.logiclander.jaasmine.authentication.http.SimpleLogoutServlet.java

/**
 * Logs out the Subject associated with the user.
 *
 * After the logout is done, the request is dispatched to a Servlet or JSP
 * specified by the {@code postLogoutProcessorName} init-param.  If the
 * param was not specified, a {@code text/plain} message will be written
 * to the response./* w ww  .  j av  a 2s. c o m*/
 *
 * This method is not idempotent.  If a request is made successfully once,
 * the user will be logged out.  Subsequent requests without a login will
 * cause an HTTP 403 - Forbidden to be returned.
 *
 * @param req the HttpServletRequest
 * @param resp the HttpServletResponse
 * @throws ServletException if a ServletException is thrown after the
 * request is dispatched to the post logout processor.
 * @throws IOException if an I/O error occurs.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession sess = req.getSession();
    Subject subj = (Subject) sess.getAttribute(AuthenticationService.SUBJECT_KEY);

    if (subj == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Log out the Subject
    AuthenticationService as = new SimpleAuthenticationService(appName);
    as.logout(subj);

    // Invalidate the session
    sess.invalidate();

    resp.setStatus(HttpServletResponse.SC_OK);
    RequestDispatcher rd = getServletContext().getNamedDispatcher(postLogoutProcessorName);

    if (rd != null) {
        resp.setContentType("text/html");
        rd.include(req, resp);
    } else {
        sendPlainTextResponse(resp);
    }

}

From source file:com.alertlogic.aws.kinesis.test1.webserver.GetCountsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    MultiMap<String> params = new MultiMap<>();
    UrlEncoded.decodeTo(req.getQueryString(), params, "UTF-8");

    // We need both parameters to properly query for counts
    if (!params.containsKey(PARAMETER_RESOURCE) || !params.containsKey(PARAMETER_RANGE_IN_SECONDS)) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from  w w  w .j a v a 2 s.com*/
    }

    // Parse query string as a single integer - the number of seconds since "now" to query for new counts
    String resource = params.getString(PARAMETER_RESOURCE);
    int rangeInSeconds = Integer.parseInt(params.getString(PARAMETER_RANGE_IN_SECONDS));

    Calendar c = Calendar.getInstance();
    c.add(Calendar.SECOND, -1 * rangeInSeconds);
    Date startTime = c.getTime();
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Querying for counts of resource %s since %s", resource,
                DATE_FORMATTER.get().format(startTime)));
    }

    DynamoDBQueryExpression<HttpReferrerPairsCount> query = new DynamoDBQueryExpression<>();
    HttpReferrerPairsCount hashKey = new HttpReferrerPairsCount();
    hashKey.setResource(resource);
    query.setHashKeyValues(hashKey);

    Condition recentUpdates = new Condition().withComparisonOperator(ComparisonOperator.GT)
            .withAttributeValueList(new AttributeValue().withS(DATE_FORMATTER.get().format(startTime)));
    query.setRangeKeyConditions(Collections.singletonMap("timestamp", recentUpdates));

    List<HttpReferrerPairsCount> counts = mapper.query(HttpReferrerPairsCount.class, query);

    // Return the counts as JSON
    resp.setContentType("application/json");
    resp.setStatus(HttpServletResponse.SC_OK);
    JSON.writeValue(resp.getWriter(), counts);
}

From source file:org.pentaho.pat.server.servlet.FileUploadController.java

protected ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response,
        final Object command, final BindException errors) throws Exception {
    final FileUploadBean fileUploadBean = (FileUploadBean) command;

    try {//w  w  w.  ja  v a 2 s  .  c  o m
        final MultipartFile files = fileUploadBean.getFile();
        String schemaData = new String(files.getBytes());
        String validationResult = AbstractSchemaValidator.validateAgainstXsd(schemaData);
        response.setContentType("text/plain"); //$NON-NLS-1$

        if (validationResult == null) {
            validationResult = ""; //$NON-NLS-1$
        }

        response.getWriter().print(VALIDATION_START + validationResult + VALIDATION_END);
        // Send a confirmation message to the client

        response.getWriter().print(DATA_START + (new String(Base64Coder.encode(files.getBytes()))) + DATA_END);
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        LOG.error(e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    // return the result to the client
    response.getWriter().flush();

    return null;
}

From source file:gov.nist.appvet.tool.synchtest.util.ReportUtil.java

/**
 * This method returns report information to the AppVet ToolAdapter as ASCII
 * text and cannot attach a file to the response.
 *//*ww w  .  j  a v  a2 s .c  om*/
public static boolean sendInHttpResponse(HttpServletResponse response, String reportText,
        ToolStatus reportStatus) {
    try {
        response.setStatus(HttpServletResponse.SC_OK); // HTTP 200
        response.setContentType("text/html");
        response.setHeader("apprisk", reportStatus.name());
        PrintWriter out = response.getWriter();
        out.println(reportText);
        out.flush();
        out.close();
        log.info("Returned report");
        return true;
    } catch (IOException e) {
        log.error("Report not sent: " + e.toString());
        return false;
    }
}

From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2KMetadata.java

/**
 * Returns the OpenURLResponse of a JSON object defining the core image properties. Having obtained a result, this
 * method is then responsible for transforming it into an OpenURLResponse that acts as a proxy for
 * HttpServletResponse.//from ww  w.  j a va 2s  .c  om
 */
@Override
public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject,
        final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) {

    String responseFormat = RESPONSE_TYPE;
    int status = HttpServletResponse.SC_OK;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode rootNode = mapper.createObjectNode();
        final IExtract jp2 = new KduExtractExe();

        ImageRecord r = ReferentManager.getImageRecord(contextObject.getReferent());
        r = jp2.getMetadata(r);

        rootNode.put("identifier", r.getIdentifier());
        rootNode.put("imagefile", r.getImageFile());
        rootNode.put("width", r.getWidth());
        rootNode.put("height", r.getHeight());
        rootNode.put("dwtLevels", r.getDWTLevels());
        rootNode.put("levels", r.getLevels());
        rootNode.put("compositingLayerCount", r.getCompositingLayerCount());

        mapper.writeValue(baos, rootNode);
    } catch (final DjatokaException e) {
        responseFormat = "text/plain";
        status = HttpServletResponse.SC_NOT_FOUND;
    } catch (final Exception e) {
        baos = new ByteArrayOutputStream();

        try {
            if (e.getMessage() != null) {
                baos.write(e.getMessage().getBytes("UTF-8"));
            } else {
                LOGGER.error(e.getMessage(), e);
                baos.write("Internal Server Error: ".getBytes());
            }
        } catch (final UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (final IOException e2) {
            e2.printStackTrace();
        }

        responseFormat = "text/plain";
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    final HashMap<String, String> header_map = new HashMap<String, String>();
    header_map.put("Content-Length", baos.size() + "");
    header_map.put("Date", HttpDate.getHttpDate());
    return new OpenURLResponse(status, responseFormat, baos.toByteArray(), header_map);
}

From source file:org.craftercms.cstudio.publishing.servlet.FileUploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (ServletFileUpload.isMultipartContent(request)) {
        ServletFileUpload servletFileUpload = createServletFileUpload();
        List<FileItem> fileItemsList = null;
        Map<String, String> parameters = new HashMap<String, String>(11);
        Map<String, InputStream> files = new HashMap<String, InputStream>(11);
        try {//from w w w .j a va  2s  .  co m
            fileItemsList = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItemsList) {
                if (fileItem.isFormField()) {
                    parameters.put(fileItem.getFieldName(), fileItem.getString());
                } else {
                    files.put(fileItem.getFieldName(), fileItem.getInputStream());
                }
            }

            if (LOGGER.isDebugEnabled()) {

                StringBuilder parametersLog = new StringBuilder("Request Parameters : ");

                for (Entry<String, String> entry : parameters.entrySet()) {

                    String key = entry.getKey();
                    String value = entry.getValue();

                    if (key.equals(PARAM_PASSWORD)) {
                        value = "********";
                    }
                    parametersLog.append(" " + key + " = " + value);
                }

                LOGGER.debug(parametersLog.toString());
            }

            String password = parameters.get(PARAM_PASSWORD);
            if (password != null && password.equalsIgnoreCase(this.password)) {
                deployFiles(parameters, files);
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn(
                            "Illegal publish request received. Password parameter does not match configured password for deployer.");
                }
            }
        } catch (Exception e) {
            handleErrorCase(files, response, e);
        }
    }
}

From source file:ch.entwine.weblounge.test.util.TestSiteUtils.java

/**
 * Test for the correct response when modified since header is set.
 * /*w w  w  . j a  v  a  2 s  . c om*/
 * @param request
 *          the http request
 * @param date
 *          the expected modification date
 * @param logger
 *          used to log test output
 * @param params
 *          the request parameters
 * @throws Exception
 *           if processing the request fails
 */
public static void testModifiedHeader(HttpUriRequest request, Date modificationDate, Logger logger,
        String[][] params) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    Date before = new Date(modificationDate.getTime() - Times.MS_PER_DAY);
    Date after = new Date(modificationDate.getTime() + Times.MS_PER_DAY);
    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
    try {
        request.removeHeaders("If-None-Match");
        request.setHeader("If-Modified-Since", format.format(after));
        logger.info("Sending 'If-Modified-Since' request to {}", request.getURI());
        HttpResponse response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode());
        assertNull(response.getEntity());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    httpClient = new DefaultHttpClient();
    try {
        request.removeHeaders("If-None-Match");
        request.setHeader("If-Modified-Since", format.format(before));
        logger.info("Sending 'If-Modified-Since' request to {}", request.getURI());
        HttpResponse response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        assertNotNull(response.getEntity());
        response.getEntity().consumeContent();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.pymegest.applicationserver.api.PuestoController.java

@RequestMapping(value = { "/Puesto" }, method = RequestMethod.GET)
public void findAll(HttpServletRequest request, HttpServletResponse response) {

    try {//w  w w  .  j  a  v  a2s  . c o m

        List<Puesto> puestos = puestoDAO.findAll();

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; chaset=UTF-8");

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(puestos);
        response.getWriter().println(json);

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.google.api.server.spi.EndpointsServletTest.java

@Test
public void proxy() throws IOException {
    req.setRequestURI("/_ah/api/static/proxy.html");
    req.setMethod("GET");

    servlet.service(req, resp);/*from  w w  w. j a  va 2 s.  co m*/

    assertThat(resp.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
    assertThat(resp.getContentAsString()).contains("/_ah/api");
    assertThat(resp.getContentAsString()).contains("https://apis.google.com/js/googleapis.proxy.js");
}

From source file:com.fpmislata.banco.presentation.controladores.CuentaBancariaController.java

@RequestMapping(value = "/cuentabancaria/{idCuentaBancaria}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
public void update(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada, @PathVariable("idCuentaBancaria") int idCuentaBancaria) {
    try {//w w w .  ja  va 2  s.c om
        CuentaBancaria cuentaBancaria = (CuentaBancaria) jsonTransformer.fromJsonToObject(jsonEntrada,
                CuentaBancaria.class);
        cuentaBancariaService.update(cuentaBancaria);
        String jsonSalida = jsonTransformer.ObjectToJson(cuentaBancaria);

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonSalida);

    } catch (BusinessException ex) {
        List<BusinessMessage> bussinessMessage = ex.getBusinessMessages();
        String jsonSalida = jsonTransformer.ObjectToJson(bussinessMessage);

        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(CuentaBancariaService.class.getName()).log(Level.SEVERE, null, ex1);
        }

    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(CuentaBancariaController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}