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.thoughtworks.go.domain.ChecksumFileHandler.java

public boolean handleResult(int returncode, GoPublisher goPublisher) {
    if (returncode == HttpServletResponse.SC_NOT_FOUND) {
        deleteQuietly(checksumFile);/*from ww  w .  j a  v a  2 s .c  om*/
        goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR,
                "[WARN] The md5checksum property file was not found on the server. Hence, Go can not verify the integrity of the artifacts.");
        return true;
    }
    if (returncode == HttpServletResponse.SC_NOT_MODIFIED) {
        LOG.info("[Agent Fetch Artifact] Not downloading checksum file as it has not changed");
        return true;
    }
    if (returncode == HttpServletResponse.SC_OK) {
        LOG.info("[Agent Fetch Artifact] Saved checksum property file [{}]", checksumFile);
        return true;
    }
    return returncode < HttpServletResponse.SC_BAD_REQUEST;
}

From source file:com.datatorrent.lib.io.HttpInputOperatorTest.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test/*from   w  w w.  j  av  a  2 s .c  om*/
public void testHttpInputModule() throws Exception {

    final List<String> receivedMessages = new ArrayList<String>();
    Handler handler = new AbstractHandler() {
        int responseCount = 0;

        @Override
        public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), bos);
            receivedMessages.add(new String(bos.toByteArray()));
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Transfer-Encoding", "chunked");
            try {
                JSONObject json = new JSONObject();
                json.put("responseId", "response" + ++responseCount);
                byte[] bytes = json.toString().getBytes();
                response.getOutputStream().println(bytes.length);
                response.getOutputStream().write(bytes);
                response.getOutputStream().println();
                response.getOutputStream().println(0);
                response.getOutputStream().flush();
            } catch (JSONException e) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error generating response: " + e.toString());
            }

            ((Request) request).setHandled(true);
        }
    };

    Server server = new Server(0);
    server.setHandler(handler);
    server.start();

    String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext";
    System.out.println(url);

    final AbstractHttpInputOperator operator = new HttpJsonChunksInputOperator();

    CollectorTestSink sink = new CollectorTestSink();

    operator.outputPort.setSink(sink);
    operator.setName("testHttpInputNode");
    operator.setUrl(new URI(url));

    operator.setup(null);
    operator.activate(null);

    int timeoutMillis = 3000;
    while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) {
        operator.emitTuples();
        timeoutMillis -= 20;
        Thread.sleep(20);
    }

    Assert.assertTrue("tuple emmitted", sink.collectedTuples.size() > 0);

    Map<String, String> tuple = (Map<String, String>) sink.collectedTuples.get(0);
    Assert.assertEquals("", tuple.get("responseId"), "response1");

    operator.deactivate();
    operator.teardown();
    server.stop();

}

From source file:com.rsginer.spring.controllers.RestaurantesController.java

