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.springinpractice.ch11.web.controller.pkg.PackageCrudController.java

/**
 * @param pkgData//  w ww .j a  v a 2  s.  c  o m
 * @param res
 */
@RequestMapping(value = "", method = RequestMethod.POST, consumes = "application/xml")
public void postPackage(@RequestBody Package pkgData, HttpServletResponse res) {
    log.debug("Posting package: {}", pkgData);

    // Look up the actual module.
    Module moduleData = pkgData.getModule();
    String groupId = moduleData.getGroupId();
    String moduleId = moduleData.getModuleId();
    log.debug("Looking up module entity with groupId={}, moduleId={}", groupId, moduleId);
    Module module = moduleService.findByGroupIdAndModuleId(groupId, moduleId);
    log.debug("Found module: {}", module);

    // Prepare the package for saving.
    pkgData.setModule(module);

    try {
        log.debug("Creating package: {}", pkgData);
        packageService.create(pkgData);
        res.setHeader("Location", appBaseUrl + "/packages/" + pkgData.getId());
    } catch (DuplicateCIException e) {
        log.info("Package already exists; ignoring: {}", pkgData);

        // Using SC_OK:
        // http://stackoverflow.com/questions/283957/rest-correct-http-response-code-for-a-post-which-is-ignored
        // But see also:
        // http://stackoverflow.com/questions/3825990/http-response-code-for-post-when-resource-already-exists
        res.setStatus(HttpServletResponse.SC_OK);
    }
}

From source file:com.flexive.war.servlet.TestRunnerServlet.java

