Example usage for javax.servlet.http HttpServletResponse SC_CREATED

List of usage examples for javax.servlet.http HttpServletResponse SC_CREATED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_CREATED.

Prototype

int SC_CREATED

To view the source code for javax.servlet.http HttpServletResponse SC_CREATED.

Click Source Link

Document

Status code (201) indicating the request succeeded and created a new resource on the server.

Usage

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    // Normally we would look up the deployment descriptor
    if (!"42".equals(profile_id)) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*www  .  j  a v a  2 s.c  o  m*/
    }

    String key = "42";
    String secret = "zaphod";

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }

    System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
    // System.out.println("OBJ:"+providerProfile);
    if (providerProfile == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM);

    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    System.out.println("shared_secret=" + shared_secret);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = LTI2Util.validateServices(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = LTI2Util.validateCapabilities(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Pass the profile to the launch process
    PERSIST.put("profile", providerProfile.toString());

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.debug(jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}

From source file:org.apache.archiva.webdav.RepositoryServletSecurityTest.java

@Test
public void testPutWithValidUserWithWriteAccess() throws Exception {
    assertTrue(repoRootInternal.getRoot().exists());

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
    InputStream is = getClass().getResourceAsStream("/artifact.jar");
    assertNotNull("artifact.jar inputstream", is);

    servlet.setDavSessionProvider(davSessionProvider);

    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet
            .getResourceFactory();//w w  w  .j a va 2s . c  om
    archivaDavResourceFactory.setHttpAuth(httpAuth);
    archivaDavResourceFactory.setServletAuth(servletAuth);

    TestAuditListener listener = new TestAuditListener();
    archivaDavResourceFactory.addAuditListener(listener);
    servlet.setResourceFactory(archivaDavResourceFactory);

    AuthenticationResult result = new AuthenticationResult();

    EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class),
            anyObject(HttpServletResponse.class))).andReturn(result);

    EasyMock.expect(servletAuth.isAuthenticated(anyObject(HttpServletRequest.class),
            anyObject(AuthenticationResult.class))).andReturn(true);

    User user = new SimpleUser();
    user.setUsername("admin");

    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();

    EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class),
            anyObject(HttpServletResponse.class))).andReturn(result);

    EasyMock.expect(httpAuth.getSecuritySession(mockHttpServletRequest.getSession())).andReturn(session);

    EasyMock.expect(httpAuth.getSessionUser(mockHttpServletRequest.getSession())).andReturn(user);

    EasyMock.expect(servletAuth.isAuthenticated(anyObject(HttpServletRequest.class), eq(result)))
            .andReturn(true);

    EasyMock.expect(servletAuth.isAuthorized(anyObject(HttpServletRequest.class), eq(session), eq("internal"),
            eq(ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD))).andReturn(true);

    httpAuthControl.replay();
    servletAuthControl.replay();

    mockHttpServletRequest.addHeader("User-Agent", "foo");
    mockHttpServletRequest.setMethod("PUT");
    mockHttpServletRequest.setRequestURI("/repository/internal/path/to/artifact.jar");
    mockHttpServletRequest.setContent(IOUtils.toByteArray(is));
    mockHttpServletRequest.setContentType("application/octet-stream");

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    servlet.service(mockHttpServletRequest, mockHttpServletResponse);

    httpAuthControl.verify();
    servletAuthControl.verify();

    assertEquals(HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus());

    assertEquals("admin", listener.getEvents().get(0).getUserId());
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

/**
 * Publish message to Backplane.//from  ww  w  . j a v  a2  s .co  m
 * @param request
 * @param response
 * @return
 */
