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.dasein.cloud.ibm.sce.SCEMethod.java
public @Nullable String put(@Nonnull String resource, @Nullable List<NameValuePair> parameters) 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 . c om*/ if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPut method = new HttpPut(endpoint + resource); method.addHeader("Content-Type", "application/x-www-form-urlencoded"); method.addHeader("Accept", "text/xml"); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (parameters != null) { Iterator<NameValuePair> it = parameters.iterator(); StringBuilder str = new StringBuilder(); while (it.hasNext()) { NameValuePair p = it.next(); str.append(p.getName()).append("=").append(p.getValue()); if (it.hasNext()) { str.append("&"); } } wire.debug(str.toString()); wire.debug(""); } } if (parameters != null) { try { method.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } 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(); String body; if (entity == null) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } 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); } else if (status.getStatusCode() == HttpServletResponse.SC_NO_CONTENT) { return null; } else { HttpEntity entity = response.getEntity(); if (entity == null) { return null; } try { return EntityUtils.toString(entity); } catch (IOException e) { throw new SCEException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + SCEMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + resource); } } }
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void createLocation() throws Exception { HashMap<String, Object> user = new HashMap<String, Object>(); long key = (System.currentTimeMillis() % 100000); user.put("name", "My Home " + key); user.put("description", "Integration test location"); user.put("timeZone", TimeZone.getDefault().getID()); HttpClient client = getClient();//from w w w .j a v a 2s .c o m HttpPost method = new HttpPost(cloudAPI + "/location"); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "post:/location:" + apiKeyId + ":" + timestamp + ":" + VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(user)).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 u = new JSONObject(json); String locationId = (u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : null; out("ID: " + locationId); Assert.assertNotNull("Location ID may not be null", locationId); if (CloudTest.locationId == null) { CloudTest.locationId = locationId; } } else { Assert.fail("Failed to create location (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java
/** * Publishes the XML metadata document supplied within the request body. * @param request the servlet request//from w ww .ja va2 s. c o m * @param response the servlet response * @param context the request context * @param publisher the publisher * @throws Exception if an exception occurs */ private void executePut(HttpServletRequest request, HttpServletResponse response, RequestContext context, Publisher publisher) throws Exception { String xml = null; HrRecord record = extractRegistrationInfo(request); //get multipart request for xml creating + upload try { //create mode - xml and zip are sended via parts if (request.getParts().size() > 0) { createAndUpload(request, response, context, publisher); return; } } catch (Exception e) { } //else normal - edit mode (no parts, no zip file - only xml change) if (record == null) { try { xml = this.readInputCharacters(request); } catch (IOException e) { throw new ServletException("400: IOException while reading request body."); } xml = Val.chkStr(Val.removeBOM(xml)); if (xml.length() > 0) { PublicationRequest pubRequest = new PublicationRequest(context, publisher, xml); PublicationRecord pubRecord = pubRequest.getPublicationRecord(); pubRecord.setPublicationMethod(MmdEnums.PublicationMethod.upload.toString()); String pubMethod = Val.chkStr(request.getParameter("publicationMethod")); if (pubMethod.length() > 0) { try { pubMethod = MmdEnums.PublicationMethod.valueOf(Val.chkStr(pubMethod)).toString(); pubRecord.setPublicationMethod(pubMethod); } catch (IllegalArgumentException ex) { } } String asDraft = Val.chkStr(request.getParameter("asDraft")); if (asDraft.equals("true")) { pubRecord.setApprovalStatus(MmdEnums.ApprovalStatus.draft.toString()); } this.determineSourceUri(request, context, pubRequest); try { pubRequest.publish(); //SAVE XML TO ZIP ARCHIVE saveXml2Package(xml, pubRecord.getUuid()); if (!pubRecord.getWasDocumentReplaced()) { response.setStatus(HttpServletResponse.SC_CREATED); } //Validation error triggert via pubRequest.publish /ValidationRequest } catch (ValidationException e) { String sMsg = e.toString(); if (sMsg.contains("XSD violation.")) { throw new ServletException("409: XSD violation."); } else if (sMsg.contains("Invalid metadata document.")) { throw new ServletException("409: Document failed to validate."); } else { throw new ServletException("409: Document failed to validate."); } } catch (SchemaException e) { String sMsg = e.toString(); if (sMsg.contains("Unrecognized metadata schema.")) { throw new ServletException("409: Unrecognized metadata schema."); } else if (sMsg.contains("Unable to parse document.")) { throw new ServletException("409: Unable to parse document as XML."); } else { throw e; } } } else { throw new ServletException("409: Document was empty."); } } else { try { HrCompleteUpdateRequest req = new HrCompleteUpdateRequest(context, record); req.execute(); response.setStatus(HttpServletResponse.SC_CREATED); } catch (HrAssertUrlException e) { throw new ServletException("409: Duplicated resource URL."); } catch (ValidationException e) { String sMsg = e.toString(); if (sMsg.contains("XSD violation.")) { throw new ServletException("409: XSD violation."); } else if (sMsg.contains("Invalid metadata document.")) { throw new ServletException("409: Document failed to validate."); } else { throw new ServletException("409: Document failed to validate."); } } catch (SchemaException e) { String sMsg = e.toString(); if (sMsg.contains("Unrecognized metadata schema.")) { throw new ServletException("409: Unrecognized metadata schema."); } else if (sMsg.contains("Unable to parse document.")) { throw new ServletException("409: Unable to parse document as XML."); } else { throw e; } } catch (Exception ex) { throw new ServletException("409: Unable to register resource."); } } }
From source file:org.ednovo.gooru.controllers.api.ResourceRestController.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_RESOURCE_UPDATE }) @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(method = RequestMethod.POST, value = "/resourceSource/new.{format}") public ModelAndView createResourcesourceAttribution(HttpServletRequest request, @PathVariable(FORMAT) String format, @RequestParam(value = SESSIONTOKEN, required = false) String sessionToken, @RequestParam(value = DOMAIN_NAME, required = false) String domainName, @RequestParam(value = ATTRIBUTION, required = false) String attribution, HttpServletResponse response) throws Exception { request.setAttribute(PREDICATE, RES_UPDATE_RES); Map<String, Object> formField = RequestUtil.getMultipartItems(request); if (formField != null) { domainName = (String) formField.get(DOMAIN_NAME); attribution = (String) formField.get(ATTRIBUTION); }/* w w w. ja va 2 s.co m*/ ResourceSource resourceSource = resourceService.createResourcesourceAttribution(domainName, attribution); if (resourceSource != null) { response.setStatus(HttpServletResponse.SC_CREATED); } return toModelAndView(resourceSource, FORMAT_JSON); }
From source file:org.alfresco.repo.webdav.PutMethodTest.java
/** * Putting a zero content file and update it * <p>/*from www. ja va 2 s. c o m*/ * Put an empty file * <p> * Lock the file * <p> * Put the contents * <p> * Unlock the node */ @Test public void testPutNoContentFileAndUpdate() throws Exception { String fileName = "file-" + GUID.generate(); NodeRef fileNoderef = null; try { executeMethod(WebDAV.METHOD_PUT, fileName, new byte[0], null); ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE, "PATH:\"/app:company_home//cm:" + fileName + "\""); fileNoderef = resultSet.getNodeRef(0); resultSet.close(); assertTrue("File should exist.", nodeService.exists(fileNoderef)); assertEquals("Filename is not correct", fileName, nodeService.getProperty(fileNoderef, ContentModel.PROP_NAME)); assertTrue("Expected return status is " + HttpServletResponse.SC_CREATED + ", but returned is " + response.getStatus(), HttpServletResponse.SC_CREATED == response.getStatus()); byte[] updatedFile = IOUtils .toByteArray(fileFolderService.getReader(fileNoderef).getContentInputStream()); assertTrue("The content should be empty", updatedFile.length == 0); } catch (Exception e) { throw new RuntimeException("Failed to upload a file", e); } try { executeMethod(WebDAV.METHOD_LOCK, fileName, davLockInfoAdminFile, null); assertEquals("File should be locked", LockStatus.LOCK_OWNER, lockService.getLockStatus(fileNoderef)); } catch (Exception e) { throw new RuntimeException("Failed to lock a file", e); } // Construct IF HEADER String lockToken = fileNoderef.getId() + WebDAV.LOCK_TOKEN_SEPERATOR + AuthenticationUtil.getAdminUserName(); String lockHeaderValue = "(<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">)"; HashMap<String, String> headers = new HashMap<String, String>(); headers.put(WebDAV.HEADER_IF, lockHeaderValue); try { executeMethod(WebDAV.METHOD_PUT, fileName, testDataFile, headers); assertTrue("File does not exist.", nodeService.exists(fileNoderef)); assertEquals("Filename is not correct", fileName, nodeService.getProperty(fileNoderef, ContentModel.PROP_NAME)); assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is " + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus()); assertTrue("File should have NO_CONTENT aspect", nodeService.hasAspect(fileNoderef, ContentModel.ASPECT_NO_CONTENT)); InputStream updatedFileIS = fileFolderService.getReader(fileNoderef).getContentInputStream(); byte[] updatedFile = IOUtils.toByteArray(updatedFileIS); updatedFileIS.close(); assertTrue("The content has to be equal", ArrayUtils.isEquals(testDataFile, updatedFile)); } catch (Exception e) { throw new RuntimeException("Failed to upload a file", e); } headers = new HashMap<String, String>(); headers.put(WebDAV.HEADER_LOCK_TOKEN, "<" + WebDAV.OPAQUE_LOCK_TOKEN + lockToken + ">"); try { executeMethod(WebDAV.METHOD_UNLOCK, fileName, null, headers); assertTrue("Expected return status is " + HttpServletResponse.SC_NO_CONTENT + ", but returned is " + response.getStatus(), HttpServletResponse.SC_NO_CONTENT == response.getStatus()); assertFalse("File should not have NO_CONTENT aspect", nodeService.hasAspect(fileNoderef, ContentModel.ASPECT_NO_CONTENT)); assertEquals("File should be unlocked", LockStatus.NO_LOCK, lockService.getLockStatus(fileNoderef)); } catch (Exception e) { throw new RuntimeException("Failed to unlock a file", e); } if (fileNoderef != null) { nodeService.deleteNode(fileNoderef); } }
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void pair() throws Exception { 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();//from w w w .j a va2 s. c om 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); String relayKeyId = (keys.has("apiKeyId") && !keys.isNull("apiKeyId")) ? keys.getString("apiKeyId") : null; String relayKeySecret = (keys.has("apiKeySecret") && !keys.isNull("apiKeySecret")) ? keys.getString("apiKeySecret") : null; out("Key ID: " + relayKeyId); out("Key secret: " + relayKeySecret); Assert.assertNotNull("Relay key ID may not be null", relayKeyId); Assert.assertNotNull("Relay key secret may not be null", relayKeySecret); if (CloudTest.relayKeyId == null) { CloudTest.relayKeyId = relayKeyId; CloudTest.relayKeySecret = relayKeySecret; } CloudTest.pairingCode = null; } else { Assert.fail("Failed to finish pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Process a POST request for the specified resource. * * @throws IOException if an input/output error occurs * @throws ServletException if a servlet-specified error occurs *//* w ww . j a v a 2 s . c o m*/ protected void doPut(ActionContext context) throws ServletException, IOException { //showRequestInfo(context.getRequest()); if (readOnly) { context.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(context.getRequest()); //Fix for MACOSX finder. Do not allow requests for files starting with a period if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) { return; } // Retrieve the resources Connection db = null; ModuleContext resources = null; SystemStatus thisSystem = null; Object object = null; boolean exists = true; boolean result = true; try { db = this.getConnection(context); resources = getCFSResources(db, context); if (resources == null) { context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } thisSystem = this.getSystemStatus(context); try { object = resources.lookup(thisSystem, db, path); } catch (NamingException e) { exists = false; } // Temp. content file used to support partial PUT File contentFile = null; // Input stream for temp. content file used to support partial PUT FileInputStream contentFileInStream = null; //ResourceInfo resourceInfo = new ResourceInfo(thisSystem, path, resources); Range range = parseContentRange(context.getRequest(), context.getResponse()); //InputStream resourceInputStream = null; ServletInputStream resourceInputStream = null; // Append data specified in ranges to existing content for this // resource - create a temp. file on the local filesystem to // perform this operation // Assume just one range is specified for now if (range != null) { contentFile = executePartialPut(context.getRequest(), range, path); //resourceInputStream = new FileInputStream(contentFile); } else { resourceInputStream = context.getRequest().getInputStream(); //System.out.println("RESOURCE INPUT STREAM: " + resourceInputStream); System.out.println("CONTENT LENGTH: " + context.getRequest().getContentLength()); //System.out.println("DATA: " + resourceInputStream.available()); } try { Object thisObject = null; if (exists) { //resources.rebind(path, newResource); Resource oldResource = (Resource) object; oldResource.setContent(resourceInputStream); thisObject = resources.copyResource(thisSystem, db, path, oldResource); } else { Resource newResource = new Resource(resourceInputStream); thisObject = resources.copyResource(thisSystem, db, path, newResource); } if (thisObject != null) { processInsertHook(context, thisObject); } } catch (NamingException e) { //e.printStackTrace(System.out); result = false; } } catch (SQLException e) { e.printStackTrace(System.out); } finally { this.freeConnection(db, context); } if (result) { if (exists) { context.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT); } else { context.getResponse().setStatus(HttpServletResponse.SC_CREATED); } } else { context.getResponse().sendError(HttpServletResponse.SC_CONFLICT); } }
From source file:org.dasein.cloud.azure.AzureMethod.java
public String invoke(@Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); }//from w w w . j a va 2s . com if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } String requestId = null; try { HttpClient client = getClient(); String url = endpoint + account + resource; HttpRequestBase httpMethod = getMethod(method, url); //If it is networking configuration services if (httpMethod instanceof HttpPut) { if (url.endsWith("/services/networking/media")) { httpMethod.addHeader("Content-Type", "text/plain"); } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } //dmayne version is older for anything to do with images and for disk deletion if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) { httpMethod.addHeader("x-ms-version", "2012-08-01"); } else { httpMethod.addHeader("x-ms-version", "2012-03-01"); } if (wire.isDebugEnabled()) { wire.debug(httpMethod.getRequestLine().toString()); for (Header header : httpMethod.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod; if (body != null) { try { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } catch (UnsupportedEncodingException e) { throw new CloudException(e); } } } HttpResponse response; StatusLine status; try { response = client.execute(httpMethod); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.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()); if (h.getName().equalsIgnoreCase("x-ms-request-id")) { requestId = h.getValue().trim(); } } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() == HttpServletResponse.SC_TEMPORARY_REDIRECT) { logger.warn("Expected OK, got " + status.getStatusCode()); String responseBody = ""; HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { responseBody = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } logger.debug(responseBody); logger.debug("https: char " + responseBody.indexOf("https://")); logger.debug("account number: char " + responseBody.indexOf(account)); String tempEndpoint = responseBody.substring(responseBody.indexOf("https://"), responseBody.indexOf(account) - responseBody.indexOf("https://")); logger.debug("temp redirect location: " + tempEndpoint); tempRedirectInvoke(tempEndpoint, method, account, resource, body); } else if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); } } return requestId; }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private void processSignup(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (disableSignups) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } else {/*from ww w . j a va 2 s . com*/ try { Document xmldoc = readXmlRequest(req); UserResource resource = new UserResource(getUrlBase(req), xmldoc, entityFactory); User user = resource.getUser(); user.setAdmin(Boolean.FALSE); user.setLocked(Boolean.FALSE); user = userService.createUser(user, createSignupListeners(req)); resource = new UserResource(user, getUrlBase(req)); resp.setStatus(HttpServletResponse.SC_CREATED); resp.setHeader("Content-Location", resource.getHomedirUrl()); resp.setHeader("ETag", resource.getEntityTag()); sendXmlResponse(resp, resource); } catch (SAXException e) { log.warn("error parsing request body: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error parsing request body: " + e.getMessage()); return; } catch (CmpException e) { log.warn("bad request for signup: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (ModelValidationException e) { handleModelValidationError(resp, e); } catch (InvalidStateException ise) { handleInvalidStateException(resp, ise); } } }
From source file:org.gss_project.gss.server.rest.Webdav.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return;/*from w w w.j a v a2s .c om*/ } final User user = getUser(req); String path = getRelativePath(req); boolean exists = true; Object resource = null; FileHeader file = null; try { resource = getService().getResourceAtPath(user.getId(), path, true); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (exists) if (resource instanceof FileHeader) file = (FileHeader) resource; else { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } boolean result = true; // Temporary content file used to support partial PUT. File contentFile = null; Range range = parseContentRange(req, resp); InputStream resourceInputStream = null; // Append data specified in ranges to existing content for this // resource - create a temporary file on the local filesystem to // perform this operation. // Assume just one range is specified for now if (range != null) { try { contentFile = executePartialPut(req, range, path); } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } resourceInputStream = new FileInputStream(contentFile); } else resourceInputStream = req.getInputStream(); try { Object parent = getService().getResourceAtPath(user.getId(), getParentPath(path), true); if (!(parent instanceof Folder)) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } final Folder folderLocal = (Folder) parent; final String name = getLastElement(path); final String mimeType = getServletContext().getMimeType(name); File uploadedFile = null; try { uploadedFile = getService().uploadFile(resourceInputStream, user.getId()); } catch (IOException ex) { throw new GSSIOException(ex, false); } // FIXME: Add attributes FileHeader fileLocal = null; final FileHeader f = file; final File uf = uploadedFile; if (exists) fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().updateFileContents(user.getId(), f.getId(), mimeType, uf.length(), uf.getAbsolutePath()); } }); else fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().createFile(user.getId(), folderLocal.getId(), name, mimeType, uf.length(), uf.getAbsolutePath()); } }); updateAccounting(user, new Date(), fileLocal.getCurrentBody().getFileSize()); } catch (ObjectNotFoundException e) { result = false; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } catch (QuotaExceededException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } catch (GSSIOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (DuplicateNameException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (result) { if (exists) resp.setStatus(HttpServletResponse.SC_NO_CONTENT); else resp.setStatus(HttpServletResponse.SC_CREATED); } else resp.sendError(HttpServletResponse.SC_CONFLICT); }