List of usage examples for javax.servlet.http HttpServletResponse SC_CREATED
int SC_CREATED
To view the source code for javax.servlet.http HttpServletResponse SC_CREATED.
Click Source Link
From source file:org.openo.auth.common.CommonMockUp.java
public void mockUserClientException() { new MockUp<UserServiceClient>() { @Mock//from ww w .j a va 2s . co m public ClientResponse createUser(String json, String authToken) { ClientResponse resp = new ClientResponse(); resp.setStatus(HttpServletResponse.SC_CREATED); resp.setBody("body"); resp.setHeader("header"); return resp; } @Mock public int assignRolesToUser(String authToken, String projectId, String userId, String roleId) { return HttpServletResponse.SC_OK; } @Mock public ClientResponse modifyUser(String userId, String json, String authToken) { ClientResponse resp = new ClientResponse(); resp.setStatus(HttpServletResponse.SC_OK); resp.setBody("body"); resp.setHeader("header"); return resp; } @Mock public int deleteUser(String userId, String authToken) { return HttpServletResponse.SC_BAD_REQUEST; } @Mock public ClientResponse getUserDetails(String authToken) { ClientResponse resp = new ClientResponse(); resp.setStatus(HttpServletResponse.SC_OK); resp.setBody("body"); resp.setHeader("header"); return resp; } @Mock public ClientResponse getUserDetails(String userId, String authToken) { ClientResponse resp = new ClientResponse(); resp.setStatus(HttpServletResponse.SC_OK); resp.setBody("body"); resp.setHeader("header"); return resp; } @Mock public int modifyPassword(String userId, String json, String authToken) { return HttpServletResponse.SC_OK; } }; }
From source file:org.apache.archiva.webdav.RepositoryServletSecurityTest.java
@Test public void testPutWithInvalidUserAndGuestHasWriteAccess() throws Exception { servlet.setDavSessionProvider(davSessionProvider); ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet .getResourceFactory();// www .j av a 2 s . com archivaDavResourceFactory.setHttpAuth(httpAuth); archivaDavResourceFactory.setServletAuth(servletAuth); 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))) .andThrow(new AuthenticationException("Authentication error")); EasyMock.expect( servletAuth.isAuthorized("guest", "internal", ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD)) .andReturn(true); // ArchivaDavResourceFactory#isAuthorized() SecuritySession session = new DefaultSecuritySession(); EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class))).andReturn(result); EasyMock.expect(httpAuth.getSecuritySession(anyObject(HttpSession.class))).andReturn(session); EasyMock.expect(servletAuth.isAuthenticated(anyObject(HttpServletRequest.class), eq(result))) .andThrow(new AuthenticationException("Authentication error")); EasyMock.expect(httpAuth.getSessionUser(anyObject(HttpSession.class))).andReturn(null); // check if guest has write access EasyMock.expect( servletAuth.isAuthorized("guest", "internal", ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD)) .andReturn(true); httpAuthControl.replay(); servletAuthControl.replay(); InputStream is = getClass().getResourceAsStream("/artifact.jar"); assertNotNull("artifact.jar inputstream", is); MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); 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()); }
From source file:org.ednovo.gooru.controllers.v2.api.CollectionRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_SCOLLECTION_ITEM_ADD }) @RequestMapping(value = { "/{id}/item" }, method = RequestMethod.POST) public ModelAndView createCollectionItem(@PathVariable(value = ID) final String collectionId, @RequestBody final String data, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final User user = (User) request.getAttribute(Constants.USER); final JSONObject json = requestData(data); final ActionResponseDTO<CollectionItem> responseDTO = getCollectionService().createCollectionItem( getValue(RESOURCE_ID, json), collectionId, this.buildCollectionItemFromInputParameters(getValue(COLLECTION_ITEM, json)), user, CollectionType.COLLECTION.getCollectionType(), false); if (responseDTO.getErrors().getErrorCount() > 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else {//from w w w.j a v a2 s . com response.setStatus(HttpServletResponse.SC_CREATED); } String includes[] = (String[]) ArrayUtils.addAll(RESOURCE_INCLUDE_FIELDS, COLLECTION_INCLUDE_FIELDS); includes = (String[]) ArrayUtils.addAll(includes, COLLECTION_ITEM_INCLUDE_FILEDS); includes = (String[]) ArrayUtils.addAll(includes, ERROR_INCLUDE); return toModelAndViewWithIoFilter(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, includes); }
From source file:com.rmn.qa.servlet.AutomationTestRunServlet.java
/** * Attempts to register a new run request with the server. Returns a 201 if the request can be fulfilled but AMIs * must be started Returns a 202 if the request can be fulfilled Returns a 400 if the required parameters are not * passed in. Returns a 409 if the server is at full node capacity *//*from www . j a v a2 s .c o m*/ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); String browserRequested = request.getParameter("browser"); String browserVersion = request.getParameter("browserVersion"); String osRequested = request.getParameter("os"); String threadCount = request.getParameter("threadCount"); String uuid = request.getParameter(AutomationConstants.UUID); BrowserPlatformPair browserPlatformPairRequest; Platform requestedPlatform; // Return a 400 if any of the required parameters are not passed in // Check for uuid first as this is the most important variable if (uuid == null) { String msg = "Parameter 'uuid' must be passed in as a query string parameter"; log.error(msg); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } if (browserRequested == null) { String msg = "Parameter 'browser' must be passed in as a query string parameter"; log.error(msg); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } if (threadCount == null) { String msg = "Parameter 'threadCount' must be passed in as a query string parameter"; log.error(msg); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } if (StringUtils.isEmpty(osRequested)) { requestedPlatform = Platform.ANY; } else { requestedPlatform = AutomationUtils.getPlatformFromObject(osRequested); if (requestedPlatform == null) { String msg = "Parameter 'os' does not have a valid Selenium Platform equivalent: " + osRequested; log.error(msg); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } } Integer threadCountRequested = Integer.valueOf(threadCount); AutomationRunRequest runRequest = new AutomationRunRequest(uuid, threadCountRequested, browserRequested, browserVersion, requestedPlatform); browserPlatformPairRequest = new BrowserPlatformPair(browserRequested, requestedPlatform); log.info(String.format("Server request [%s] received.", runRequest)); boolean amisNeeded; int amiThreadsToStart = 0; int currentlyAvailableNodes; // Synchronize this block until we've added the run to our context for other potential threads to see synchronized (AutomationTestRunServlet.class) { int remainingNodesAvailable = AutomationContext.getContext().getTotalThreadsAvailable(getProxySet()); // If the number of nodes this grid hub can actually run is less than the number requested, this hub can not // fulfill this run at this time if (remainingNodesAvailable < runRequest.getThreadCount()) { log.error(String.format( "Requested node count of [%d] could not be fulfilled due to hub limit. [%d] nodes available - Request UUID [%s]", threadCountRequested, remainingNodesAvailable, uuid)); response.sendError(HttpServletResponse.SC_CONFLICT, "Server cannot fulfill request due to configured node limit being reached."); return; } // Get the number of matching, free nodes to determine if we need to start up AMIs or not currentlyAvailableNodes = requestMatcher.getNumFreeThreadsForParameters(getProxySet(), runRequest); // If the number of available nodes is less than the total number requested, we will have to spin up AMIs in // order to fulfill the request amisNeeded = currentlyAvailableNodes < threadCountRequested; if (amisNeeded) { // Get the difference which will be the number of additional nodes we need to spin up to supplement // existing nodes amiThreadsToStart = threadCountRequested - currentlyAvailableNodes; } // If the browser requested is not supported by AMIs, we need to not unnecessarily spin up AMIs if (amisNeeded && !AutomationUtils.browserAndPlatformSupported(browserPlatformPairRequest)) { response.sendError(HttpServletResponse.SC_GONE, "Request cannot be fulfilled and browser and platform is not supported by AMIs"); return; } // Add the run to our context so we can track it AutomationRunRequest newRunRequest = new AutomationRunRequest(uuid, threadCountRequested, browserRequested, browserVersion, requestedPlatform); boolean addSuccessful = AutomationContext.getContext().addRun(newRunRequest); if (!addSuccessful) { log.warn(String.format("Test run already exists for the same UUID [%s]", uuid)); // response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Test run already exists with the same UUID."); response.setStatus(HttpServletResponse.SC_CREATED); return; } } if (amisNeeded) { // Start up AMIs as that will be required log.warn(String.format( "Insufficient nodes to fulfill request. New AMIs will be queued up. Requested [%s] - Available [%s] - Request UUID [%s]", threadCountRequested, currentlyAvailableNodes, uuid)); try { AutomationTestRunServlet.startNodes(ec2, uuid, amiThreadsToStart, browserRequested, requestedPlatform); } catch (NodesCouldNotBeStartedException e) { // Make sure and de-register the run if the AMI startup was not successful AutomationContext.getContext().deleteRun(uuid); String throwableMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); String msg = "Nodes could not be started: " + throwableMessage; response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } // Return a 201 to let the caller know AMIs will be started response.setStatus(HttpServletResponse.SC_CREATED); return; } else { // Otherwise just return a 202 letting the caller know the requested resources are available response.setStatus(HttpServletResponse.SC_ACCEPTED); return; } }
From source file:org.j2free.servlet.EntityAdminServlet.java
/** * * @param request/*from ww w . ja va2 s . c o m*/ * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Controller controller = Controller.get(); // Get the controller associated with the current thread; String uri = request.getRequestURI(); uri = uri.replaceFirst(".*?/(list|find|inspect|create|save|update|delete)", "$1"); // chop off the part before what we care about String path[] = uri.split("/"); log.debug(uri); log.debug("path.length = " + path.length); if (path.length < 1) { log.debug("too little path info " + uri); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } RequestDispatcher rd = null; if (path[0].equals("list")) { log.debug("in list"); if (path.length < 2) { log.debug("too few parts for list"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); int start = ServletUtils.getIntParameter(request, "start", 0); int limit = ServletUtils.getIntParameter(request, "limit", 100); List entities; if (path.length == 3) { String[] stringIds = path[2].split(","); Object[] ignoredIds = new Object[stringIds.length]; Class idType = marshaller.getIdType(); // NOTE: this will only work with integer entityIds if (idType == Integer.class) { for (int i = 0; i < stringIds.length; i++) ignoredIds[i] = Integer.parseInt(stringIds[i]); } else if (idType == String.class) { for (int i = 0; i < stringIds.length; i++) ignoredIds[i] = stringIds[i]; } else if (idType == Long.class) { for (int i = 0; i < stringIds.length; i++) ignoredIds[i] = Long.parseLong(stringIds[i]); } entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName()), Restrictions.not(Restrictions.in(marshaller.getIdName(), ignoredIds))); } else entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName())); TreeMap<String, Object> entityMap = new TreeMap<String, Object>(); for (Object obj : entities) { entityMap.put(marshaller.extractId(obj).toString(), obj); } request.setAttribute("start", start); request.setAttribute("limit", limit); request.setAttribute("total", controller.count(klass)); request.setAttribute("simpleName", klass.getSimpleName()); request.setAttribute("package", klass.getPackage().getName() + "."); request.setAttribute("entities", entityMap); if (ServletUtils.getBooleanParameter(request, "selector", false)) rd = request.getRequestDispatcher(Dispatch.ENTITY_SELECTOR); else rd = request.getRequestDispatcher(Dispatch.ENTITY_LIST); } catch (Exception e) { log.error("Error listing entities", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("find") || path[0].equals("inspect")) { log.debug("in find"); if (path.length < 3) { log.debug("too few parts for find"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2])); request.setAttribute("entity", entity); request.setAttribute("entityId", marshaller.extractId(entity)); request.setAttribute("fields", marshaller.marshallOut(entity, true)); if (path[0].equals("find")) rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT); else rd = request.getRequestDispatcher(Dispatch.ENTITY_INSPECT); } catch (Exception e) { log.error("error finding entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("create")) { log.debug("in create"); if (path.length < 2) { log.debug("too few parts for create"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Constructor zeroArgsConst = klass.getConstructor(); if (!zeroArgsConst.isAccessible()) zeroArgsConst.setAccessible(true); Object entity = zeroArgsConst.newInstance(); request.setAttribute("simpleName", klass.getSimpleName()); request.setAttribute("package", klass.getPackage().getName() + "."); request.setAttribute("fields", marshaller.marshallOut(entity, true)); rd = request.getRequestDispatcher(Dispatch.ENTITY_CREATE); } catch (Exception e) { log.error("error creating entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("save")) { log.debug("in save"); if (path.length < 2) { log.debug("too few parts for save"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } Marshaller marshaller = null; try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } marshaller = ReflectionMarshaller.getForClass(klass); Object entity = klass.newInstance(); entity = marshaller.marshallIn(entity, request.getParameterMap(), controller); controller.persist(entity, true); if (controller.hasErrors()) { response.getWriter().println(controller.getErrorsAsString("<br />", true)); return; } else { response.setStatus(HttpServletResponse.SC_CREATED); // need this to display dates in the DB stored format entity = controller.findPrimaryKey(klass, marshaller.extractId(entity)); request.setAttribute("entity", entity); request.setAttribute("entityId", marshaller.extractId(entity)); request.setAttribute("fields", marshaller.marshallOut(entity, true)); rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT); } } catch (MarshallingException e) { log.error("error saving entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().println(e.getMessage()); return; } catch (Exception e) { log.error("error saving entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("update")) { log.debug("in update"); if (path.length < 3) { log.debug("too few parts for update"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2])); entity = marshaller.marshallIn(entity, request.getParameterMap(), controller); controller.merge(entity); if (controller.hasErrors()) { response.getWriter().println(controller.getErrorsAsString("<br />", true)); return; } else { response.setStatus(HttpServletResponse.SC_CREATED); // need this to display dates in the DB stored format entity = controller.findPrimaryKey(klass, marshaller.extractId(entity)); request.setAttribute("entity", entity); request.setAttribute("entityId", marshaller.extractId(entity)); request.setAttribute("fields", marshaller.marshallOut(entity, true)); rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT); } } catch (MarshallingException e) { log.error("error saving entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().println(e.getMessage()); return; } catch (Exception e) { log.error("error updating entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else if (path[0].equals("delete")) { log.debug("in delete"); if (path.length < 3) { log.debug("too few parts for delete"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } try { Class klass = entityLookup.get(path[1]); if (klass == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().println("Could not find class for entity type: " + path[1]); return; } Marshaller marshaller = ReflectionMarshaller.getForClass(klass); Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2])); controller.remove(entity); entity = null; controller.flush(); if (controller.hasErrors()) { response.getWriter().println(controller.getErrorsAsString("<br />", true)); return; } else { response.setStatus(HttpServletResponse.SC_CREATED); return; } } catch (Exception e) { log.error("error updating entity", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else { log.debug("Don't know what to do!"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } CharArrayWrapper responseWrapper = new CharArrayWrapper((HttpServletResponse) response); rd.forward(request, responseWrapper); String responseString = responseWrapper.toString().replaceAll("\n", " ").replaceAll("\\s{2,}", " ") .replaceAll("> ", ">").replaceAll(" <", "<").replaceAll(" />", "/>"); response.setContentLength(responseString.length()); response.setContentType("text/javascript"); PrintWriter out = response.getWriter(); out.write(responseString); out.flush(); out.close(); }
From source file:org.sakaiproject.nakamura.files.pool.ContentPoolCommentServlet.java
@Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String user = request.getRemoteUser(); String body = request.getParameter(COMMENT); int statusCode; // stop now if user is not logged in if ("anonymous".equals(user)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Must be logged in to post a comment."); return;/*from ww w.j a va 2 s . co m*/ } Resource resource = request.getResource(); Session adminSession = null; try { adminSession = repository.loginAdministrative(); ContentManager contentManager = adminSession.getContentManager(); AuthorizableManager authorizableManager = adminSession.getAuthorizableManager(); User currentUser = (User) authorizableManager.findAuthorizable(user); Content poolContent = resource.adaptTo(Content.class); String path = poolContent.getPath() + "/" + COMMENTS; Content comments = contentManager.get(path); if (comments == null) { comments = new Content(path, new HashMap<String, Object>()); contentManager.update(comments); } String commentId = request.getParameter("commentId"); if (commentId != null) { // we're going to edit an existing comment Content existingComment = contentManager.get(commentId); if (existingComment == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Attempting to update non-existent content: " + commentId); return; } if (!isManager(poolContent, currentUser, authorizableManager) && !currentUser.getId().equals(existingComment.getProperty("author"))) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Must be a manager of the pooled content item or author of the comment to edit a comment."); return; } path = commentId; statusCode = HttpServletResponse.SC_OK; } else { // stop now if no comment provided if (StringUtils.isBlank(body)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "'comment' must be provided."); return; } // have the node name be the current time in milliseconds since the epoch Calendar cal = Calendar.getInstance(); String newNodeName = Long.toString(cal.getTimeInMillis()); path = path + "/" + newNodeName; statusCode = HttpServletResponse.SC_CREATED; } ImmutableMap.Builder<String, Object> commentPropertiesBuilder = ImmutableMap.builder(); commentPropertiesBuilder.put(AUTHOR, user); // KERN-1536 allow arbitrary properties to be stored on a comment for (String parameterName : request.getRequestParameterMap().keySet()) { // commentId is not meant to be stored if ("commentId".equals(parameterName)) { continue; } String[] parameterValues = request.getParameterValues(parameterName); if (parameterValues.length == 1) { commentPropertiesBuilder.put(parameterName, parameterValues[0]); } else { commentPropertiesBuilder.put(parameterName, parameterValues); } } Content comment = new Content(path, commentPropertiesBuilder.build()); contentManager.update(comment); response.setStatus(statusCode); // return the comment id created for this comment response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); ExtendedJSONWriter w = new ExtendedJSONWriter(response.getWriter()); w.object(); w.key(COMMENT_ID); w.value(path); w.endObject(); } catch (JSONException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (ClientPoolException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (StorageClientException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } finally { try { if (adminSession != null) { adminSession.logout(); } } catch (ClientPoolException e) { LOGGER.warn(e.getMessage(), e); } } }
From source file:com.imaginary.home.cloud.api.RestApi.java
@Override public void doPost(@Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp) throws IOException { String requestId = request(req); try {/*from ww w . j a v a2 s. c o m*/ Map<String, Object> headers = parseHeaders(req); String[] path = getPath(req); if (path.length < 1) { throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION, "No POST is allowed against /"); } else if (path[0].equals("token")) { String token = generateToken("POST", req, headers); HashMap<String, Object> json = new HashMap<String, Object>(); json.put("token", token); resp.setStatus(HttpServletResponse.SC_CREATED); resp.getWriter().println((new JSONObject(json)).toString()); resp.getWriter().flush(); } else if (path[0].equals("relay")) { Map<String, Object> parameters = parseParameters(req); APICall call = apiCalls.get("relay"); call.post(requestId, null, path, req, resp, headers, parameters); } else if (path[0].equals("user")) { BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder source = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { source.append(line); source.append(" "); } String email = null, firstName = null, lastName = null, password = null; JSONObject object = new JSONObject(source.toString()); if (object.has("email") && !object.isNull("email")) { email = object.getString("email").toLowerCase(); } if (object.has("firstName") && !object.isNull("firstName")) { firstName = object.getString("firstName"); } if (object.has("lastName") && !object.isNull("lastName")) { lastName = object.getString("lastName"); } if (object.has("password") && !object.isNull("password")) { password = object.getString("password"); } if (email == null || firstName == null || lastName == null || password == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA, "Required fields: email, firstName, lastName, password"); } User user = User.create(email, firstName, lastName, password); ApiKey key = ApiKey.create(user, "default"); HashMap<String, Object> json = new HashMap<String, Object>(); json.put("email", email); json.put("firstName", firstName); json.put("lastName", lastName); json.put("userId", user.getUserId()); HashMap<String, Object> k = new HashMap<String, Object>(); k.put("apiKeyId", key.getApiKeyId()); k.put("apiKeySecret", Configuration.decrypt(user.getUserId(), key.getApiKeySecret())); k.put("userId", user.getUserId()); json.put("apiKeys", k); resp.setStatus(HttpServletResponse.SC_CREATED); resp.getWriter().println((new JSONObject(json)).toString()); resp.getWriter().flush(); } else if (apiCalls.containsKey(path[0])) { Map<String, Object> parameters = parseParameters(req); APICall call = apiCalls.get(path[0]); String userId = authenticate("POST", req, headers); call.post(requestId, userId, path, req, resp, headers, parameters); } else { throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_RESOURCE, "No " + path[0] + " resource exists in this API"); } } catch (RestException e) { HashMap<String, Object> error = new HashMap<String, Object>(); error.put("code", e.getStatus()); error.put("message", e.getMessage()); error.put("description", e.getDescription()); resp.setStatus(e.getStatus()); resp.getWriter().println((new JSONObject(error)).toString()); resp.getWriter().flush(); } catch (Throwable t) { t.printStackTrace(); HashMap<String, Object> error = new HashMap<String, Object>(); error.put("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); error.put("message", RestException.INTERNAL_ERROR); error.put("description", t.getMessage()); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().println((new JSONObject(error)).toString()); resp.getWriter().flush(); } }
From source file:org.opendatakit.aggregate.servlet.FormUploadServlet.java
/** * Handler for HTTP Post request that takes an xform, parses, and saves a * parsed version in the datastore//w w w.j a v a2 s . c om * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { CallingContext cc = ContextFactory.getCallingContext(this, req); Double openRosaVersion = getOpenRosaVersion(req); // verify request is multipart if (!ServletFileUpload.isMultipartContent(req)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.NO_MULTI_PART_CONTENT); return; } StringBuilder warnings = new StringBuilder(); // TODO Add in form title process so it will update the changes in the XML // of form try { // process form MultiPartFormData uploadedFormItems = new MultiPartFormData(req); FormParserForJavaRosa parser = null; MultiPartFormItem formNameData = uploadedFormItems.getFormDataByFieldName(ServletConsts.FORM_NAME_PRAM); MultiPartFormItem formXmlData = uploadedFormItems.getFormDataByFieldName(ServletConsts.FORM_DEF_PRAM); String formName = null; String inputXml = null; String xmlFileName = "default.xml"; if (formNameData != null) { formName = formNameData.getStream().toString(HtmlConsts.UTF8_ENCODE); } if (formXmlData != null) { // TODO: changed added output stream writer. probably something better // exists inputXml = formXmlData.getStream().toString(HtmlConsts.UTF8_ENCODE); xmlFileName = formXmlData.getFilename(); } try { parser = new FormParserForJavaRosa(formName, formXmlData, inputXml, xmlFileName, uploadedFormItems, warnings, cc); logger.info("Upload form successful: " + parser.getFormId()); // GAE requires some settle time before these entries will be // accurately retrieved. Do not re-fetch the form after it has been // uploaded. resp.setStatus(HttpServletResponse.SC_CREATED); resp.setHeader("Location", cc.getServerURL() + BasicConsts.FORWARDSLASH + ADDR); if (openRosaVersion == null) { // web page -- show HTML response resp.setContentType(HtmlConsts.RESP_TYPE_HTML); resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE); PrintWriter out = resp.getWriter(); out.write(HtmlConsts.HTML_OPEN); out.write(HtmlConsts.BODY_OPEN); if (warnings.length() != 0) { out.write("<p>Form uploaded with warnings. There are value fields in the form that do not " + "have <code><bind/></code> declarations or those <code><bind/></code> " + "declarations do not have a <code>type</code> attribute that " + "identifies the data type of that field (e.g., boolean, int, decimal, date, dateTime, time, string, " + "select1, select, barcode, geopoint or binary).</p>" + "<p><b>All these value fields have been declared as string values.</b> It will use " + "lexical ordering on those fields. E.g., the value 100 will be considered less than 11.</p>" + "<p><font color=\"red\">If these value fields hold date, dateTime, time or numeric data (e.g., decimal or int), then " + "ODK Aggregate will produce erroneous sortings and erroneous filtering results against those value fields.</font></p>" + "<table><th><td>Field Name</td></th>"); out.write(warnings.toString()); out.write("</table>"); } else { out.write("<p>Successful form upload.</p>"); } out.write("<p>Click "); out.write(HtmlUtil.createHref(cc.getWebApplicationURL(ADDR), "here", false)); out.write(" to return to add new form page.</p>"); out.write(HtmlConsts.BODY_CLOSE); out.write(HtmlConsts.HTML_CLOSE); } else { addOpenRosaHeaders(resp); resp.setContentType(HtmlConsts.RESP_TYPE_XML); resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE); PrintWriter out = resp.getWriter(); out.write("<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">"); if (warnings.length() != 0) { StringBuilder b = new StringBuilder(); b.append("<p>Form uploaded with warnings. There are value fields in the form that do not " + "have <code><bind/></code> declarations or those <code><bind/></code> " + "declarations do not have a <code>type</code> attribute that " + "identifies the data type of that field (e.g., boolean, int, decimal, date, dateTime, time, string, " + "select1, select, barcode, geopoint or binary).</p>" + "<p><b>All these value fields have been declared as string values.</b> It will use " + "lexical ordering on those fields. E.g., the value 100 will be considered less than 11.</p>" + "<p><font color=\"red\">If these value fields hold date, dateTime, time or numeric data (e.g., decimal or int), then " + "ODK Aggregate will produce erroneous sortings and erroneous filtering results against those value fields.</font></p>" + "<table><th><td>Field Name</td></th>"); b.append(warnings.toString()); b.append("</table>"); out.write("<message>"); out.write(StringEscapeUtils.escapeXml10(b.toString())); out.write("</message>"); } else { out.write("<message>Successful upload.</message>"); } out.write("</OpenRosaResponse>"); } } catch (ODKFormAlreadyExistsException e) { logger.info("Form already exists: " + e.toString()); resp.sendError(HttpServletResponse.SC_CONFLICT, ErrorConsts.FORM_WITH_ODKID_EXISTS + "\n" + e.toString()); } catch (ODKIncompleteSubmissionData e) { logger.warn("Form upload parsing error: " + e.toString()); switch (e.getReason()) { case TITLE_MISSING: createTitleQuestionWebpage(resp, inputXml, xmlFileName, cc); return; case ID_MALFORMED: resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.JAVA_ROSA_PARSING_PROBLEM + "\n" + e.toString()); return; case ID_MISSING: resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.MISSING_FORM_ID); return; case MISSING_XML: resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.MISSING_FORM_INFO); return; case BAD_JR_PARSE: resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.JAVA_ROSA_PARSING_PROBLEM + "\n" + e.toString()); return; case MISMATCHED_SUBMISSION_ELEMENT: resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.FORM_INVALID_SUBMISSION_ELEMENT); return; default: resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.INVALID_PARAMS); return; } } catch (ODKEntityPersistException e) { // TODO NEED TO FIGURE OUT PROPER ACTION FOR ERROR logger.error("Form upload persistence error: " + e.toString()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString()); } catch (ODKDatastoreException e) { logger.error("Form upload persistence error: " + e.toString()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString()); } catch (ODKParseException e) { // unfortunately, the underlying javarosa utility swallows the parsing // error. logger.error("Form upload persistence error: " + e.toString()); e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.PARSING_PROBLEM + "\n" + e.toString()); } } catch (FileUploadException e) { logger.error("Form upload persistence error: " + e.toString()); e.printStackTrace(resp.getWriter()); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.UPLOAD_PROBLEM); } }
From source file:com.imaginary.home.cloud.CloudTest.java
private void setupRelay() throws Exception { if (pairingCode == null) { setupPairing();//from w ww .j ava 2s.c o m } HashMap<String, Object> map = new HashMap<String, Object>(); long key = (System.currentTimeMillis() % 100000); map.put("pairingCode", pairingCode); map.put("name", "Test Controller " + key); HttpClient client = getClient(); HttpPost method = new HttpPost(cloudAPI + "/relay"); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(map)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject keys = new JSONObject(json); relayKeyId = (keys.has("apiKeyId") && !keys.isNull("apiKeyId")) ? keys.getString("apiKeyId") : null; relayKeySecret = (keys.has("apiKeySecret") && !keys.isNull("apiKeySecret")) ? keys.getString("apiKeySecret") : null; pairingCode = null; } else { Assert.fail("Failed to setup pairing for relay keys (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:com.couchbase.capi.servlet.CAPIServlet.java
protected void handleEnsureFullCommit(HttpServletRequest req, HttpServletResponse resp, String database) throws ServletException, IOException { if (!req.getMethod().equals("POST")) { throw new UnsupportedOperationException("_ensure_full_commit must be POST"); }//from w w w. j a v a 2s. com logger.trace("Got ensure full commitf request for " + database); resp.setStatus(HttpServletResponse.SC_CREATED); resp.setContentType("application/json"); if (capiBehavior.ensureFullCommit(database)) { Map<String, Object> responseMap = new HashMap<String, Object>(); responseMap.put("ok", true); OutputStream os = resp.getOutputStream(); mapper.writeValue(os, responseMap); } else { sendNotFoundResponse(resp, "missing"); } }