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:org.magnum.mobilecloud.video.VideoSvcCtrl.java

@PreAuthorize("hasRole(USER)")
@RequestMapping(method = RequestMethod.POST, value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like")
public @ResponseBody void likeVideo(@PathVariable("id") long id, Principal principal,
        HttpServletResponse response) {/*from w w  w.  ja  v  a  2  s  .  com*/
    Video v = videoRepo.findOne(id);
    if (v != null) {
        HashSet<String> likers = v.getLikers();
        if (likers.contains(principal.getName()))
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        else {
            likers.add(principal.getName());
            videoRepo.save(v);
            response.setStatus(HttpServletResponse.SC_OK);
        }
    } else
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:com.thoughtworks.go.domain.ChecksumFileHandlerTest.java

@Test
public void shouldHandleResultIfHttpCodeIsSuccessful() {
    StubGoPublisher goPublisher = new StubGoPublisher();
    assertThat(checksumFileHandler.handleResult(HttpServletResponse.SC_OK, goPublisher), is(true));
}

From source file:com.homesnap.webserver.LabelRestAPITest.java

@Test
public void test7UpdateLabel() {
    // Test new label creation
    JSONObject label = putRequestJSONObject(urn_labels + "/ch6", createJsonLabelCh6Bis(),
            HttpServletResponse.SC_OK);
    testLabelCh6Bis(label);/*w w w.  ja va 2  s.com*/

    label = putRequestJSONObject(urn_labels + "/label?id=ch7", createJsonLabelCh7Bis(),
            HttpServletResponse.SC_OK);
    testLabelCh7Bis(label);
}

From source file:com.commercehub.dropwizard.BuildInfoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControl.toString());
    response.setStatus(HttpServletResponse.SC_OK);

    String requestedKey = getRequestedKey(request);
    if (StringUtils.isNotBlank(requestedKey)) {
        writeValueForKey(requestedKey, response);
    } else if (requestedHtml(request)) {
        writeAllHtml(response);//w  w w  .ja va 2 s.  c  o m
    } else {
        writeAllJson(response);
    }
}

From source file:org.obm.opush.HealthCheckTest.java

@Test
public void testHealthCheckInstalled() throws Exception {
    mocksControl.replay();//from   ww  w  .  j a  v  a2 s  .  co  m
    opushServer.start();
    HttpResponse response = Request
            .Get("http://localhost:" + opushServer.getHttpPort() + "/opush/healthcheck/java/version").execute()
            .returnResponse();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpServletResponse.SC_OK);
    assertThat(IOUtils.toString(response.getEntity().getContent()))
            .isEqualTo(System.getProperty("java.version"));
}

From source file:net.ymate.module.sso.support.SSOUserSessionHandler.java

private boolean __doValidateToken(ISSOToken token) {
    try {/* ww  w.  j  ava2s .  c o m*/
        if (SSO.get().getModuleCfg().isClientMode()) {
            Map<String, String> _params = new HashMap<String, String>();
            _params.put("token_id", token.getId());
            _params.put("uid", token.getUid());
            _params.put("remote_addr", token.getRemoteAddr());
            _params.put("sign",
                    ParamUtils.createSignature(_params, false, SSO.get().getModuleCfg().getServiceAuthKey()));
            IHttpResponse _result = HttpClientHelper.create().post(
                    SSO.get().getModuleCfg().getServiceBaseUrl().concat("sso/authorize"), _params,
                    new Header[] {
                            new BasicHeader("User-Agent", WebContext.getRequest().getHeader("User-Agent")) });
            if (_result != null && _result.getStatusCode() == HttpServletResponse.SC_OK) {
                JSONObject _resultObj = JSON.parseObject(_result.getContent());
                if (_resultObj.getIntValue("ret") == ErrorCode.SUCCEED) {
                    // ?Cookie
                    SSO.get().getModuleCfg().getTokenAdapter().setToken(token);
                    // ?????token?
                    JSONObject _dataObj = _resultObj.getJSONObject("data");
                    if (_dataObj != null && !_dataObj.isEmpty()) {
                        for (Map.Entry<String, Object> _attr : _dataObj.entrySet()) {
                            token.getAttributes().put(_attr.getKey(),
                                    BlurObject.bind(_attr.getValue()).toStringValue());
                        }
                    }
                    //
                    return true;
                }
            }
        } else {
            ISSOTokenStorageAdapter _storageAdapter = SSO.get().getModuleCfg().getTokenStorageAdapter();
            // ???
            ISSOToken _originalToken = _storageAdapter.load(token.getUid(), token.getId());
            if (_originalToken != null) {
                boolean _ipCheck = (SSO.get().getModuleCfg().isIpCheckEnabled()
                        && !StringUtils.equals(token.getRemoteAddr(), _originalToken.getRemoteAddr()));
                if (_originalToken.timeout() || !_originalToken.verified() || _ipCheck) {
                    _storageAdapter.remove(_originalToken.getUid(), _originalToken.getId());
                } else {
                    // ?
                    ISSOTokenAttributeAdapter _attributeAdapter = SSO.get().getModuleCfg()
                            .getTokenAttributeAdapter();
                    if (_attributeAdapter != null) {
                        _attributeAdapter.loadAttributes(token);
                    }
                    return true;
                }
            }
        }
    } catch (Exception e) {
        _LOG.warn("An exception occurred while validate token '" + token.getId() + "' for user '"
                + token.getUid() + "'", RuntimeUtils.unwrapThrow(e));
    }
    return false;
}

