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.imaginary.home.device.hue.HueMethod.java

public void delete(@Nonnull String resource) throws HueException {
    Logger std = Hue.getLogger(HueMethod.class);
    Logger wire = Hue.getWireLogger(HueMethod.class);

    if (std.isTraceEnabled()) {
        std.trace("enter - " + HueMethod.class.getName() + ".delete(" + resource + ")");
    }/*  w w w.jav a  2s .c o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [DELETE (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource);
    }
    try {
        HttpClient client = getClient();
        HttpDelete method = new HttpDelete(hue.getAPIEndpoint() + resource);

        method.addHeader("Content-Type", "application/json");
        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            std.error("DELETE: Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new HueException(e);
        }
        if (std.isDebugEnabled()) {
            std.debug("DELETE: HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_NO_CONTENT
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            std.error("DELETE: Expected OK or NO_CONTENT or ACCEPTED for DELETE request, got "
                    + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new HueException(status.getStatusCode(), "An error was returned without explanation");
            }
            String body;

            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            throw new HueException(status.getStatusCode(), body);
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + HueMethod.class.getName() + ".delete()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [DELETE (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java

/**
 * Handles the HTTP/*from ww w .  ja va 2s  .  c om*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);

    if (isMultiPart) {
        log("Content-Type: " + request.getContentType());
        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

        List items = null;

        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        ListIterator li = items.listIterator();

        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                if (debug) {
                    processFormField(fileItem);
                }
            } else {
                writer.print(processUploadedFile(fileItem));
            }
        }
    }

    if ("application/octet-stream".equals(request.getContentType())) {
        log("Content-Type: " + request.getContentType());
        String filename = request.getHeader("X-File-Name");

        try {
            is = request.getInputStream();
            fos = new FileOutputStream(new File(realPath + filename));
            IOUtils.copy(is, fos);
            response.setStatus(HttpServletResponse.SC_OK);
            writer.print("{success: true}");
        } catch (FileNotFoundException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }

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

From source file:ee.ria.xroad.asyncsender.ProxyClientTest.java

/**
 * Test./*from   ww w . j  a va 2  s .  c  om*/
 * @throws Exception if an error occurs
 */
@Test
public void sendMessageAndGetUnknownResponse() throws Exception {
    createMockServer(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            checkHeader(request);

            response.setContentType(MimeTypes.TEXT_PLAIN);
            response.setStatus(HttpServletResponse.SC_OK);

            response.getOutputStream().write("Hello world!".getBytes(StandardCharsets.UTF_8));

            baseRequest.setHandled(true);
        }
    });

    client.send(MimeTypes.TEXT_XML, getSimpleMessage());
}

From source file:com.googlesource.gerrit.plugins.oauth.GoogleOAuthService.java

@Override
public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
    service.signRequest(t, request);//from w  w w  .j a  va2 s .  c  o m
    Response response = request.send();
    if (response.getCode() != HttpServletResponse.SC_OK) {
        throw new IOException(String.format("Status %s (%s) for request %s", response.getCode(),
                response.getBody(), request.getUrl()));
    }
    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
    if (log.isDebugEnabled()) {
        log.debug("User info response: {}", response.getBody());
    }
    if (userJson.isJsonObject()) {
        JsonObject jsonObject = userJson.getAsJsonObject();
        JsonElement id = jsonObject.get("id");
        if (id == null || id.isJsonNull()) {
            throw new IOException("Response doesn't contain id field");
        }
        JsonElement email = jsonObject.get("email");
        JsonElement name = jsonObject.get("name");
        String login = null;

        if (domains.size() > 0) {
            boolean domainMatched = false;
            JsonObject jwtToken = retrieveJWTToken(token);
            String hdClaim = retrieveHostedDomain(jwtToken);
            for (String domain : domains) {
                if (domain.equalsIgnoreCase(hdClaim)) {
                    domainMatched = true;
                    break;
                }
            }
            if (!domainMatched) {
                // TODO(davido): improve error reporting in OAuth extension point
                log.error("Error: hosted domain validation failed: {}", Strings.nullToEmpty(hdClaim));
                return null;
            }
        }
        if (useEmailAsUsername && !email.isJsonNull()) {
            login = email.getAsString().split("@")[0];
        }
        return new OAuthUserInfo(GOOGLE_PROVIDER_PREFIX + id.getAsString() /*externalId*/, login /*username*/,
                email == null || email.isJsonNull() ? null : email.getAsString() /*email*/,
                name == null || name.isJsonNull() ? null : name.getAsString() /*displayName*/,
                fixLegacyUserId ? id.getAsString() : null /*claimedIdentity*/);
    }

    throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
}

From source file:hr.diskobolos.controller.EvaluationController.java

/**
 * REST service responsible for creation of evaluation answers
 *
 * @param evaluationAnswerDto/*from ww w .  j av  a  2 s  .c  o  m*/
 * @param request
 * @param response
 * @return
 * @throws JSONException
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasRole('ADMIN')")
public String createEvaluationAnswers(@RequestBody EvaluationAnswerDto evaluationAnswerDto,
        HttpServletRequest request, HttpServletResponse response) throws JSONException {
    try {
        evaluationAnswerService.bulkSave(evaluationAnswerDto.getEvaluationAnswers());
        response.setStatus(HttpServletResponse.SC_OK);
        return new JSONObject().put("result", 200).toString();
    } catch (Exception e) {
        logger.error("Error during editing member register data: ", e.getMessage());
        return ErrorHandlerUtils.handleAjaxError(request, response);
    }
}

