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.telefonica.iot.perseo.RulesManager.java

/**
 * Make a new rule from a JSON representation of an object with a name field
 * and a text field/*from   w w w. j  a  v a 2 s.  co  m*/
 *
 * @param epService Esper provider containing rules
 * @param text JSON text of the rule
 *
 * @return Result object with a code and a JSON response
 */
public static synchronized Result make(EPServiceProvider epService, String text) {
    try {

        logger.debug("rule text: " + text);
        org.json.JSONObject jo = new JSONObject(text);

        logger.debug("rule as JSONObject: " + jo);
        String name = jo.optString("name", "");
        logger.info("post rule: " + name);
        if ("".equals(name.trim())) {
            return new Result(HttpServletResponse.SC_BAD_REQUEST, "{\"error\":\"missing name\"}");
        }
        String newEpl = jo.optString("text", "");
        if ("".equals(newEpl.trim())) {
            return new Result(HttpServletResponse.SC_BAD_REQUEST, "{\"error\":\"missing text\"}");
        }
        logger.debug("statement name: " + name);
        logger.debug("statement text: " + newEpl);

        EPStatement statement;
        EPStatement prevStmnt = epService.getEPAdministrator().getStatement(name);
        if (prevStmnt == null) {
            logger.debug("found new statement: " + name);

            statement = epService.getEPAdministrator().createEPL(newEpl, name);
            logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
            statement.addListener(new GenericListener());
        } else {
            String oldEpl = prevStmnt.getText();
            logger.debug("old epl: " + oldEpl);
            if (!newEpl.equals(oldEpl)) {
                logger.debug("found changed statement: " + name);
                prevStmnt.destroy();
                logger.debug("deleted statement: " + name);
                statement = epService.getEPAdministrator().createEPL(newEpl, name);
                logger.debug("re-created statement: " + name);
                logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
                statement.addListener(new GenericListener());
            } else {
                logger.debug("found repeated statement: " + name);
                statement = prevStmnt;
            }
        }
        return new Result(HttpServletResponse.SC_OK, Utils.Statement2JSONObject(statement).toString());
    } catch (EPException epe) {
        logger.error("creating statement " + epe);
        return new Result(HttpServletResponse.SC_BAD_REQUEST,
                String.format("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage())));
    } catch (JSONException je) {
        logger.error("creating statement " + je);
        return new Result(HttpServletResponse.SC_BAD_REQUEST,
                String.format("{\"error\":%s}\n", JSONObject.valueToString(je.getMessage())));
    }
}

From source file:com.tasktop.c2c.server.common.service.tests.ajp.AjpProtocolTest.java

@Test
public void testGetLargePayload() throws IOException {
    int resonseDataSize = (Packet.MAX_SIZE * 3) + 243;
    byte[] responseData = createData(resonseDataSize);
    Payload payload = new Payload(HttpServletResponse.SC_OK, responseData);
    payload.getResponseHeaders().put("foo", "bar");
    TestServlet.setResponsePayload(payload);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/testGetLargePayload");

    MockHttpServletResponse response = new MockHttpServletResponse();
    protocol.forward(request, response);

    assertRequestIsExpected(request, TestServlet.getLastRequest());
    assertResponseIsExpected(payload, response);
}

From source file:org.alfresco.services.TextRepoContentGetter.java

public GetTextContentResponse getTextContent(Long nodeId, QName propertyQName, Long modifiedSince)
        throws AuthenticationException, IOException, org.alfresco.httpclient.AuthenticationException {
    StringBuilder url = new StringBuilder(128);
    url.append(GET_CONTENT);/*from ww  w.j  a  va2 s. c  o m*/

    StringBuilder args = new StringBuilder(128);
    if (nodeId != null) {
        args.append("?");
        args.append("nodeId");
        args.append("=");
        args.append(nodeId);
    } else {
        throw new NullPointerException("getTextContent(): nodeId cannot be null.");
    }
    if (propertyQName != null) {
        if (args.length() == 0) {
            args.append("?");
        } else {
            args.append("&");
        }
        args.append("propertyQName");
        args.append("=");
        args.append(URLEncoder.encode(propertyQName.toString()));
    }

    url.append(args);

    GetRequest req = new GetRequest(url.toString());

    if (modifiedSince != null) {
        Map<String, String> headers = new HashMap<String, String>(1, 1.0f);
        headers.put("If-Modified-Since", String.valueOf(DateUtil.formatDate(new Date(modifiedSince))));
        req.setHeaders(headers);
    }

    Response response = repoClient.sendRequest(req);

    if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED
            && response.getStatus() != HttpServletResponse.SC_NO_CONTENT
            && response.getStatus() != HttpServletResponse.SC_OK) {
        throw new AlfrescoRuntimeException("GetTextContentResponse return status is " + response.getStatus());
    }

    return new GetTextContentResponse(response);
}

From source file:eu.roschi.obdkinesis.webserver.GetCountsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    MultiMap<String> params = new MultiMap<>();
    UrlEncoded.decodeTo(req.getQueryString(), params, "UTF-8");

    // We need both parameters to properly query for counts
    if (!params.containsKey(PARAMETER_RESOURCE) || !params.containsKey(PARAMETER_RANGE_IN_SECONDS)) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*ww  w .ja  va 2  s .c om*/
    }

    // Parse query string as a single integer - the number of seconds since "now" to query for new counts
    String resource = params.getString(PARAMETER_RESOURCE);
    int rangeInSeconds = Integer.parseInt(params.getString(PARAMETER_RANGE_IN_SECONDS));

    Calendar c = Calendar.getInstance();
    c.add(Calendar.SECOND, -1 * rangeInSeconds);
    Date startTime = c.getTime();
    //if (LOG.isDebugEnabled()) {
    LOG.debug(String.format("Querying for counts of resource %s since %s", resource,
            DATE_FORMATTER.get().format(startTime)));
    //}

    DynamoDBQueryExpression<HttpReferrerPairsCount> query = new DynamoDBQueryExpression<>();
    HttpReferrerPairsCount hashKey = new HttpReferrerPairsCount();
    hashKey.setResource(resource);
    query.setHashKeyValues(hashKey);

    Condition recentUpdates = new Condition().withComparisonOperator(ComparisonOperator.GT)
            .withAttributeValueList(new AttributeValue().withS(DATE_FORMATTER.get().format(startTime)));
    query.setRangeKeyConditions(Collections.singletonMap("timestamp", recentUpdates));

    List<HttpReferrerPairsCount> counts = mapper.query(HttpReferrerPairsCount.class, query);

    // Return the counts as JSON
    resp.setContentType("application/json");
    resp.setStatus(HttpServletResponse.SC_OK);
    JSON.writeValue(resp.getWriter(), counts);
}

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

