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.tasktop.c2c.server.common.service.tests.ajp.AjpProxyWebTest.java

@Test
public void testProxyHandlesCookies() throws Exception {
    final String ajpBaseUri = String.format("ajp://localhost:%s", container.getAjpPort());
    Payload payload = new Payload(HttpServletResponse.SC_OK, "some content\none two three\n\nfour");
    payload.getResponseHeaders().put("foo", "bar");
    payload.getSessionVariables().put("s1", "v1");
    TestServlet.setResponsePayload(payload);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/test");
    request.setQueryString("a=b");
    request.setParameter("a", new String[] { "b" });
    request.addHeader("c", "d ef");
    MockHttpServletResponse response = new MockHttpServletResponse();
    proxy.proxyRequest(ajpBaseUri + "/foo", request, response);

    Request firstRequest = null;//  w w w  . j a  v a 2 s. c o m
    for (int i = 0; i < 100; i++) {
        firstRequest = TestServlet.getLastRequest();

        // If our request is not yet there, then pause and retry shortly - proxying is an async process, and this
        // request was sometimes coming back as null which was causing test failures on the first assert below.
        if (firstRequest == null) {
            Thread.sleep(10);
        } else {
            // Got our request, so break now.
            break;
        }
    }

    Assert.assertTrue(firstRequest.isNewSession());
    Assert.assertEquals("v1", firstRequest.getSessionAttributes().get("s1"));

    List<org.apache.commons.httpclient.Cookie> cookies = new ArrayList<org.apache.commons.httpclient.Cookie>();
    for (String headerName : response.getHeaderNames()) {
        if (headerName.equalsIgnoreCase("set-cookie") || headerName.equalsIgnoreCase("set-cookie2")) {
            cookies.addAll(Arrays.asList(new RFC2965Spec().parse("localhost", container.getPort(), "/", false,
                    response.getHeader(headerName).toString())));
        }
    }
    Assert.assertEquals(1, cookies.size());
    Cookie cookie = cookies.get(0);
    Assert.assertEquals("almp.JSESSIONID", cookie.getName());

    MockHttpServletRequest request2 = new MockHttpServletRequest();
    request2.setMethod("GET");
    request2.setRequestURI("/test");
    request2.addHeader("Cookie", cookie.toExternalForm());
    MockHttpServletResponse response2 = new MockHttpServletResponse();

    payload = new Payload(HttpServletResponse.SC_OK, "test");
    TestServlet.setResponsePayload(payload);

    proxy.proxyRequest(ajpBaseUri + "/foo", request2, response2);

    Request secondRequest = TestServlet.getLastRequest();
    Assert.assertFalse(secondRequest.isNewSession());
    Assert.assertEquals(firstRequest.getSessionId(), secondRequest.getSessionId());
    Assert.assertEquals("v1", secondRequest.getSessionAttributes().get("s1"));
}

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

