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.pymegest.applicationserver.api.SessionController.java

@RequestMapping(value = { "/Session" }, method = RequestMethod.POST)
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse response,
        @RequestBody String jsonSession) {

    try {/*from  www . ja va2 s .  c o  m*/

        ObjectMapper objectMapper = new ObjectMapper();

        Credentials credentials = (Credentials) objectMapper.readValue(jsonSession, Credentials.class);

        Usuario usuario = usuarioDAO.findByLogin(credentials.getLogin());

        if (usuario == null) {
            //No existe usuario con login introducido
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(null);
            response.getWriter().println(jsonOutput);
        } else {

            boolean existe = usuario.checkPassword(credentials.getPassword());

            if (existe) {

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

                String jsonOutput = objectMapper.writeValueAsString(usuario);
                response.getWriter().println(jsonOutput);

                httpServletRequest.getSession(true).setAttribute("idUsuario", usuario.getId_usuario());

            } else {

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

                String jsonOutput = objectMapper.writeValueAsString(null);
                response.getWriter().println(jsonOutput);
            }

        }

    } 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.panet.imeta.www.GetTransStatusServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!request.getContextPath().equals(CONTEXT_PATH))
        return;//from   w w  w.  j a  va  2s. co  m

    if (log.isDebug())
        log.logDebug(toString(), Messages.getString("TransStatusServlet.Log.TransStatusRequested"));

    String transName = request.getParameter("name");
    boolean useXML = "Y".equalsIgnoreCase(request.getParameter("xml"));

    response.setStatus(HttpServletResponse.SC_OK);

    if (useXML) {
        response.setContentType("text/xml");
        response.setCharacterEncoding(Const.XML_ENCODING);
    } else {
        response.setContentType("text/html");
    }

    PrintWriter out = response.getWriter();

    Trans trans = transformationMap.getTransformation(transName);

    if (trans != null) {
        String status = trans.getStatus();

        if (useXML) {
            response.setContentType("text/xml");
            response.setCharacterEncoding(Const.XML_ENCODING);
            out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));

            SlaveServerTransStatus transStatus = new SlaveServerTransStatus(transName, status);

            for (int i = 0; i < trans.nrSteps(); i++) {
                BaseStep baseStep = trans.getRunThread(i);
                if ((baseStep.isAlive()) || baseStep.getStatus() != StepDataInterface.STATUS_EMPTY) {
                    StepStatus stepStatus = new StepStatus(baseStep);
                    transStatus.getStepStatusList().add(stepStatus);
                }
            }

            Log4jStringAppender appender = (Log4jStringAppender) transformationMap.getAppender(transName);
            if (appender != null) {
                // The log can be quite large at times, we are going to put a base64 encoding around a compressed stream
                // of bytes to handle this one.

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(baos);
                gzos.write(appender.getBuffer().toString().getBytes());
                gzos.close();

                String loggingString = new String(Base64.encodeBase64(baos.toByteArray()));
                transStatus.setLoggingString(loggingString);
            }

            // Also set the result object...
            //
            transStatus.setResult(trans.getResult());

            // Is the transformation paused?
            //
            transStatus.setPaused(trans.isPaused());

            // Send the result back as XML
            //
            out.println(transStatus.getXML());
        } else {
            response.setContentType("text/html");

            out.println("<HTML>");
            out.println("<HEAD>");
            out.println("<TITLE>" + Messages.getString("TransStatusServlet.KettleTransStatus") + "</TITLE>");
            out.println("<META http-equiv=\"Refresh\" content=\"10;url=/kettle/transStatus?name="
                    + URLEncoder.encode(transName, "UTF-8") + "\">");
            out.println("</HEAD>");
            out.println("<BODY>");
            out.println("<H1>" + Messages.getString("TransStatusServlet.TopTransStatus", transName) + "</H1>");

            try {
                out.println("<table border=\"1\">");
                out.print("<tr> <th>" + Messages.getString("TransStatusServlet.TransName") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.TransStatus") + "</th> </tr>");

                out.print("<tr>");
                out.print("<td>" + transName + "</td>");
                out.print("<td>" + status + "</td>");
                out.print("</tr>");
                out.print("</table>");

                out.print("<p>");

                if ((trans.isFinished() && trans.isRunning())
                        || (!trans.isRunning() && !trans.isPreparing() && !trans.isInitializing())) {
                    out.print("<a href=\"/kettle/startTrans?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("TransStatusServlet.StartTrans") + "</a>");
                    out.print("<p>");
                    out.print("<a href=\"/kettle/prepareExec?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("TransStatusServlet.PrepareTrans") + "</a><br>");
                    //out.print("<a href=\"/kettle/startExec?name="+URLEncoder.encode(transName, "UTF-8")+"\">" + Messages.getString("TransStatusServlet.StartTrans") + "</a><p>");
                } else if (trans.isRunning()) {
                    out.print("<a href=\"/kettle/pauseTrans?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("PauseStatusServlet.PauseResumeTrans") + "</a><br>");
                    out.print("<a href=\"/kettle/stopTrans?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("TransStatusServlet.StopTrans") + "</a>");
                    out.print("<p>");
                }
                out.print("<a href=\"/kettle/cleanupTrans?name=" + URLEncoder.encode(transName, "UTF-8") + "\">"
                        + Messages.getString("TransStatusServlet.CleanupTrans") + "</a>");
                out.print("<p>");

                out.println("<table border=\"1\">");
                out.print("<tr> <th>" + Messages.getString("TransStatusServlet.Stepname") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.CopyNr") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Read") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Written") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Input") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Output") + "</th> " + "<th>"
                        + Messages.getString("TransStatusServlet.Updated") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Rejected") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Errors") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Active") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Time") + "</th> " + "<th>"
                        + Messages.getString("TransStatusServlet.Speed") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.prinout") + "</th> </tr>");

                for (int i = 0; i < trans.nrSteps(); i++) {
                    BaseStep baseStep = trans.getRunThread(i);
                    if ((baseStep.isAlive()) || baseStep.getStatus() != StepDataInterface.STATUS_EMPTY) {
                        StepStatus stepStatus = new StepStatus(baseStep);
                        out.print(stepStatus.getHTMLTableRow());
                    }
                }
                out.println("</table>");
                out.println("<p>");

                out.print("<a href=\"/kettle/transStatus/?name=" + URLEncoder.encode(transName, "UTF-8")
                        + "&xml=y\">" + Messages.getString("TransStatusServlet.ShowAsXml") + "</a><br>");
                out.print("<a href=\"/kettle/status\">"
                        + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><br>");
                out.print("<p><a href=\"/kettle/transStatus?name=" + URLEncoder.encode(transName, "UTF-8")
                        + "\">" + Messages.getString("TransStatusServlet.Refresh") + "</a>");

                // Put the logging below that.
                Log4jStringAppender appender = (Log4jStringAppender) transformationMap.getAppender(transName);
                if (appender != null) {
                    out.println("<p>");
                    /*
                    out.println("<pre>");
                    out.println(appender.getBuffer().toString());
                    out.println("</pre>");
                    */
                    out.println(
                            "<textarea id=\"translog\" cols=\"120\" rows=\"20\" wrap=\"off\" name=\"Transformation log\" readonly=\"readonly\">"
                                    + appender.getBuffer().toString() + "</textarea>");

                    out.println("<script type=\"text/javascript\"> ");
                    out.println("  translog.scrollTop=translog.scrollHeight; ");
                    out.println("</script> ");
                    out.println("<p>");
                }
            } catch (Exception ex) {
                out.println("<p>");
                out.println("<pre>");
                ex.printStackTrace(out);
                out.println("</pre>");
            }

            out.println("<p>");
            out.println("</BODY>");
            out.println("</HTML>");
        }
    } else {
        if (useXML) {
            out.println(new WebResult(WebResult.STRING_ERROR,
                    Messages.getString("TransStatusServlet.Log.CoundNotFindSpecTrans", transName)));
        } else {
            out.println("<H1>" + Messages.getString("TransStatusServlet.Log.CoundNotFindTrans", transName)
                    + "</H1>");
            out.println("<a href=\"/kettle/status\">"
                    + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><p>");

        }
    }
}

From source file:de.knightsoftnet.validators.server.security.AuthSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest prequest, final HttpServletResponse presponse,
        final Authentication pauthentication) throws IOException, ServletException {
    this.csrfCookieHandler.setCookie(prequest, presponse);

    if (pauthentication.isAuthenticated()) {
        presponse.setStatus(HttpServletResponse.SC_OK);
        LOGGER.info("User is authenticated!");
        LOGGER.debug(pauthentication.toString());

        final PrintWriter writer = presponse.getWriter();
        this.mapper.writeValue(writer,
                this.userDetailsConverter.convert((UserDetails) pauthentication.getPrincipal()));
        writer.flush();/* w ww. jav  a 2s  .  c o  m*/
    } else {
        presponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.thinkberg.webdav.DeleteHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {/*  www .  j  av a2  s  .  co  m*/
        String fragment = new URI(request.getRequestURI()).getFragment();
        if (fragment != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    } catch (URISyntaxException e) {
        throw new IOException(e.getMessage());
    }

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        int deletedObjects = object.delete(ALL_FILES_SELECTOR);
        LOG.debug("deleted " + deletedObjects + " objects");
        if (deletedObjects > 0) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:br.eti.kinoshita.testlinkjavaapi.HttpTestServer.java

public Handler getMockHandler() {
    Handler mockHandler = new AbstractHandler() {
        public void handle(String target, Request request, HttpServletRequest httpRequest,
                HttpServletResponse httpResponse) throws IOException, ServletException {
            Request baseRequest = HttpConnection.getCurrentConnection().getRequest();
            setResponseBody(getMockResponseBody());
            setRequestBody(IOUtils.toString(baseRequest.getInputStream()));
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            httpResponse.setContentType("text/xml;charset=utf-8");
            httpResponse.getWriter().write(getResponseBody());
            baseRequest.setHandled(true);
        }/*from   ww  w.  ja  va  2  s. co m*/
    };
    return mockHandler;
}

From source file:de.devbliss.apitester.dummyserver.DummyRequestHandler.java

private void handleGet(String path, HttpServletResponse response) throws IOException {

    try {//from   w ww  .  j  a v  a  2s .  c  om
        int desiredResponseCode = parseDesiredResponseCode(path);
        response.setStatus(desiredResponseCode);
        response.setContentType(CONTENT_TYPE);

        if (desiredResponseCode == HttpServletResponse.SC_OK) {
            response.getWriter().write(gson.toJson(DummyDto.createSampleInstance()));
        }
    } catch (Exception e) {
        handleException(e, response);
    }
}

From source file:com.carolinarollergirls.scoreboard.jetty.LoadXmlScoreBoard.java

protected void handleDocument(HttpServletRequest request, HttpServletResponse response, Document doc)
        throws IOException {
    if (request.getPathInfo().equalsIgnoreCase("/load"))
        getXmlScoreBoard().loadDocument(doc);
    else if (request.getPathInfo().equalsIgnoreCase("/merge"))
        getXmlScoreBoard().mergeDocument(doc);
    else//from  w  w w .  j a  v  a 2s .c  o m
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Must specify to load or merge document");
    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.controller.schedule.GetScheduledEmailDetailServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  www  .  j a va 2 s. c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    HttpSession session = request.getSession();
    if (session.getAttribute("UID") == null) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "User is not logged in");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().flush();
        return;
    }
    Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
    if (StringUtils.isEmpty(request.getParameter("schedule_id"))) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Schedule id is missing");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }

    try {
        Integer scheduleEmailId = Integer.parseInt(request.getParameter("schedule_id"));
        Map<String, Object> scheduleEmailDetails = ScheduleDAO.getScheduleEmailDetails(userId, scheduleEmailId);
        response.getWriter().write(AppConstants.GSON.toJson(scheduleEmailDetails));
        response.getWriter().flush();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (ParseException parse) {
        logger.log(Level.SEVERE, null, parse);
    } catch (NumberFormatException ex) {
        logger.log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Schedule id cannot be parsed to integer");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(GetScheduledEmailDetailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ch.entwine.weblounge.test.harness.content.JavaServerPagesTest.java

/**
 * {@inheritDoc}//from   ww w .ja  v a 2 s.  c o  m
 * 
 * @see ch.entwine.weblounge.testing.kernel.IntegrationTest#execute(java.lang.String)
 */
@Override
public void execute(String serverUrl) throws Exception {
    logger.info("Testing loading of java server page");

    String requestUrl = UrlUtils.concat(serverUrl, JSP_PATH);
    HttpGet request = new HttpGet(requestUrl);
    logger.info("Sending request to {}", requestUrl);

    // Send and the request and examine the response
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        String contentType = response.getEntity().getContentType().getValue();
        assertEquals(CONTENT_TYPE_HTML, contentType.split(";")[0]);

        // Test template contents
        Document xml = TestUtils.parseXMLResponse(response);
        String templateOutput = XPathHelper.valueOf(xml, "/html/head/title");
        assertNotNull("General template output does not work", templateOutput);
        assertEquals("Template title is not as expected", "Weblounge Test Site", templateOutput);

        // Test site tag libraries
        logger.info("Testing weblounge taglibrary on {}", requestUrl);
        String generator = "/html/head/meta[@name='generator']/@content";
        Assert.assertNotNull("Generator tag not found", XPathHelper.valueOf(xml, generator));
        Assert.assertNotNull("Weblounge 3.0", XPathHelper.valueOf(xml, generator));

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.eureka.v1_0.account.information.api.AccountInformationController.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE)
public CreateAccountResponse createAccount(@RequestBody CreateAccountRequest createAccountRequest,
        HttpServletRequest request, HttpServletResponse response) {
    if (createAccountRequest != null) {
        try {/* ww w  .j  a  va  2 s  .c  o m*/
            CreateAccountResponse createAccountResponse = this.accountInformationApiService
                    .createAccount(createAccountRequest);
            witLoggerService.debug(JaxbHandler.toXml(createAccountRequest));
            if (createAccountResponse != null) {
                witLoggerService.debug(JaxbHandler.toXml(createAccountResponse));
                response.setStatus(HttpServletResponse.SC_OK);
                return createAccountResponse;
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            }
        } catch (Exception ex) {
            witLoggerService.warn(ex);
            ex.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return null;
}