@Test
public void test8OnStatus() {

    // Test to get a specific label
    JSONObject label = getRequestJSONObject("/house/labels/ch6?param=param");
    // Test label Ch1
    testLabelCh6Bis(label);/*from  w w w.  j a va 2 s  .  co  m*/

    label = getRequestJSONObject("/house/labels/label?id=ch7&param=param");
    // Test label Ch1
    testLabelCh7Bis(label);

    putRequestJSONObject("/house/labels/ch1?param=param", createJsonController17(),
            HttpServletResponse.SC_NOT_ACCEPTABLE); // Ch1 not existing!
    putRequestJSONObject("/house/labels/label?id=ch1&param=param", createJsonController17(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);

    postRequestJSONObject("/house/labels/ch7?param=param", createJsonLabelCh7(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);
    postRequestJSONObject("/house/labels/label?id=ch7&param=param", createJsonLabelCh7(),
            HttpServletResponse.SC_NOT_ACCEPTABLE);

    deleteRequestJSONObject("/house/labels/ch7?param=param", HttpServletResponse.SC_OK);
    deleteRequestJSONObject("/house/labels/label?id=ch7&param=param", HttpServletResponse.SC_NOT_ACCEPTABLE);
}

From source file:org.bjason.oauth2.TokenResource.java

@POST
@Produces("application/json")
public Response authorize(@Context HttpServletRequest request) throws OAuthSystemException {
    try {/*from  ww  w .  java 2 s. c o m*/

        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);

        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

        if (Common.checkClientIdandSecret(oauthRequest) == false) {
            return Common.unauthorisedResponse();
        }

        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            TOKEN_STATE ts = checkAuthCode(oauthRequest.getParam(OAuth.OAUTH_CODE));
            if (ts == TOKEN_STATE.BAD) {
                return buildBadAuthCodeResponse("invalid authorization code");
            }
            if (ts == TOKEN_STATE.EXPIRED) {
                return buildBadAuthCodeResponse("expired authorization code");
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString())) {
            if (!checkUserPass(oauthRequest.getUsername(), oauthRequest.getPassword())) {
                return buildInvalidUserPassResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.toString())) {
            buildInvalidUserPassResponse();
        }

        final String accessToken = oauthIssuerImpl.accessToken();

        GenerictokenData authCodeFromUser = database.getTokenCode(oauthRequest.getParam(OAuth.OAUTH_CODE));
        GenerictokenData newAccessToken = new GenerictokenData(accessToken, Common.THIRTY_SECONDS);
        Set<String> requestedScopes = oauthRequest.getScopes();

        // check if we are limiting scope to access token
        if (requestedScopes != null && requestedScopes.size() > 0) {
            LinkedHashSet<String> permToGrant = new LinkedHashSet<String>();
            for (String what : requestedScopes) {
                if (authCodeFromUser.allowedTo(what) == false) {
                    return buildBadAuthCodeResponse("invalid scope");
                }
                permToGrant.add(what + "true");
            }

            newAccessToken.copyPermission(permToGrant);
        } else {
            newAccessToken.copyPermission(authCodeFromUser);
        }

        database.addAccessToken(newAccessToken);

        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessToken).setExpiresIn("" + newAccessToken.getExpires()).buildJSONMessage();
        return Response.status(response.getResponseStatus()).entity(response.getBody()).build();

    } catch (OAuthProblemException e) {
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();
        return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
    }
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