From source file:eu.eidas.node.service.ServiceExceptionHandlerServlet.java

/**
 * Prepares exception redirection, or if no information is available to redirect, prepares the exception to be
 * displayed. Also, clears the current session object, if not needed.
 *
 * @return {ERROR} if there is no URL to return to, {SUCCESS} otherwise.
 *//*from w  ww .j av  a 2 s .c  o m*/
private void handleError(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /*
      Current exception.
     */
    AbstractEIDASException exception;
    /*
      URL to redirect the citizen to.
     */
    String errorRedirectUrl;

    String retVal = NodeViewNames.INTERNAL_ERROR.toString();
    try {
        // Prevent cookies from being accessed through client-side script.
        setHTTPOnlyHeaderToSession(false, request, response);

        //Set the Exception
        exception = (AbstractEIDASException) request.getAttribute("javax.servlet.error.exception");
        prepareErrorMessage(exception, request);
        errorRedirectUrl = prepareSession(exception, request);
        request.setAttribute(NodeParameterNames.EXCEPTION.toString(), exception);

        if (!StringUtils.isBlank(exception.getSamlTokenFail()) && null != errorRedirectUrl) {
            retVal = NodeViewNames.SUBMIT_ERROR.toString();
        } else if (exception instanceof EidasNodeException || exception instanceof EIDASServiceException) {
            retVal = NodeViewNames.PRESENT_ERROR.toString();
        } else if (exception instanceof InternalErrorEIDASException) {
            LOG.debug("BUSINESS EXCEPTION - null redirectUrl or SAML response");
            retVal = NodeViewNames.INTERNAL_ERROR.toString();
        } else {
            LOG.warn("exception not recognized so internal error page shown", exception);
            retVal = NodeViewNames.INTERNAL_ERROR.toString();
        }

    } catch (Exception e) {
        LOG.info("BUSINESS EXCEPTION: in exception handler: " + e, e);
    }
    //Forward to error page
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(retVal);
    response.setStatus(HttpServletResponse.SC_OK);
    dispatcher.forward(request, response);
}

From source file:com.cloud.servlet.StaticResourceServletTest.java

@Test
public void testCompressedFile() throws ServletException, IOException {
    final HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Accept-Encoding", "gzip");
    final HttpServletResponse response = doGetTest("default.css", headers);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
    Mockito.verify(response).setContentType("text/css");
    Mockito.verify(response, Mockito.times(1)).setHeader("Content-Encoding", "gzip");
}

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Handle hand shake./*from   ww  w.j a  va  2  s . c o m*/
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleHandShake(final HttpServletRequest req, final HttpServletResponse res)
        throws IOException {
    final String time = req.getHeader("X-Eve-requestToken");

    if (time == null) {
        return false;
    }

    final String token = TokenStore.get(time);
    if (token == null) {
        res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
    } else {
        res.setHeader("X-Eve-replyToken", token);
        res.setStatus(HttpServletResponse.SC_OK);
        res.flushBuffer();
    }
    return true;
}

From source file:hr.diskobolos.controller.MemberRegisterController.java

/**
 * REST service responsible for editing member register data
 *
 * @param memberRegister//  w w w .  j  av a 2  s.c  om
 * @param request
 * @param response
 * @return
 * @throws JSONException
 */
@RequestMapping(value = "/edit", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
public String editMemberRegisterData(@RequestBody MemberRegister memberRegister, HttpServletRequest request,
        HttpServletResponse response) throws JSONException {
    try {
        memberRegister.getEmails().stream().forEach((email) -> {
            email.setMemberRegister(memberRegister);
        });
        memberRegister.getBankAccounts().stream().forEach((bankAccounts) -> {
            bankAccounts.setMemberRegister(memberRegister);
        });

        List<Phone> phones = mapPhoneDtoToPhoneModelObject(memberRegister.getPhonesDto());
        phones.stream().forEach((phone) -> {
            phone.setMemberRegister(memberRegister);
        });
        memberRegister.setPhones(phones);

        memberRegisterService.update(memberRegister);

        if (memberRegister.getRemovedPhones() != null) {
            phoneService.delete(memberRegister.getRemovedPhones());
        }

        if (memberRegister.getRemovedEmails() != null) {
            emailService.delete(memberRegister.getRemovedEmails());
        }

        if (memberRegister.getRemovedBankAccounts() != null) {
            bankAccountService.delete(memberRegister.getRemovedBankAccounts());
        }

        response.setStatus(HttpServletResponse.SC_OK);
        return new JSONObject().put("result", 200).toString();
    } catch (Exception e) {
        logger.error("Error during editing member register data: ", e.getMessage());
        return ErrorHandlerUtils.handleAjaxError(request, response);
    }
}

From source file:org.jboss.as.test.clustering.cluster.singleton.SingletonBackupServiceTestCase.java

@Test
public void testSingletonService(
        @ArquillianResource(ValueServiceServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(ValueServiceServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, URISyntaxException {

    // Needed to be able to inject ArquillianResource
    stop(CONTAINER_2);//from   w w w.  jav  a2  s. c o  m

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_2);

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("false",
                    response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        stop(CONTAINER_2);

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_2);

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("false",
                    response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        stop(CONTAINER_1);

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_1);

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL1, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("false",
                    response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(
                new HttpGet(ValueServiceServlet.createURI(baseURL2, ValueServiceActivator.SERVICE_NAME)));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("true", response.getFirstHeader(ValueServiceServlet.PRIMARY_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}