@RequestMapping(value = { "/restaurantes" }, method = RequestMethod.GET, produces = "application/json")
public void getRestaurantes(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse) {
    List<Restaurante> listaRestaurantes = new ArrayList<>();
    try {/* w ww .j  a  v a2 s  .c o m*/
        listaRestaurantes = restaurantesDAO.findAll();
        String jsonSalida = jsonTransformer.toJson(listaRestaurantes);
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonSalida);
    } catch (BussinessException ex) {
        List<BussinessMessage> bussinessMessages = ex.getBussinessMessages();
        String jsonSalida = jsonTransformer.toJson(bussinessMessages);
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(RestaurantesController.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(RestaurantesController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}

From source file:net.sf.j2ep.responsehandlers.OptionsResponseHandler.java

/**
 * Will check if we are to handle this request, if so 
 * the http methods allowed by this proxy is returned in the 
 * Allow header./* w w w  . ja  va2s.c om*/
 * If it is a request meant for the backing server its
 * allowed method will be returned.
 * 
 * @see net.sf.j2ep.model.ResponseHandler#process(javax.servlet.http.HttpServletResponse)
 */
public void process(HttpServletResponse response) {
    if (useOwnAllow) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("allow", AllowedMethodHandler.getAllowHeader());
        response.setHeader("Connection", "close");
        response.setHeader("content-length", "0");
    } else {
        setHeaders(response);
        response.setStatus(getStatusCode());
        String allow = method.getResponseHeader("allow").getValue();
        response.setHeader("allow", AllowedMethodHandler.processAllowHeader(allow));
        Header contentLength = method.getResponseHeader("Content-Length");
        if (contentLength == null || contentLength.getValue().equals("0")) {
            response.setHeader("Content-Length", "0");
        } else {
            try {
                sendStreamToClient(response);
            } catch (IOException e) {
                log.error("Problem with writing response stream, solving by setting Content-Length=0", e);
                response.setHeader("Content-Length", "0");
            }
        }
    }
}

From source file:com.datatorrent.lib.io.HttpLinesInputOperatorTest.java

@Test
public void testHttpInputModule() throws Exception {

    final List<String> receivedMessages = new ArrayList<String>();
    Handler handler = new AbstractHandler() {
        @Override//from ww  w.ja v  a  2s  .  c o m
        public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response)
                throws IOException, ServletException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), bos);
            receivedMessages.add(new String(bos.toByteArray()));
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getOutputStream().println("Hello");
            response.getOutputStream().println("World,");
            response.getOutputStream().println("Big");
            response.getOutputStream().println("Data!");
            response.getOutputStream().flush();

            ((Request) request).setHandled(true);
        }

    };

    Server server = new Server(0);
    server.setHandler(handler);
    server.start();

    String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext";

    final HttpLinesInputOperator operator = new HttpLinesInputOperator();
    CollectorTestSink<String> sink = TestUtils.setSink(operator.outputPort, new CollectorTestSink<String>());
    operator.setUrl(new URI(url));

    operator.setup(null);
    operator.activate(null);

    int timeoutMillis = 3000;
    while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) {
        operator.emitTuples();
        timeoutMillis -= 20;
        Thread.sleep(20);
    }

    Assert.assertTrue("tuple emitted", sink.collectedTuples.size() > 0);

    Assert.assertEquals("", sink.collectedTuples.get(0), "Hello");
    Assert.assertEquals("", sink.collectedTuples.get(1), "World,");
    Assert.assertEquals("", sink.collectedTuples.get(2), "Big");
    Assert.assertEquals("", sink.collectedTuples.get(3), "Data!");

    operator.deactivate();
    operator.teardown();
    server.stop();

}

From source file:com.janrain.servlet.JsonpCallbackFilter.java

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

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Map<String, String[]> parameters = httpRequest.getParameterMap();
    String callbackName = "";
    String[] values = parameters.get("callback");
    if (values != null) {
        callbackName = values[0];//from   w  w w.  ja v  a 2s.com
    }

    if (StringUtils.isNotBlank(callbackName)) {
        // wrap the json in the callback
        OutputStream stream = httpResponse.getOutputStream();
        GenericResponseWrapper wrapper = new GenericResponseWrapper(httpResponse);

        chain.doFilter(request, wrapper);

        stream.write((callbackName + "(").getBytes());
        stream.write(wrapper.getData());
        stream.write(");".getBytes());

        wrapper.setContentType("text/javascript;charset=UTF-8");
        // always return 200 when using the callback to allow the message to
        // reach the browser based function
        wrapper.setStatus(HttpServletResponse.SC_OK);
        stream.close();

    } else {
        // pass the request/response on
        chain.doFilter(request, response);
    }

}

From source file:org.codemucker.testserver.TestServerTest.java