/**
 * {@inheritDoc}//from  ww  w .  ja v a 2s.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 i18n dictionary and tag");

    String requestUrl = UrlUtils.concat(serverUrl, TEST_URL);
    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());

        Document xml = TestUtils.parseXMLResponse(response);

        // Test i18n values defined at the module level
        String i18nModuleValue = "I18n Module Value";
        String xpath = "/html/body//div[@id='i18n-module']";
        Assert.assertEquals(i18nModuleValue, XPathHelper.valueOf(xml, xpath));

        // Test i18n values defined at the page level
        String i18nPageValue = "I18n Page Value";
        xpath = "/html/body//div[@id='i18n-page']";
        Assert.assertEquals(i18nPageValue, XPathHelper.valueOf(xml, xpath));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.github.rabid_fish.proxy.servlet.SoapServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter writer = response.getWriter();
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/xml");

    try {//from  w  ww  .ja  v  a  2s.c om
        ServletInputStream stream = request.getInputStream();
        String requestBody = IOUtils.toString(stream);

        Integer mathResult = getMathResult(requestBody);
        writeMathResult(writer, mathResult);
    } catch (Exception e) {
        writeSoapError(writer, e.getMessage());
    }

    writer.flush();
    writer.close();
}

From source file:com.image32.demo.simpleapi.ContentHandler.java

@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    HttpSession session = request.getSession();
    response.setStatus(HttpServletResponse.SC_OK);
    httpHeaderNoCache(response);/*www  .  jav a2  s . c om*/

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

    if (request.getMethod().equals("POST") && target.equals("/login")) {
        response.setContentType("application/json;charset=utf-8");
        String requestToken = request.getParameter("requestToken");
        String demoPass = request.getParameter("demoPass");
        logger.info("logging in with requestToken:" + requestToken + " demoPass:" + demoPass);
        Image32APIAuthResponse responseObj = null;
        HashMap<String, String> out = new HashMap<String, String>();

        if (demoPass != null && (demoPass.equals("admin"))) { //has no security for this demo.
            session.setAttribute("adminRole", true);
            //authenticate with image32 api
            DefaultHttpClient httpclient = new DefaultHttpClient();//
            HttpPost httpPost = new HttpPost(SimpleApiDemo.image32ApiAuthUrl);
            try {
                String body = "{\"client_id\": \"" + SimpleApiDemo.image32ApiClientId
                        + "\",\"client_secret\":\"" + SimpleApiDemo.image32ApiSecrect
                        + "\",\"auth_request_token\":\"" + requestToken + "\",";
                body += "\"scopes\":[";
                body += "{\"type\":\"user-id\",\"id\":\"abc_user_001\",\"permission\":\"view\"},"; //give access to all studies
                body += "{\"type\":\"case-id\",\"id\":\"abc\",\"permission\":\"full\"}"; //give full access to case/folder 'abc'
                body += "]}";
                HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8"));
                httpPost.setEntity(entity);
                HttpResponse apiResponse = httpclient.execute(httpPost);
                String result = EntityUtils.toString(apiResponse.getEntity());
                logger.info("image32 api response:" + result);
                EntityUtils.consume(entity);
                //parse response
                Gson gson = new Gson();
                responseObj = gson.fromJson(result, Image32APIAuthResponse.class);
                session.setAttribute("responseObj", responseObj);

                if (responseObj != null && responseObj.getRedirect_url() != null) {
                    out.put("confirmUrl", responseObj.getRedirect_url());
                }

            } catch (ParseException e) {
                logger.warn(e.getMessage());

            } finally {
                httpPost.releaseConnection();
            }
            out.put("result", "true");

            //print journal entries
            Gson gson = new Gson();

            //print response
            String outStr = gson.toJson(out);
            response.getWriter().println(outStr);
        } else {
            response.getWriter().println("{\"result\":false}");//role is not valid
        }

        return;

    }
    //      else if (request.getMethod().equals("POST") && target.equals("/getStudies") && isWriter(session)) {
    //         //get all available studies for current session
    //         response.setContentType("application/json;charset=utf-8");
    //         logger.info("getStudies");
    //         
    //         Image32APIAuthResponse responseObj = (Image32APIAuthResponse)session.getAttribute("responseObj");
    //         if(responseObj!=null){
    //            //get all studies
    //            HttpGet httpGet = new HttpGet(SimpleApiDemo.image32ApiGetStudiesUrl);
    //            
    //            try {
    //               httpGet.setHeader("Authorization", "Bearer "+responseObj.getAccess_token());
    //               DefaultHttpClient httpclient = new DefaultHttpClient();
    //               HttpResponse apiResponse = httpclient.execute(httpGet);
    //               String result = EntityUtils.toString(apiResponse.getEntity());
    //               EntityUtils.consume(apiResponse.getEntity());
    //               response.getWriter().println(result);
    //               logger.info("image32 api response:" + result);
    //               
    //            } catch (ParseException e) {
    //               logger.warn(e.getMessage());
    //               
    //            }finally{
    //               httpGet.releaseConnection();
    //            }
    //         }
    //      }
}

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

