List of usage examples for javax.servlet.http HttpServletResponse SC_ACCEPTED
int SC_ACCEPTED
To view the source code for javax.servlet.http HttpServletResponse SC_ACCEPTED.
Click Source Link
From source file:org.eclipse.orion.internal.server.servlets.xfer.SFTPTransfer.java
private void transferWithExceptions() throws ServletException, IOException, URISyntaxException, JSONException { String host, remotePath, user, passphrase; int port;//from w ww . j a v a 2 s. c o m try { JSONObject requestInfo = OrionServlet.readJSONRequest(request); host = requestInfo.getString(ProtocolConstants.KEY_HOST); remotePath = requestInfo.getString(ProtocolConstants.KEY_PATH); port = requestInfo.optInt(ProtocolConstants.KEY_PORT, 22); user = requestInfo.getString(ProtocolConstants.KEY_USER_NAME); passphrase = requestInfo.getString(ProtocolConstants.KEY_PASSPHRASE); } catch (Exception e) { handleException("Request body is not in the expected format", e, HttpServletResponse.SC_BAD_REQUEST); return; } File localFile; try { localFile = localRoot.toLocalFile(EFS.NONE, null); } catch (CoreException e) { handleException(NLS.bind("Import is not supported at this location: {0}", localRoot.toString()), e, HttpServletResponse.SC_NOT_IMPLEMENTED); return; } SFTPTransferJob job; if (TransferServlet.PREFIX_IMPORT.equals(new Path(request.getPathInfo()).segment(0))) { job = new SFTPImportJob(TaskJobHandler.getUserId(request), localFile, host, port, new Path(remotePath), user, passphrase, options); } else { job = new SFTPExportJob(TaskJobHandler.getUserId(request), localFile, host, port, new Path(remotePath), user, passphrase, options); } job.schedule(); TaskInfo task = job.getTask(); JSONObject result = task.toJSON(); //Not nice that the import service knows the location of the task servlet, but task service doesn't know this either URI requestLocation = ServletResourceHandler.getURI(request); URI taskLocation = new URI(requestLocation.getScheme(), requestLocation.getAuthority(), "/task/temp/" + task.getId(), null, null); //$NON-NLS-1$ result.put(ProtocolConstants.KEY_LOCATION, taskLocation); response.setHeader(ProtocolConstants.HEADER_LOCATION, ServletResourceHandler.resovleOrionURI(request, taskLocation).toString()); OrionServlet.writeJSONResponse(request, response, result); response.setStatus(HttpServletResponse.SC_ACCEPTED); }
From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2Ping.java
/** * Returns the OpenURLResponse of a JSON object defining image status. Status Codes: */// www .ja v a 2 s . c om @Override public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject, final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) { final String responseFormat = RESPONSE_TYPE; int status = HttpServletResponse.SC_NOT_FOUND; byte[] bytes = new byte[] {}; try { final String id = ((URI) contextObject.getReferent().getDescriptors()[0]).toASCIIString(); status = ReferentManager.getResolver().getStatus(id); if (status != HttpServletResponse.SC_NOT_FOUND) { final ObjectMapper mapper = new ObjectMapper(); final ObjectNode rootNode = mapper.createObjectNode(); String res_status = null; if (status == HttpServletResponse.SC_OK) { res_status = STATUS_OK; } else if (status == HttpServletResponse.SC_ACCEPTED) { res_status = STATUS_ACCEPTED; } rootNode.put("identifier", id); rootNode.put("status", res_status); bytes = mapper.writeValueAsBytes(rootNode); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } final HashMap<String, String> header_map = new HashMap<String, String>(); header_map.put("Content-Length", Integer.toString(bytes.length)); header_map.put("Date", HttpDate.getHttpDate()); return new OpenURLResponse(status, responseFormat, bytes, header_map); }
From source file:org.clothocad.phagebook.controllers.AutoCompleteController.java
@RequestMapping(value = "/autoCompleteProjects", method = RequestMethod.GET) protected void autoCompleteProjects(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { //I WILL RETURN THE MAP AS A JSON OBJECT.. it is client side's issue to parse all data for what they need! //they could check over there if the schema matches what they are querying for and so i can do this generically! //user should be logged in so I will log in as that user. String name = params.get("name") != null ? params.get("name") : ""; boolean isValid = false; System.out.println("Name is: " + name); if (!name.equals("")) { isValid = true;/*from w w w .ja v a 2 s.co m*/ } if (isValid) { ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); //TODO: we need to have an authentication token at some point String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap); Map query = new HashMap(); query.put("query", name); // the value for which we are querying. query.put("key", "name"); // the key of the object we are querying List<Project> projects = ClothoAdapter.queryProject(query, clothoObject, ClothoAdapter.QueryMode.STARTSWITH); org.json.JSONArray responseArray = new org.json.JSONArray(); for (Project proj : projects) { JSONObject obj = new JSONObject(); obj.put("id", proj.getId()); obj.put("name", proj.getName()); responseArray.put(obj); } response.setStatus(HttpServletResponse.SC_ACCEPTED); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(responseArray); out.flush(); out.close(); clothoObject.logout(); conn.closeConnection(); } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("application/json"); JSONObject reply = new JSONObject(); reply.put("message", "Auto Complete requires a query parameter"); PrintWriter out = response.getWriter(); out.print(reply); out.flush(); out.close(); }
From source file:org.appcelerator.transport.AjaxServiceTransportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //// ww w. j a v a 2 s. c om // make sure we check the integrity of the request before we continue // if (!validate(req, resp)) { LOG.warn("security validation failed for request=" + req + " from " + req.getRemoteAddr()); return; } String type = req.getContentType(); int idx = type.indexOf(';'); if (idx > 0) { type = type.substring(0, idx); } try { // decode the incoming request ArrayList<Message> requests = new ArrayList<Message>(1); ArrayList<Message> responses = new ArrayList<Message>(1); ServiceMarshaller.getMarshaller(type).decode(req.getInputStream(), requests); if (requests.isEmpty()) { // no incoming messages, just return accepted header resp.setHeader("Content-Length", "0"); resp.setContentType("text/plain;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_ACCEPTED); return; } HttpSession session = req.getSession(); InetAddress address = InetAddress.getByName(req.getRemoteAddr()); //String instanceid = req.getParameter("instanceid"); for (Message request : requests) { request.setUser(req.getUserPrincipal()); request.setSession(session); request.setAddress(address); request.setServletRequest(req); //FIXME => refactor this out if (request.getType().equals(MessageType.APPCELERATOR_STATUS_REPORT)) { IMessageDataObject data = (IMessageDataObject) request.getData(); data.put("remoteaddr", req.getRemoteAddr()); data.put("remotehost", req.getRemoteHost()); data.put("remoteuser", req.getRemoteUser()); } ServiceRegistry.dispatch(request, responses); } if (responses.isEmpty()) { // no response messages, just return accepted header resp.setHeader("Content-Length", "0"); resp.setContentType("text/plain;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_ACCEPTED); return; } // setup the response resp.setStatus(HttpServletResponse.SC_OK); resp.setHeader("Connection", "Keep-Alive"); resp.setHeader("Pragma", "no-cache"); resp.setHeader("Cache-control", "no-cache, no-store, private, must-revalidate"); resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // encode the responses ServletOutputStream output = resp.getOutputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(1000); String responseType = ServiceMarshaller.getMarshaller(type).encode(responses, req.getSession().getId(), bout); byte buf[] = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(buf); resp.setContentType(responseType); // do gzip encoding if browser supports it and if length > 1000 bytes String ae = req.getHeader("accept-encoding"); if (ae != null && ae.indexOf("gzip") != -1 && buf.length > 1000) { resp.setHeader("Content-Encoding", "gzip"); //a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to //clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent //to a client that will not understand it. resp.addHeader("Vary", "Accept-Encoding"); GZIPOutputStream gzip = new GZIPOutputStream(output, buf.length); Util.copy(bin, gzip); gzip.flush(); gzip.finish(); } else { resp.setContentLength(buf.length); Util.copy(bin, output); } output.flush(); } catch (Throwable e) { LOG.error("Error handling incoming POST request", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:ge.taxistgela.servlet.AdminServlet.java
private void toogleBan(SuperUserManager superUserManager, String sID, String password, HttpServletRequest request, HttpServletResponse response) { if (superUserManager == null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else {//from w w w. j ava 2 s . com Admin admin = (Admin) request.getSession().getAttribute(Admin.class.getName()); if (admin != null) { if (sID != null) { Integer id = null; try { id = Integer.parseInt(sID); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } SuperDaoUser superUser = superUserManager.getByID(id); if (superUser != null) { superUser.setPassword(password); ErrorCode errorCode = superUserManager.update(superUser); if (errorCode.errorNotAccrued()) { response.setStatus(HttpServletResponse.SC_ACCEPTED); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); } } }
From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java
@Test public void forwardShouldPostCorrectRequest() throws CloudException, InternalException { final AtomicInteger putCount = new AtomicInteger(0); new MockUp<CloseableHttpClient>() { @Mock(invocations = 2)// w w w. ja v a 2 s . c o m public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException { if (request.getMethod().equals("GET")) { DaseinObjectToXmlEntity<PersistentVMRoleModel> daseinEntity = new DaseinObjectToXmlEntity<PersistentVMRoleModel>( createPersistentVMRoleModelWithoutEndpoint()); assertGet(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") }); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else if (request.getMethod().equals("PUT")) { putCount.incrementAndGet(); PersistentVMRoleModel persistentVMRoleModel = createPersistentVMRoleModelWithEndpoint(); assertPut(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") }, persistentVMRoleModel); return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_ACCEPTED), null, new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) }); } else { throw new IOException("Request is not mocked"); } } }; String result = ipAddressSupport.forward("127.0.0.1", PUBLIC_PORT, PROTOCOL, PRIVATE_PORT, VM_ID); assertEquals("IpAddressSupport.forward() doesn't return correct result", new AzureRuleIdParts(VM_ID, Protocol.TCP.toString(), String.valueOf(PRIVATE_PORT)).toProviderId(), result); assertEquals("PUT count doesn't match", 1, putCount.get()); }
From source file:org.jahia.modules.userregistration.actions.NewUser.java
public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, final Resource resource, JCRSessionWrapper session, final Map<String, List<String>> parameters, URLResolver urlResolver) throws Exception { final String username = getParameter(parameters, "username"); final String password = getParameter(parameters, "password"); if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { return ActionResult.BAD_REQUEST; }//from w ww .j a va 2 s . co m final Properties properties = new Properties(); properties.put("j:email", parameters.get("desired_email").get(0)); properties.put("j:firstName", parameters.get("desired_firstname").get(0)); properties.put("j:lastName", parameters.get("desired_lastname").get(0)); for (Map.Entry<String, List<String>> param : parameters.entrySet()) { if (param.getKey().startsWith("j:")) { String value = getParameter(parameters, param.getKey()); if (value != null) { properties.put(param.getKey(), value); } } } JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Boolean>() { @Override public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException { final JCRUserNode user = userManagerService.createUser(username, password, properties, session); session.save(); if (mailService.isEnabled()) { // Prepare mail to be sent : boolean toAdministratorMail = Boolean .valueOf(getParameter(parameters, "toAdministrator", "false")); String to = toAdministratorMail ? mailService.getSettings().getTo() : getParameter(parameters, "to"); String from = parameters.get("from") == null ? mailService.getSettings().getFrom() : getParameter(parameters, "from"); String cc = parameters.get("cc") == null ? null : getParameter(parameters, "cc"); String bcc = parameters.get("bcc") == null ? null : getParameter(parameters, "bcc"); Map<String, Object> bindings = new HashMap<String, Object>(); bindings.put("newUser", user); try { mailService.sendMessageWithTemplate(templatePath, bindings, to, from, cc, bcc, resource.getLocale(), "Jahia User Registration"); } catch (ScriptException e) { logger.error("Error sending e-mail notification for user creation", e); } } return true; } }); return new ActionResult(HttpServletResponse.SC_ACCEPTED, parameters.get("userredirectpage").get(0), new JSONObject()); }
From source file:org.clothocad.phagebook.controllers.OrdersController.java
@RequestMapping(value = "/addProductsToOrder", method = RequestMethod.POST) protected void addProductsToOrder(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { /*Add products to an order... *ASSUMPTION 1: I receive a JSONArray with key value pairs <String, int> product id, and quantity *ASSUMPTION 2: Along with each object I get a "discount" : double key... * I take care of everything here /* w w w .j a v a 2 s . c om*/ *ASSUMPTION 3: I GET THE LOGGED IN PERSONS'S ID (if I need it) from the cookie *ASSUMPTION 4: I GET THE ORDER ID PASSED IN. */ Object pCartItems = params.get("CartItems"); String cartItems = pCartItems != null ? (String) pCartItems : ""; Object pUser = params.get("loggedInUserId"); String user = pUser != null ? (String) pUser : ""; Object pOrderId = params.get("orderId"); String orderId = pOrderId != null ? (String) pOrderId : ""; boolean isValid = false; if (!cartItems.equals("") && !user.equals("") && !orderId.equals("")) { isValid = true; } //should now have something like this parsed. /* [{"productId": "<ID>" , "quantity": "5", "discount": "100" }, {"productId": "<ID> ,.. etc"}]; */ if (isValid) { //NEED TO LOG INTO CLOTHO... better way TBA ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap); // //STEP 1, get the order we want to modify... //assuming valid order ID. Order editableOrder = ClothoAdapter.getOrder(orderId, clothoObject); //now we have the order object. JSONArray cartItemsJSONArray = new JSONArray(cartItems); //we have our JSONArray of products to add with discounts List<String> items = editableOrder.getProducts(); //initialize, we want to add not replace Date date = new Date(); for (int i = 0; i < cartItemsJSONArray.length(); i++) { //process the information that we have JSONObject obj = (JSONObject) cartItemsJSONArray.get(i); Product product = ClothoAdapter.getProduct(obj.getString("productId"), clothoObject); product.decreaseInventory(obj.getInt("quantity")); CartItem item = new CartItem(); item.setDateCreated(date); item.setProductId(obj.getString("productId")); item.setDiscount(obj.getDouble("discount")); item.setQuantity(obj.getInt("quantity")); ClothoAdapter.createCartItem(item, clothoObject); ClothoAdapter.setProduct(product, clothoObject); items.add(item.getId()); } //now have a CART ITEM OBJECT all with ID's editableOrder.setProducts(items); ClothoAdapter.setOrder(editableOrder, clothoObject); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_ACCEPTED); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "successfully modified order object"); PrintWriter out = response.getWriter(); out.print(responseJSON); out.flush(); conn.closeConnection(); } else { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "missing parameters for servlet call"); PrintWriter out = response.getWriter(); out.print(responseJSON); out.flush(); } }
From source file:org.opendatakit.aggregate.servlet.UserManagePasswordsServlet.java
/** * Returns an object possibly wrapped by a callback method name. The return is * of the form:/*w ww. j av a2 s .co m*/ * * <pre> * cccc ({ "username" : "nnnn", "status" : "oooo", "echo" : "ssss" }) * </pre> * * Where: * <ul> * <li>cccc = callback parameter value</li> * <li>nnnn = username parameter value</li> * <li>oooo = outcome of change password action</li> * <li>ssss = echo parameter value</li> * </ul> * */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getScheme().equals("http")) { LogFactory.getLog(UserManagePasswordsServlet.class).warn("Setting user passwords over http"); } CallingContext cc = ContextFactory.getCallingContext(this, req); resp.setContentType("text/javascript; charset=UTF-8"); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("Pragma", "no-cache"); resp.addHeader(HtmlConsts.X_FRAME_OPTIONS, HtmlConsts.X_FRAME_SAMEORIGIN); PrintWriter out = resp.getWriter(); String callback = req.getParameter(CALLBACK); String echo = req.getParameter(ECHO); if (callback != null) { out.write(callback); } out.write("({"); String username = req.getParameter(USERNAME); String digestAuthHash = req.getParameter(DIGEST_AUTH_HASH); String basicAuthHash = req.getParameter(BASIC_AUTH_HASH); String basicAuthSalt = req.getParameter(BASIC_AUTH_SALT); String outcome; if (username == null || username.length() == 0) { username = ""; outcome = "No username specified"; } else { CredentialsInfo credential = new CredentialsInfo(); credential.setUsername(username); credential.setDigestAuthHash(digestAuthHash); credential.setBasicAuthHash(basicAuthHash); credential.setBasicAuthSalt(basicAuthSalt); try { SecurityServiceUtil.setUserCredentials(credential, cc); String superUsername = cc.getUserService().getSuperUserUsername(); if (superUsername.equals(username)) { cc.getUserService().reloadPermissions(); } outcome = "OK"; } catch (AccessDeniedException e1) { outcome = "Bad username"; } catch (DatastoreFailureException e1) { outcome = ErrorConsts.PERSISTENCE_LAYER_PROBLEM; } } username.replace(BasicConsts.QUOTE, BasicConsts.EMPTY_STRING); // shouldn't // be // allowed... out.write(BasicConsts.QUOTE + USERNAME + BasicConsts.QUOTE + BasicConsts.COLON + BasicConsts.QUOTE + username + BasicConsts.QUOTE); outcome.replace(BasicConsts.QUOTE, BasicConsts.EMPTY_STRING); // shouldn't // be // allowed... out.write(BasicConsts.COMMA); out.write(BasicConsts.QUOTE + STATUS + BasicConsts.QUOTE + BasicConsts.COLON + BasicConsts.QUOTE + outcome + BasicConsts.QUOTE); if (echo != null) { echo.replace(BasicConsts.QUOTE, BasicConsts.EMPTY_STRING); // shouldn't be // allowed... out.write(BasicConsts.COMMA); out.write(BasicConsts.QUOTE + ECHO + BasicConsts.QUOTE + BasicConsts.COLON + BasicConsts.QUOTE + echo + BasicConsts.QUOTE); } out.write("})"); resp.setStatus(HttpServletResponse.SC_ACCEPTED); }
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
public void delete(@Nonnull String resource) throws CloudException, InternalException { Logger std = SCE.getLogger(SCEMethod.class, "std"); Logger wire = SCE.getLogger(SCEMethod.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + SCEMethod.class.getName() + ".post(" + resource + ")"); }//from ww w . j a v a 2 s . co m if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpDelete method = new HttpDelete(endpoint + resource); method.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; StatusLine status; try { APITrace.trace(provider, resource); response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { std.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (std.isDebugEnabled()) { std.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { std.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } String body; try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), body); } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + SCEMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + resource); } } }