@RequestMapping(value = "/message", method = { RequestMethod.POST })
public @ResponseBody Map<String, Object> postMessages(HttpServletRequest request, HttpServletResponse response,
        @RequestBody Map<String, Map<String, Object>> messagePostBody,
        @RequestParam(value = OAUTH2_ACCESS_TOKEN_PARAM_NAME, required = false) String access_token,
        @RequestHeader(value = "Authorization", required = false) String authorizationHeader)
        throws SimpleDBException, BackplaneServerException {

    ServletUtil.checkSecure(request);

    final TimerContext context = v2PostTimer.time();

    try {
        Token token = Token.fromRequest(daoFactory, request, access_token, authorizationHeader);
        if (token.getType().isRefresh() || !token.getType().isPrivileged()) {
            throw new TokenException("Invalid token type: " + token.getType(),
                    HttpServletResponse.SC_FORBIDDEN);
        }

        BackplaneMessage message = parsePostedMessage(messagePostBody, token);
        daoFactory.getBackplaneMessageDAO().persist(message);

        aniLogNewMessage(request, message, token);

        response.setStatus(HttpServletResponse.SC_CREATED);
        return null;

    } catch (TokenException te) {
        return handleTokenException(te, response);
    } catch (InvalidRequestException ire) {
        throw ire;
    } catch (Exception e) {
        throw new BackplaneServerException("Error processing post request: " + e.getMessage(), e);
    } finally {
        context.stop();
    }
}

From source file:com.couchbase.capi.servlet.CAPIServlet.java

protected void handleBulkDocs(HttpServletRequest req, HttpServletResponse resp, String database)
        throws ServletException, IOException {

    if (!req.getMethod().equals("POST")) {
        throw new UnsupportedOperationException("_bulk_docs must be POST");
    }/* w w  w  . ja v  a 2s.  com*/

    logger.trace("Got bulk docs request for " + database);

    resp.setStatus(HttpServletResponse.SC_CREATED);
    resp.setContentType("application/json");

    OutputStream os = resp.getOutputStream();
    InputStream is = req.getInputStream();

    int requestLength = req.getContentLength();
    byte[] buffer = new byte[requestLength];
    IOUtils.readFully(is, buffer, 0, requestLength);

    @SuppressWarnings("unchecked")
    Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class);

    logger.trace("parsed value is " + parsedValue);

    try {
        List<Object> responseList = capiBehavior.bulkDocs(database,
                (ArrayList<Map<String, Object>>) parsedValue.get("docs"));
        if (responseList == null) {
            sendNotFoundResponse(resp, "missing");
            return;
        }
        mapper.writeValue(os, responseList);
    } catch (UnavailableException e) {
        sendServiceUnavailableResponse(resp, "too many concurrent requests");
    }
}

From source file:org.sakaiproject.lti2.LTI2Service.java