/**
 * {@inheritDoc}//  w  ww . j av a 2s  . c om
 */
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    String cmd = URLDecoder.decode(request.getRequestURI(), "UTF8");
    if (cmd != null && cmd.lastIndexOf('/') > 0)
        cmd = cmd.substring(cmd.lastIndexOf('/') + 1);
    if (CMD_AVAILABLE.equals(cmd)) {
        boolean available = false;
        try {
            Class.forName("com.flexive.testRunner.FxTestRunner");
            available = true;
        } catch (Exception e) {
            LOG.error(e);
        }
        response.setStatus(available ? HttpServletResponse.SC_OK : HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.getWriter().write(String.valueOf(available));
    } else if (CMD_RUN.equals(cmd)) {
        String outputPath = request.getParameter(PARAM_OUTPUTPATH);
        try {
            Class runner = Class.forName("com.flexive.testRunner.FxTestRunner");
            Method check = runner.getMethod("checkTestConditions", String.class, Boolean.class);
            Boolean status = false;
            if (!StringUtils.isEmpty(outputPath))
                status = (Boolean) check.invoke(null, String.valueOf(outputPath), Boolean.FALSE);
            if (!status) {
                response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
                response.getWriter()
                        .write("Invalid output path, assertations not enabled or test division not definied!");
                return;
            }
            Method exec = runner.getMethod("runTests", String.class);
            exec.invoke(null, outputPath);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("Tests started.");
        } catch (Exception e) {
            LOG.error(e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error: " + e.getMessage());
        }
    } else if (CMD_RUNNING.equals(cmd)) {
        try {
            Class runner = Class.forName("com.flexive.testRunner.FxTestRunner");
            Method check = runner.getMethod("isTestInProgress");
            Boolean status = (Boolean) check.invoke(null);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(String.valueOf(status));
        } catch (Exception e) {
            LOG.error(e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error: " + e.getMessage());
        }
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        response.getWriter().write("Unknown command: " + cmd);
    }
}

From source file:com.graphaware.module.resttest.RestTestApi.java

@RequestMapping(value = "/assertEmpty", method = RequestMethod.POST)
@ResponseBody/*from   w w w. j  a v  a  2 s . co  m*/
public String assertEmpty(@RequestBody(required = false) RestTestRequest request, HttpServletResponse response)
        throws IOException {
    try {
        GraphUnit.assertEmpty(database, resolveInclusionPolicies(request));
        response.setStatus(HttpServletResponse.SC_OK);
        return null;
    } catch (AssertionError error) {
        response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
        return error.getMessage();
    }
}

From source file:eu.stratosphere.pact.client.web.PactJobJSONServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json");

    String jobName = req.getParameter(JOB_PARAM_NAME);
    if (jobName == null) {
        LOG.warn("Received request without job parameter name.");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from   ww w.  j  a v a2s  .c  om*/
    }

    // check, if the jar exists
    File jarFile = new File(jobStoreDirectory, jobName);
    if (!jarFile.exists()) {
        LOG.warn("Received request for non-existing jar file.");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // create the pact plan
    PactProgram pactProgram;
    try {
        pactProgram = new PactProgram(jarFile, new String[0]);
    } catch (Throwable t) {
        LOG.info("Instantiating the PactProgram for '" + jarFile.getName() + "' failed.", t);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(t.getMessage());
        return;
    }

    String jsonPlan = null;
    String programDescription = null;

    try {
        jsonPlan = Client.getPreviewAsJSON(pactProgram);
    } catch (Throwable t) {
        LOG.error("Failed to create json dump of pact program.", t);
    }

    try {
        programDescription = pactProgram.getDescription();
    } catch (Throwable t) {
        LOG.error("Failed to create description of pact program.", t);
    }

    if (jsonPlan == null && programDescription == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } else {
        resp.setStatus(HttpServletResponse.SC_OK);
        PrintWriter wrt = resp.getWriter();
        wrt.print("{ \"jobname\": \"");
        wrt.print(jobName);
        if (jsonPlan != null) {
            wrt.print("\", \"plan\": ");
            wrt.println(jsonPlan);
        }
        if (programDescription != null) {
            wrt.print(", \"description\": \"");
            wrt.print(escapeString(programDescription));
        }

        wrt.print("\"");
        wrt.println("}");
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww  w  . 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");
    try {
        if (!AuthenticationUtil.isUserLoggedIn(request)) {
            AuthenticationUtil.printAuthErrorToResponse(response);
            return;
        }
        Integer userId = AuthenticationUtil.getUUID(request);

        Map<String, Object> requestBodyMap = AppConstants.GSON.fromJson(new BufferedReader(request.getReader()),
                Map.class);
        if (requestBodyMap == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Request body is missing");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }

        List<String> errorMsgs = validateRequestBody(requestBodyMap);
        if (!errorMsgs.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        Double schedule = (Double) requestBodyMap.get("schedule_time");
        //As of now schedule description is not yet mandatory.
        String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                ? String.valueOf(requestBodyMap.get("schedule_desc"))
                : null;

        Map<String, Integer> idMap = ScheduleDAO.addToScheduledEmailList(userId,
                requestBodyMap.get("email_subject").toString(), requestBodyMap.get("email_body").toString(),
                requestBodyMap.get("from_email_address").toString(),
                requestBodyMap.get("email_list").toString(), requestBodyMap.get("from_name").toString(),
                requestBodyMap.get("reply_to_email_address").toString(),
                requestBodyMap.get("to_email_addresses").toString().split(","),
                requestBodyMap.get("schedule_title").toString(), scheduleDesc,
                new Timestamp(schedule.longValue()), TemplateStatus.template_saved.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(idMap));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Invalid format for schedule time.");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (Exception ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a new file upload handler
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();

        try {//from www.  j  av a  2  s.  c o  m
            // Parse the request
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    System.out.println(
                            "Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                } else {
                    System.out
                            .println("File field " + name + " with file name " + item.getName() + " detected.");
                    DataSource source = createDataSource(item);
                    SessionManager.get().getCurrentComposeMessage().addComposeAttachment(source);
                }

                JSONObject jsonResponse = null;
                try {
                    jsonResponse = new JSONObject();
                    jsonResponse.put("success", true);
                    jsonResponse.put("error", "Upload successful");
                } catch (Exception e) {

                }

                Writer w = new OutputStreamWriter(response.getOutputStream());
                w.write(jsonResponse.toString());
                w.close();

                stream.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    response.setStatus(HttpServletResponse.SC_OK);
}

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

@RequestMapping(value = {
        "/usuario" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada) {
    try {// w w  w. j  a v  a 2  s. c  o m
        Usuario usuario = (Usuario) jsonTransformer.fromJsonToObject(jsonEntrada, Usuario.class);
        if (usuario == null) {
            throw new BusinessException("Campo", "Debe rellenar los datos");
        }

        if (!passwordManager.checkComplexity(usuario.getPassword()) || usuario.getPassword().isEmpty()) {
            throw new BusinessException("Password",
                    "La contrasea debe contener Minusculas, Maysculas, Dgitos y de 6-20 caractres");
        }

        usuario.setPassword(passwordManager.encrypt(usuario.getPassword()));

        usuarioService.insert(usuario);

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

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

        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo Lista de Mensajes", ex1);
        }
    } catch (Exception ex1) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex1.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex2) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo la traza", ex2);
        }
    }
}

From source file:com.pactera.edg.am.metamanager.extractor.util.AntZip.java

public static void zipFile(String inputFileName, HttpServletResponse response) {
    try {/*from w ww  . j a v a2  s  .co  m*/
        response.setContentType("text/plain;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=data.zip");
        response.setStatus(HttpServletResponse.SC_OK); //??
        OutputStream output = response.getOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(output);
        zip(zipOut, new File(inputFileName), "");
        if (zipOut != null)
            zipOut.close();
        if (output != null)
            output.close();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    } finally {

    }

}

From source file:org.jboss.as.test.clustering.single.singleton.SingletonServiceTestCase.java

@Test
public void testSingletonService(@ArquillianResource(NodeServiceServlet.class) URL baseURL)
        throws IOException, URISyntaxException {

    // URLs look like "http://IP:PORT/singleton/service"
    URI defaultURI = NodeServiceServlet.createURI(baseURL, NodeServiceActivator.DEFAULT_SERVICE_NAME);
    URI quorumURI = NodeServiceServlet.createURI(baseURL, NodeServiceActivator.QUORUM_SERVICE_NAME);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(new HttpGet(defaultURI));
        try {/*from  w  w  w  . j a va2  s.c o  m*/
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
            Assert.assertEquals(NODE_1, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Service should be started regardless of whether a quorum was required.
        response = client.execute(new HttpGet(quorumURI));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertTrue(response.containsHeader(NodeServiceServlet.NODE_HEADER));
            Assert.assertEquals(NODE_1, response.getFirstHeader(NodeServiceServlet.NODE_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}

From source file:org.hsweb.web.oauth2.controller.OAuth2Controller.java

@RequestMapping(value = "/access_token", method = { RequestMethod.POST })
@AccessLogger("?access_token")
public ResponseMessage accessToken(
        @RequestParam(value = OAuth.OAUTH_GRANT_TYPE, defaultValue = "client_credentials") String grantType,
        HttpServletRequest request) {/* w ww .j  ava2  s.c  o m*/
    try {
        OAuthTokenRequest tokenRequest = new OAuthTokenRequest(request);
        //?OAuth
        String clientId = tokenRequest.getClientId();
        String clientSecret = tokenRequest.getClientSecret();
        OAuth2Client client = oAuth2ClientService.selectSingle(
                QueryParam.build().where("id", clientId).and("secret", clientSecret).and("status", 1));
        //?
        if (null == client) {
            throw new AuthorizeException(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT);
        }
        //???client_credentials?
        if (grantType.equals(GrantType.CLIENT_CREDENTIALS.toString())) {
            String userId = client.getUserId();
            String accessToken = oauthIssuerImpl.accessToken();
            String refreshToken = oauthIssuerImpl.refreshToken();
            OAuth2Access access = new OAuth2Access();
            access.setExpireIn(oAuth2Service.getDefaultExpireIn());
            access.setCreateDate(new Date());
            access.setAccessToken(accessToken);
            access.setRefreshToken(refreshToken);
            access.setUserId(userId);
            access.setClientId(clientId);
            oAuth2Service.addAccessToken(access);
            OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                    .setTokenType("bearer").setAccessToken(accessToken)
                    .setExpiresIn(String.valueOf(oAuth2Service.getDefaultExpireIn()))
                    .setRefreshToken(refreshToken).setScope("public").buildJSONMessage();
            return ResponseMessage.ok(response.getBody()).onlyData();
        } else {
            throw new AuthorizeException(OAuthError.TokenResponse.UNSUPPORTED_GRANT_TYPE);
        }
    } catch (Exception e) {
        throw new AuthorizeException(e.getMessage(), e, 401);
    }
}