@RequestMapping(value = { "/Puesto/{idsPuestos}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsPuestos") String idsPuestosStr) {

    try {//from  www .  j av  a  2 s.  c om

        String[] idsPuestosArr = idsPuestosStr.split(",");
        List<Puesto> listaPuestos = new ArrayList();
        for (int i = 0; i < idsPuestosArr.length; i++) {
            listaPuestos.add(puestoDAO.read(Integer.parseInt(idsPuestosArr[i])));
        }

        if (listaPuestos.isEmpty() == false) {

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

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

        } else {

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

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de puestos de trabajo esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            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:de.quadrillenschule.azocamsynca.webservice.WebService.java

public WebService(final JobProcessor jobProcessor) {
    history = new History(jobProcessor.getActivity().getApplication());
    this.jobProcessor = jobProcessor;
    Server server = new Server(8000);
    server.setHandler(new AbstractHandler() {

        public void handle(String string, Request baseRequest, HttpServletRequest hsr,
                HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            final HttpServletResponse finalresponse = response;
            baseRequest.setHandled(true);
            if (baseRequest.getPathInfo().contains(WebCommands.list.name())) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(jobProcessor.toJSONArray().toString());
                return;
            }/*w  ww. ja va2 s  . c  o m*/
            if (baseRequest.getPathInfo().contains(WebCommands.pulltrigger.name())) {
                new NikonIR(activity).trigger();
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.jobprocessorstatus.name())) {
                response.getWriter().println(jobProcessor.getStatus().name());
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.startjobprocessor.name())) {
                startJobProcessor(finalresponse);
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.pausejobprocessor.name())) {
                pauseJobProcessor(finalresponse);
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.addjob.name())) {
                addJob(finalresponse, baseRequest);
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.confirmdialog.name())) {
                ((AzoTriggerServiceApplication) activity.getApplication()).getJobProcessor()
                        .confirmPreparedDialog();
                response.getWriter().println(COMMAND_RECEIVED);

                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.addform.name())) {
                response.getWriter().println(printForm());
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.help.name())) {
                response.getWriter().println(ArrayUtils.toString(WebCommands.values()));
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.updateTriggered.name())) {
                updateTriggered(finalresponse, baseRequest);
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.updateJob.name())) {
                updateJob(finalresponse, baseRequest);
                return;
            }
            if (baseRequest.getPathInfo().contains(WebCommands.removejob.name())) {
                removeJob(finalresponse, baseRequest);
                return;
            }
            response.getWriter().println("<h1>AZoCamsyncTrigger Webservice is alive!</h1>");

        }
    });
    try {
        server.start();
    } catch (Exception ex) {
        Logger.getLogger(WebService.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.openmrs.module.casereport.CrossOriginResourceSharingFilter.java

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */// ww w.  ja  v a2 s  . com
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        log.debug("In Cors filter...");
    }
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    String gpValue = Context.getAdministrationService()
            .getGlobalProperty(CaseReportWebConstants.GP_ENABLE_CORS);
    if (Boolean.valueOf(gpValue)) {
        if (log.isDebugEnabled()) {
            log.debug("Cors is enabled");
        }
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST");
        response.addHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.addHeader("Access-Control-Max-Age", "3600");

        //TODO add GP to disable this filter
        if (request.getMethod().equals("OPTIONS")) {

            if (log.isDebugEnabled()) {
                log.debug("Cors filter responding with Ok status");
            }
            response.setStatus(HttpServletResponse.SC_OK);

            return;
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Cors is disabled");
        }
    }

    // pass the request along the filter chain
    chain.doFilter(request, servletResponse);
}

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

@RequestMapping(value = { "/Familia/{idsFamilias}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsFamilias") String idsFamiliasStr) {

    try {/*from  w  w  w  .  j  av  a  2s.  c o m*/

        String[] idsFamiliasArr = idsFamiliasStr.split(",");
        List<Familia> listaFamilias = new ArrayList();
        for (int i = 0; i < idsFamiliasArr.length; i++) {
            listaFamilias.add(familiaDAO.read(Integer.parseInt(idsFamiliasArr[i])));
        }
        if (listaFamilias.isEmpty() == false) {

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

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

        } else {

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

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de puestos de trabajo esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            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.thoughtworks.go.domain.ChecksumFileHandlerTest.java

@Test
public void shouldRetainMd5ChecksumFileIfItIsDownloadedSuccessfully() throws IOException {
    StubGoPublisher goPublisher = new StubGoPublisher();
    file.createNewFile();/*from   ww  w  .  j a  v  a 2s  .  c om*/

    boolean isSuccessful = checksumFileHandler.handleResult(HttpServletResponse.SC_OK, goPublisher);
    assertThat(isSuccessful, is(true));
    assertThat(file.exists(), is(true));

}

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

@RequestMapping(value = "/usuario", method = RequestMethod.GET, produces = "application/json")
public void find(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    try {// w ww  .  jav  a 2 s.c  o m

        List<Usuario> usuarios;

        if (httpServletRequest.getParameter("name") != null) {

            usuarios = usuarioService.findByNombre(httpServletRequest.getParameter("name"));
        } else {
            usuarios = usuarioService.findAll();
        }

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        String jsonSalida = jsonTransformer.ObjectToJson(usuarios);
        httpServletResponse.getWriter().println(jsonSalida);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}