private void handleAuthnRequest(HttpServletRequest request, HttpServletResponse response,
        AuthnProcessorData data, SPEP spep) throws AuthenticationException {
    try {//from   w ww. j  av a2 s  .  co m
        String remoteAddress = request.getRemoteAddr();

        this.logger.info("[Authn for {}] Initiating HTTP POST binding. Creating AuthnRequest", remoteAddress);
        String document = buildAuthnRequestDocument(request.getParameter("redirectURL"), request, response,
                data, spep);
        PrintStream out = new PrintStream(response.getOutputStream());

        /* Set cookie to allow javascript enabled browsers to autosubmit, ensures navigation with the back button is not broken because auto submit is active for only a very short period */
        Cookie autoSubmit = new Cookie("spepAutoSubmit", "enabled");
        autoSubmit.setMaxAge(172800); //set expiry to be 48 hours just to make sure we still work with badly configured clocks skewed from GMT
        autoSubmit.setPath("/");
        response.addCookie(autoSubmit);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type", "text/html");

        out.print(document);

        out.close();

        this.logger.info("[Authn for {}] Sent AuthnRequest successfully", remoteAddress);
    } catch (IOException e) {
        throw new AuthenticationException("Unable to send response due to an I/O error.", e);
    }
}

From source file:gr.cti.android.experimentation.controller.PluginController.java

/**
 * Register a new plugin to the backend.
 *
 * @param response the HTTP response object.
 * @param plugin   the plugin object to register.
 *//*from  www .  j  a v a2  s  . co m*/