@SuppressWarnings("serial")
@Test/* w  w  w. ja v  a2 s.  c  o m*/
public void ensure_custom_servlets_are_invoked() throws Exception {
    final Collection<CapturedRequest> capturedRequests = new Vector<CapturedRequest>();

    server.addServlet("/my/test/path", new TestServlet() {
        @Override
        protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
                throws ServletException, IOException {
            capturedRequests.add(new CapturedRequest(req));
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    });
    server.start();

    final long paramX = System.currentTimeMillis();
    final String url = "http://" + server.getHost() + ":" + server.getHttpPort() + "/my/test/path?x=" + paramX;

    //check we can hit the servlet, that it's run only once, and that we get the params passed to it
    final HttpClient client = HttpClientBuilder.create().build();
    final HttpGet get = new HttpGet(url);
    final HttpResponse resp = client.execute(get);

    assertEquals(HttpServletResponse.SC_OK, resp.getStatusLine().getStatusCode());
    assertEquals(1, capturedRequests.size());
    final CapturedRequest req = capturedRequests.iterator().next();
    assertEquals(paramX + "", req.getParameters().get("x").iterator().next());
}

From source file:com.sdapp.server.LoginServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SdLogger.getInstance().getLogger().info("Post on LoginServlet");

    /**//from  w  w  w.  ja v  a 2 s.c o m
     * Get the parameters
     */
    String username = request.getParameter("username");
    String isDeviceString = request.getParameter("isDevice");
    boolean isDevice = false;

    if (isDeviceString != null && isDeviceString.length() > 0)
        isDevice = Boolean.parseBoolean(isDeviceString);

    UserMsg user = null;
    /**
     * Sanity check
     */
    if ((username != null) && (username.length() > 0) && (true == username.contains("@"))) {
        /**
         * See if the user object exists
         */
        user = DAO.getUser(username, true);
    }

    /** Login failed */
    if (null == user) {
        /** If login failed on device, return a 403 */
        if (isDevice) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        } else {
            /** Create the response */
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String title = "Login Failure";
            out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n"
                    + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n");
            /** End table */
            out.println("</TABLE>\n</BODY></HTML>");
        }
    }
    /** Login successful */
    else {
        /** Login successful */
        response.setStatus(HttpServletResponse.SC_OK);

        /** JSON response or html*/
        if (createJSONRespone) {
            /**
             * TODO: Sid fix this.
             * Cant figure out how to deserialize JSON objects on client.
             * It keeps crashing. So extracting String and passing String object.
             */
            String licensePlateString = "";
            for (LicensePlateMsg msg : user.getLicensePlateList()) {
                licensePlateString += ";" + msg.getLicensePlateNumber();
            }
            LicensePlateJsonObject msg = new LicensePlateJsonObject();
            msg.setLicensePlateList(licensePlateString);
            /** JSONify the object and bundle it with the response*/
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(msg);
            response.setContentType("application/json");
            PrintWriter out = response.getWriter();
            out.write(json);
            out.close();
        } else {
            createHTMLSuccessResponse(response, user);
        }
    }
}

From source file:net.thewaffleshop.passwd.security.AuthenticationHandler.java

/**
 * Successful login; send the redirect URL
 *
 * @param request//  w  ww  .  j  a  v  a2 s .  c  o  m
 * @param response
 * @param authentication
 * @throws IOException
 * @throws ServletException
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    AccountAuthenticationToken auth = (AccountAuthenticationToken) authentication;

    HttpSession session = request.getSession();
    session.setAttribute("account", auth.getAccount());
    session.setAttribute("secretKey", auth.getSecretKey());

    String url = ServletUriComponentsBuilder.fromContextPath(request).path(TARGET_URL).build().toUriString();

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");
    response.getWriter().write("{\"success\": true, \"url\": \"" + StringEscapeUtils.escapeJson(url) + "\"}");
}

From source file:de.mendelson.comm.as2.client.HTMLPanel.java

/**Sets a new page to the viewer and handles the Stack update
 *@param url URL to move to//  w  w  w.j ava 2  s .  c  om
 */
public Header[] setURL(String urlStr, String userAgent, File fallbackOnError) {
    Header[] header = new Header[0];
    try {
        //post for header data
        HttpPost filePost = new HttpPost(new URL(urlStr).toExternalForm());
        HttpParams params = filePost.getParams();
        HttpProtocolParams.setUserAgent(params, userAgent);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(filePost);
        header = httpResponse.getAllHeaders();
        int status = httpResponse.getStatusLine().getStatusCode();
        if (status != HttpServletResponse.SC_OK) {
            throw new Exception("HTTP " + status);
        }
        httpClient.getConnectionManager().shutdown();
        //now get for body data
        this.jEditorPane.setPage(new URL(urlStr));
    } catch (Exception e) {
        e.printStackTrace();
        try {
            this.setPage(fallbackOnError);
        } catch (Exception ex) {
            //nop
        }
    }
    return (header);
}