public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    Map<String, Object> deploy = ltiService.getDeployForConsumerKeyDao(profile_id);
    if (deploy == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;//from   ww  w. ja v a2  s.  c  om
    }
    Long deployKey = foorm.getLong(deploy.get(LTIService.LTI_ID));

    // See if we can even register...
    Long reg_state = foorm.getLong(deploy.get(LTIService.LTI_REG_STATE));
    String key = null;
    String secret = null;
    if (reg_state == 0) {
        key = (String) deploy.get(LTIService.LTI_REG_KEY);
        secret = (String) deploy.get(LTIService.LTI_REG_PASSWORD);
    } else {
        key = (String) deploy.get(LTIService.LTI_CONSUMERKEY);
        secret = (String) deploy.get(LTIService.LTI_SECRET);
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }
    // System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
    // System.out.println("OBJ:"+providerProfile);
    if (providerProfile == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM);

    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Blank out the new shared secret
    security_contract.put(LTI2Constants.SHARED_SECRET, "*********");

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = getToolConsumerProfile(deploy, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = LTI2Util.validateServices(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = LTI2Util.validateCapabilities(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Passed all the tests, lets commit this...
    Map<String, Object> deployUpdate = new TreeMap<String, Object>();
    shared_secret = SakaiBLTIUtil.encryptSecret(shared_secret);
    deployUpdate.put(LTIService.LTI_SECRET, shared_secret);

    // Indicate ready to validate and kill the interim info
    deployUpdate.put(LTIService.LTI_REG_STATE, LTIService.LTI_REG_STATE_REGISTERED);
    deployUpdate.put(LTIService.LTI_REG_KEY, "");
    deployUpdate.put(LTIService.LTI_REG_PASSWORD, "");
    if (default_custom != null)
        deployUpdate.put(LTIService.LTI_SETTINGS, default_custom.toString());
    deployUpdate.put(LTIService.LTI_REG_PROFILE, providerProfile.toString());

    M_log.debug("deployUpdate=" + deployUpdate);

    Object obj = ltiService.updateDeployDao(deployKey, deployUpdate);
    boolean success = (obj instanceof Boolean) && ((Boolean) obj == Boolean.TRUE);
    if (!success) {
        M_log.warn(
                "updateDeployDao fail deployKey=" + deployKey + "\nretval=" + obj + "\ndata=" + deployUpdate);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Failed update of deployment=" + deployKey, null);
        return;
    }

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    String serverUrl = ServerConfigurationService.getServerUrl();
    jsonResponse.put(LTI2Constants.JSONLD_ID, resourceUrl + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            resourceUrl + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.debug(jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

/**
 * Process a PUT request for the specified resource.
 *
 * Note: PUT method currently does not support Content-Range parameter.
 * It will throw a 501 error if Content-Range is present in the header,
 * as expected by RFC./*  w  ww. ja va2  s. c  om*/
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    AtmosApi api = getAPIFromAuthent(req, resp);
    ObjectPath obj_path = getAtmosPath(getPathFromReq(req), api);

    UploadHelper up_helper = new UploadHelper(api.api);
    up_helper.setMinReadSize(UploadHelper.DEFAULT_BUFFSIZE);

    // first test if object exists
    AtmosType obj_type = getObjectType(getObjectMetadata(api.api, obj_path));
    boolean partial = false;

    // RFC says we MUST reject request containing Content-Range if we don't support it
    if (req.getHeader("Content-Range") != null) {
        resp.sendError(resp.SC_NOT_IMPLEMENTED);
        return;
    }

    if (!partial) {
        if (obj_type == AtmosType.NON_EXISTENT) {
            up_helper.createObjectOnPath(obj_path, req.getInputStream(), null, null, false);
            resp.setStatus(HttpServletResponse.SC_CREATED);
        } else if (obj_type == AtmosType.REGULAR) {
            up_helper.updateObject(obj_path, req.getInputStream(), null, null, false);
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); // Cannot PUT on a directory
        }
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        //                    if (!exists)
        //                        api.createObjectOnPath(obj_path, null, null, null, null);
        //                    Extent extent = new Extent(range.start, range.length);
        //                    api.updateObject(obj_path, null, null, extent, content, null);
    }
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletMoveTest.java

public void testMoveNodeMultipleSourceReplace() throws Exception {
    final String testPath = TEST_BASE_PATH + "/mvmult/" + System.currentTimeMillis();
    final String testRoot = testClient.createNode(HTTP_BASE_URL + testPath, null);

    // create multiple source nodes
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src1", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src2", props);

    // move the src? nodes
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Move Failure: dest parent does not exist");

    // create destination parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", null);

    // now dest exists, so we expect success
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Move Success");

    // assert partial existence of the src?/text properties
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src1/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src2/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src3/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src4/text", HttpServletResponse.SC_NOT_FOUND);

    // assert content test
    String content = getContent(HTTP_BASE_URL + testPath + "/dest/src1.json", CONTENT_TYPE_JSON);
    JSONObject json = new JSONObject(content);
    assertEquals("Hello", json.get("text"));

    // modify src1 content
    nvPairs.clear();//from   w ww . ja  va  2  s  .c om
    nvPairs.add(new NameValuePair("text", "Modified Hello"));
    assertPostStatus(HTTP_BASE_URL + testPath + "/src1", HttpServletResponse.SC_CREATED, nvPairs,
            "Expect Content Create Success");

    // move the src? nodes
    nvPairs.clear();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Move Success");

    // assert content test
    String content2 = getContent(HTTP_BASE_URL + testPath + "/dest/src1.json", CONTENT_TYPE_JSON);
    JSONObject json2 = new JSONObject(content2);
    assertEquals("Modified Hello", json2.get("text"));

    // clean up
    testClient.delete(testRoot);
}

From source file:com.imaginary.home.device.hue.HueMethod.java

public JSONObject put(@Nonnull String resource, JSONObject body) throws HueException {
    Logger std = Hue.getLogger(HueMethod.class);
    Logger wire = Hue.getWireLogger(HueMethod.class);

    if (std.isTraceEnabled()) {
        std.trace("enter - " + HueMethod.class.getName() + ".put(" + resource + ")");
    }/*from w  w  w .j a  v  a2s .c  o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource);
    }
    try {
        HttpClient client = getClient();
        HttpPut method = new HttpPut(hue.getAPIEndpoint() + resource);

        method.addHeader("Content-Type", "application/json");

        try {
            if (body != null) {
                //noinspection deprecation
                method.setEntity(new StringEntity(body.toString(), "application/json", "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            throw new HueException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                try {
                    wire.debug(EntityUtils.toString(method.getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            }
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            std.error("PUT: 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("PUT: 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_NO_CONTENT) {
            return null;
        } else if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            std.error("PUT: Expected NO_CONTENT or CREATED or OK or ACCEPTED for PUT request, got "
                    + status.getStatusCode());

            HttpEntity entity = response.getEntity();

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

            try {
                json = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(json);
                wire.debug("");
            }
            throw new HueException(status.getStatusCode(), json);
        } else {
            try {
                String json = EntityUtils.toString(response.getEntity());

                if (wire.isDebugEnabled()) {
                    wire.debug(json);
                    wire.debug("");
                }
                if (json.startsWith("[")) {
                    JSONArray arr = new JSONArray(json);

                    if (arr.length() > 0) {
                        JSONObject ob = arr.getJSONObject(0);

                        if (ob.has("error")) {
                            ob = ob.getJSONObject("error");
                            if (ob.has("description")) {
                                throw new HueException(ob.getString("description"));
                            }
                        }
                        return ob;
                    }
                    return null;
                }
                return new JSONObject(json);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            } catch (JSONException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + HueMethod.class.getName() + ".put()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:org.imsglobal.lti2.LTI2Servlet.java

@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response,
        String profile_id) throws java.io.IOException {
    // Normally we would look up the deployment descriptor
    if (!TEST_KEY.equals(profile_id)) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;// w  ww . ja  v  a2  s. co  m
    }

    String key = TEST_KEY;
    String secret = TEST_SECRET;

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);

    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null);
        return;
    }

    System.out.println(jsonRequest.getPostBody());

    // Lets check the signature
    if (key == null || secret == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null);
        return;
    }

    jsonRequest.validateRequest(key, secret, request);
    if (!jsonRequest.valid) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null);
        return;
    }

    JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
    // System.out.println("OBJ:"+providerProfile);
    if (providerProfile == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON parse failed", null);
        return;
    }

    JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM);

    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    if (security_contract == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null);
        return;
    }

    String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);
    System.out.println("shared_secret=" + shared_secret);
    if (shared_secret == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null);
        return;
    }

    // Make sure that the requested services are a subset of the offered services
    ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id);

    JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE);
    String retval = LTI2Util.validateServices(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Parse the tool profile bit and extract the tools with error checking
    retval = LTI2Util.validateCapabilities(consumer, providerProfile);
    if (retval != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, retval, null);
        return;
    }

    // Pass the profile to the launch process
    PERSIST.put("profile", providerProfile.toString());

    // Share our happiness with the Tool Provider
    Map jsonResponse = new TreeMap();
    jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT);
    jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE);
    jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id);
    jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id);
    jsonResponse.put(LTI2Constants.CUSTOM_URL,
            getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id);
    response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT);
    response.setStatus(HttpServletResponse.SC_CREATED);
    String jsonText = JSONValue.toJSONString(jsonResponse);
    M_log.log(Level.FINE, jsonText);
    PrintWriter out = response.getWriter();
    out.println(jsonText);
}