@ResponseBody
@RequestMapping(value = "/plugin", method = RequestMethod.POST, produces = "application/json")
public Object addPlugin(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute final Plugin plugin) throws IOException {
    LOGGER.info(request.getRemoteAddr());

    final ApiResponse apiResponse = new ApiResponse();
    final String contextType = plugin.getContextType();
    if (contextType == null || plugin.getName() == null || plugin.getImageUrl() == null
            || plugin.getFilename() == null || plugin.getInstallUrl() == null || plugin.getDescription() == null
            || plugin.getRuntimeFactoryClass() == null || plugin.getUserId() == null) {
        LOGGER.info("wrong data: " + plugin);
        String errorMessage = "error";
        if (contextType == null) {
            errorMessage = "contextType cannot be null";
        } else if (plugin.getName() == null) {
            errorMessage = "name cannot be null";
        } else if (plugin.getImageUrl() == null) {
            errorMessage = "imageUrl cannot be null";
        } else if (plugin.getFilename() == null) {
            errorMessage = "filename cannot be null";
        } else if (plugin.getInstallUrl() == null) {
            errorMessage = "url cannot be null";
        } else if (plugin.getDescription() == null) {
            errorMessage = "description cannot be null";
        } else if (plugin.getRuntimeFactoryClass() == null) {
            errorMessage = "runtimeFactoryClass cannot be null";
        } else if (plugin.getUserId() == null) {
            errorMessage = "userId cannot be null";
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage);
    } else {
        final Set<Plugin> existingPlugins = pluginRepository.findByContextType(contextType);
        if (existingPlugins.isEmpty()) {
            LOGGER.info("addPlugin: " + plugin);
            pluginRepository.save(plugin);
            apiResponse.setStatus(HttpServletResponse.SC_OK);
            apiResponse.setMessage("ok");
            apiResponse.setValue(plugin);
            return apiResponse;
        } else {
            LOGGER.info("plugin exists: " + plugin);
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "a plugin with this contextType already exists");
        }
    }
    return null;
}

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

/**
 * Tests the whether the original document is returned.
 * //from w ww . ja  v a  2s .  c  om
 * @param serverUrl
 *          the base url
 * @throws Exception
 *           if an exception occurs
 */
private void testGetDocument(String serverUrl) throws Exception {
    HttpClient httpClient = null;
    String url = UrlUtils.concat(serverUrl, path);
    HttpGet request = new HttpGet(url);
    request.setHeader("Accept-Language", "de");
    httpClient = new DefaultHttpClient();
    String eTagValue = null;
    Date modificationDate = null;
    try {
        logger.info("Requesting original document from {}", request.getURI());
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        assertTrue("No content received", response.getEntity().getContentLength() > 0);

        // Test general headers
        assertEquals(1, response.getHeaders("Content-Type").length);
        assertEquals(mimetypeGerman, response.getHeaders("Content-Type")[0].getValue());
        assertEquals(sizeGerman, response.getEntity().getContentLength());
        assertEquals(1, response.getHeaders("Content-Disposition").length);
        assertEquals("inline; filename=" + filenameGerman,
                response.getHeaders("Content-Disposition")[0].getValue());

        // Test ETag header
        Header eTagHeader = response.getFirstHeader("ETag");
        assertNotNull(eTagHeader);
        assertNotNull(eTagHeader.getValue());
        eTagValue = eTagHeader.getValue();

        // Test Last-Modified header
        Header modifiedHeader = response.getFirstHeader("Last-Modified");
        assertNotNull(modifiedHeader);
        modificationDate = lastModifiedDateFormat.parse(modifiedHeader.getValue());

        // Consume the content
        response.getEntity().consumeContent();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    TestSiteUtils.testETagHeader(request, eTagValue, logger, null);
    TestSiteUtils.testModifiedHeader(request, modificationDate, logger, null);
}

From source file:org.obm.push.spushnik.resources.FolderSyncScenarioTest.java

@Test
public void testFolderSyncScenarioWithNiceCertificate() throws Exception {
    HttpResponse httpResponse = folderSyncScenarioWithRequest(baseURL, "request_jaures_certificate_good.txt");

    InputStream content = httpResponse.getEntity().getContent();
    assertThat(httpResponse.getStatusLine().getStatusCode()).isEqualTo(HttpServletResponse.SC_OK);
    assertThat(IOUtils.toString(content, Charsets.UTF_8)).isEqualTo("{\"status\":0,\"messages\":[]}");
}