From source file:eu.rethink.lhcb.broker.servlet.WellKnownServlet.java

private void handleRequest(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    // add header for cross domain stuff
    resp.addHeader("Access-Control-Allow-Origin", "*");
    String host = req.getHeader("X-Forwarded-Host");
    if (host == null)
        host = req.getHeader("Host");

    // setting external host here helps BrokerWebSocketListener to return info about HTTP interface
    // Broker might not know how it is accessible. This is a workaround for it
    LHCBBroker.externalHost = host;/*from w  ww  . ja va2s.c  om*/
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.start(() -> {
        ServletRequest aReq = asyncContext.getRequest();
        String payload = null;
        try {
            payload = IOUtils.toString(aReq.getReader());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String finalPayload = payload;

        Map<String, String[]> params = aReq.getParameterMap();
        LOG.debug("payload: {}\r\nparams: {}", payload, params);

        RequestCallback cb = new RequestCallback() {

            @Override
            public void response(Message msg) {
                resp.setStatus(HttpServletResponse.SC_OK);
                try {
                    asyncContext.getResponse().getWriter().write(msg.toString());
                    asyncContext.getResponse().getWriter().flush();
                    asyncContext.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Exception e) {
                String error = "Request failed.\r\npayload: " + finalPayload + "\r\nparams: " + params;
                LOG.error(error + "\r\nreason: " + e.getLocalizedMessage(),
                        e instanceof InvalidMessageException ? null : e);
                if (e instanceof InvalidMessageException) {
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                }
                completeAsyncContext(asyncContext, error + "\r\nreason: " + e.getLocalizedMessage());
            }
        };

        try {
            Message msg = null;

            if (payload.length() > 0) {
                msg = Message.fromString(payload);
            } else {
                msg = Message.fromParams(params);
            }

            requestHandler.handleRequest(msg, cb);
        } catch (InvalidMessageException e) {
            cb.error(e);
        }
    });
}

From source file:fedora.server.management.UploadServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    sendResponse(HttpServletResponse.SC_OK, "Client must use HTTP Multipart POST", response);
}

From source file:com.haulmont.cuba.restapi.FileUploadController.java

@RequestMapping(value = "/api/upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null)
        return;//from w ww . j ava 2s  . co  m

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        InputStream is = request.getInputStream();
        if (is == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        FileDescriptor fd = getFileDescriptor(request, response);
        if (fd == null)
            return;

        try {
            uploadToMiddleware(userSession, is, fd);
            saveFileDescriptor(fd);

            response.setStatus(HttpServletResponse.SC_OK);
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
            writer.write(fd.getId().toString());
            writer.close();

        } catch (FileStorageException e) {
            log.error("Unable to upload file", e);
            response.sendError(e.getType().getHttpStatus());
        } finally {
            IOUtils.closeQuietly(is);
        }
    } finally {
        AppContext.setSecurityContext(null);
    }
}

From source file:org.fejoa.server.Portal.java

@Override
public void handle(String s, Request request, HttpServletRequest httpServletRequest,
        HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("text/plain;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    request.setHandled(true);// w  w w . j  a v  a  2  s .  co  m

    final MultipartConfigElement MULTI_PART_CONFIG = new MultipartConfigElement(
            System.getProperty("java.io.tmpdir"));
    if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")) {
        request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
    }

    Session session = new Session(baseDir, httpServletRequest.getSession());
    ResponseHandler responseHandler = new ResponseHandler(response);

    Part messagePart = request.getPart(HTMLRequest.MESSAGE_KEY);
    Part data = request.getPart(HTMLRequest.DATA_KEY);

    if (messagePart == null) {
        responseHandler.setResponseHeader("empty request!");
        responseHandler.finish();
        return;
    }

    StringWriter stringWriter = new StringWriter();
    StreamHelper.copy(messagePart.getInputStream(), stringWriter);

    String error = handleJson(responseHandler, stringWriter.toString(),
            (data != null) ? data.getInputStream() : null, session);

    if (!responseHandler.isHandled() || error != null)
        responseHandler.setResponseHeader(error);

    responseHandler.finish();
}