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.webdavaccess.servlet.WebdavServlet.java
/** * Process a POST request for the specified resource. * //from www. j a v a 2s . c om * @param req * The servlet request we are processing * @param resp * The servlet response we are creating * * @exception WebdavException * if an error in the underlying store occurs */ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!readOnly) { String path = getRelativePath(req); String parentPath = getParentPath(path); String lockOwner = "doPut" + System.nanoTime() + req.toString(); if (fResLocks.lock(path, lockOwner, true, -1)) { try { if (parentPath != null && fStore.isFolder(parentPath) && !fStore.isFolder(path)) { if (!fStore.objectExists(path)) { fStore.createResource(path); resp.setStatus(HttpServletResponse.SC_CREATED); } else { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } fStore.setResourceContent(path, req.getInputStream(), null, null); resp.setContentLength((int) fStore.getResourceLength(path)); } else { resp.sendError(WebdavStatus.SC_CONFLICT); } } catch (AccessDeniedException e) { log.error("WebdavServer not authenticated: ", e); resp.sendError(WebdavStatus.SC_FORBIDDEN); } catch (WebdavException e) { log.error("WebdavServer internal error: ", e); resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); } finally { fResLocks.unlock(path, lockOwner); } } else { log.error("WebdavServer unable to lock resource " + lockOwner); resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); } } else { resp.sendError(WebdavStatus.SC_FORBIDDEN); } }
From source file:com.janrain.backplane2.server.Backplane2ControllerTest.java
@Test public void testMessagesPostEndPointPAL() throws Exception { // Create source token for the channel TokensAndChannel tokensAndChannel = anonTokenRequest("testbus"); logger.info("created one anon token"); // Create appropriate token saveGrant(new Grant.Builder(GrantType.CLIENT_CREDENTIALS, GrantState.ACTIVE, "fakeOwnerId", testClient.getClientId(),/* w w w . j a v a2s. c om*/ Scope.getEncodedScopesAsString(BackplaneMessage.Field.BUS, "testbus otherbus")).buildGrant()); String token2 = privTokenRequest( Scope.getEncodedScopesAsString(BackplaneMessage.Field.BUS, "testbus otherbus")); // Make the call refreshRequestAndResponse(); request.setRequestURI("/v2/message"); request.setMethod("POST"); setOauthBearerTokenAuthorization(request, token2); request.addHeader("Content-type", "application/json"); HashMap<String, Object> msg = new HashMap<String, Object>(); Map<String, Object> postMessage = new ObjectMapper().readValue(TEST_MSG_1, new TypeReference<Map<String, Object>>() { }); postMessage.put(BackplaneMessage.Field.BUS.getFieldName(), "testbus"); postMessage.put(BackplaneMessage.Field.CHANNEL.getFieldName(), tokensAndChannel.channel); msg.put("message", postMessage); String msgsString = new ObjectMapper().writeValueAsString(msg); logger.info(msgsString); request.setContent(msgsString.getBytes()); handlerAdapter.handle(request, response, controller); logger.info(response.getContentAsString()); assertTrue(response.getStatus() == HttpServletResponse.SC_CREATED); Thread.sleep(1000); List<BackplaneMessage> messages = daoFactory.getBackplaneMessageDAO() .retrieveMessagesByChannel(tokensAndChannel.channel); for (BackplaneMessage message : messages) { daoFactory.getBackplaneMessageDAO().delete(message.getIdValue()); } TokenDAO tokenDAO = daoFactory.getTokenDao(); tokenDAO.delete(tokensAndChannel.bearerToken); tokenDAO.delete(tokensAndChannel.refreshToken); }
From source file:org.clothocad.phagebook.controllers.PersonController.java
@RequestMapping(value = "/createStatus", method = RequestMethod.POST) protected void createStatus(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { System.out.println("inside create status post"); Object pUserId = params.get("clothoId"); String userId = pUserId != null ? (String) pUserId : ""; Object pNewStatus = params.get("status"); String newStatus = pNewStatus != null ? (String) pNewStatus : ""; System.out.println(newStatus); boolean isValid = false; //used only to make sure the person exists in Clotho if (!userId.equals("") && !newStatus.equals("")) { isValid = true;/*from www.j a v a 2 s.co m*/ } if (isValid) { //ESTABLISH CONNECTION 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); // Person retrieve = ClothoAdapter.getPerson(userId, clothoObject); if (!retrieve.getId().equals("")) { if (!newStatus.equals("")) { Status newStatusThing = new Status(); newStatusThing.setText(newStatus); newStatusThing.setUserId(retrieve.getId()); ClothoAdapter.createStatus(newStatusThing, clothoObject); retrieve.addStatus(newStatusThing); } clothoObject.logout(); ClothoAdapter.setPerson(retrieve, clothoObject); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_CREATED); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "status added"); PrintWriter out = response.getWriter(); out.print(responseJSON); out.flush(); out.close(); conn.closeConnection(); } } else { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "missing parameters"); PrintWriter out = response.getWriter(); out.print(responseJSON); out.flush(); out.close(); } }
From source file:com.ephesoft.dcma.webservice.service.EphesoftWebService.java
/** * Sign up method./*from w w w .j a v a2 s . c o m*/ * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} */ @RequestMapping(value = "/signUp", method = RequestMethod.POST) @ResponseBody public void signUp(final HttpServletRequest request, final HttpServletResponse response) { LOGGER.info("Start processing sign up process"); String workingDir = WebServiceUtil.EMPTY_STRING; InputStream instream = null; if (request instanceof DefaultMultipartHttpServletRequest) { UserInformation userInformation = null; User user = null; String receiverName = null; try { final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath(); workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath); LOGGER.info("workingDir:" + workingDir); final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir); LOGGER.info("outputDir:" + outputDir); final DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request; final String batchClassId = request.getParameter("batchClassId"); final String batchClassPriority = request.getParameter("batchClassPriority"); final String batchClassDescription = request.getParameter("batchClassDescription"); String batchClassName = request.getParameter("batchClassName"); batchClassName = getUniqueBatchClassName(batchClassName); final String batchInstanceLimit = request.getParameter("batchInstanceLimit"); final String noOfDays = request.getParameter("noOfDays"); final String pageCount = request.getParameter("pageCount"); String uncFolder = "unc" + ICommonConstants.HYPHEN + batchClassName; LOGGER.info("Batch Class ID value is: " + batchClassId); LOGGER.info("Batch Class Priority value is: " + batchClassPriority); LOGGER.info("Batch Class Description value is: " + batchClassDescription); LOGGER.info("Batch Class Name value is: " + batchClassName); LOGGER.info("UNC Folder value is: " + uncFolder); final MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap(); for (final String fileName : fileMap.keySet()) { if (fileName.toLowerCase(Locale.getDefault()) .indexOf(FileType.XML.getExtension().toLowerCase()) > -WebserviceConstants.ONE) { final MultipartFile multipartFile = multipartRequest.getFile(fileName); instream = multipartFile.getInputStream(); final Source source = XMLUtil.createSourceFromStream(instream); userInformation = (UserInformation) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller() .unmarshal(source); user = createUserObjectFromUserInformation(userInformation); break; } } if (userInformation != null && user != null) { LOGGER.info("Recevier name created: " + receiverName); userConnectivityService.addUser(userInformation); LOGGER.info("Successfully added user for email id: " + userInformation.getEmail()); userConnectivityService.addGroup(userInformation); LOGGER.info("Successfully added group for email id: " + userInformation.getEmail()); BatchClass batchClass = batchClassService.copyBatchClass( batchClassId, batchClassName, batchClassDescription, userInformation.getCompanyName() + ICommonConstants.UNDERSCORE + userInformation.getEmail(), batchClassPriority, uncFolder, true); LOGGER.info("Adding user information into database"); user.setBatchClass(batchClass); userService.createUser(user); LOGGER.info("Successfully added user information into database"); BatchClassCloudConfig batchClassCloudConfig = createBatchClassCloudConfig(batchInstanceLimit, noOfDays, pageCount, batchClass); batchClassCloudConfigService.createBatchClassCloudConfig(batchClassCloudConfig); LOGGER.info("Successfully copied batch class for batch class: " + batchClassId); deploymentService.createAndDeployBatchClassJpdl(batchClass); LOGGER.info("Batch Class deployed successfully"); wizardMailService.sendConfirmationMail(userInformation, false, null); LOGGER.info("User login information sent for email id: " + userInformation.getEmail()); } else { LOGGER.error( "user Information file is invalid. Unable create the User Information Object from XML."); } } catch (WizardMailException wizardMailException) { try { response.sendError(HttpServletResponse.SC_CREATED); } catch (IOException e) { LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE); } } catch (Exception e) { LOGGER.error("Exception occurs while sign up process: " + e.getMessage(), e); if (userInformation != null && user != null) { LOGGER.info("Deleting created user/groups while signup for : " + userInformation.getEmail()); userConnectivityService.deleteUser(userInformation.getEmail()); userConnectivityService.deleteGroup(userInformation.getCompanyName() + ICommonConstants.UNDERSCORE + userInformation.getEmail()); userService.deleteUser(user); LOGGER.info( "Successfully deleted user/groups while signup for : " + userInformation.getEmail()); LOGGER.info("Sending error mail"); try { wizardMailService.sendConfirmationMail(userInformation, true, ExceptionUtils.getStackTrace(e)); LOGGER.info("Error mail sent succesfully"); } catch (WizardMailException e1) { LOGGER.error("Error in sending error mail to client"); } } try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE); } } } }
From source file:org.wyona.yanel.servlet.YanelServlet.java
/** * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) */// ww w . j a v a2 s . c o m @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String transition = request.getParameter(YANEL_RESOURCE_WORKFLOW_TRANSITION); if (transition != null) { executeWorkflowTransition(request, response, request.getParameter(YANEL_RESOURCE_REVISION), transition); return; } String value = request.getParameter(YANEL_RESOURCE_USECASE); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response, false); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response, true); log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.info("No parameter " + YANEL_RESOURCE_USECASE + "!"); String contentType = request.getContentType(); // TODO: Check for type (see section 9.2 of APP spec (e.g. draft 16) if (contentType != null && contentType.indexOf("application/atom+xml") >= 0) { InputStream in = intercept(request.getInputStream()); // Create new Atom entry try { String atomEntryUniversalName = "<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>"; Realm realm = yanelInstance.getMap().getRealm(request.getServletPath()); String newEntryPath = yanelInstance.getMap().getPath(realm, request.getServletPath() + "/" + new Date().getTime() + ".xml"); log.debug("Realm and Path of new Atom entry: " + realm + " " + newEntryPath); Resource atomEntryResource = yanelInstance.getResourceManager().getResource( getEnvironment(request, response), realm, newEntryPath, new ResourceTypeRegistry().getResourceTypeDefinition(atomEntryUniversalName), new ResourceTypeIdentifier(atomEntryUniversalName, null)); ((ModifiableV2) atomEntryResource).write(in); byte buffer[] = new byte[8192]; int bytesRead; InputStream resourceIn = ((ModifiableV2) atomEntryResource).getInputStream(); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } resourceIn.close(); //responseOut.close(); // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + newEntryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } // Enable or disable toolbar yanelUI.switchToolbar(request); getContent(request, response); } }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
protected @Nullable String putStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nullable String md5Hash, @Nullable InputStream stream) throws CloudException, InternalException { Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std"); Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + AbstractMethod.class.getName() + ".putStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)"); }//from w w w.j a v a 2 s.c om if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPut put = new HttpPut(endpoint + resource); put.addHeader("Content-Type", "application/octet-stream"); put.addHeader("X-Auth-Token", authToken); if (md5Hash != null) { put.addHeader("ETag", md5Hash); } put.setEntity(new InputStreamEntity(stream, -1, ContentType.APPLICATION_OCTET_STREAM)); if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); wire.debug("--> BINARY DATA <--"); } HttpResponse response; try { response = client.execute(put); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { std.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); std.debug("HTTP STATUS: " + code); String responseHash = null; for (Header h : response.getAllHeaders()) { if (h.getName().equals("ETag")) { responseHash = h.getValue(); } } if (responseHash != null && md5Hash != null && !responseHash.equals(md5Hash)) { throw new CloudException("MD5 hash values do not match, probably data corruption"); } if (code != HttpServletResponse.SC_CREATED && code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) { std.error("putStream(): Expected CREATED, ACCEPTED, or NO CONTENT for PUT request, got " + code); HttpEntity entity = response.getEntity(); String json = null; if (entity != null) { try { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } RackspaceException.ExceptionItems items = (json == null ? null : RackspaceException.parseException(code, json)); if (items == null) { items = new RackspaceException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } std.error("putStream(): [" + code + " : " + items.message + "] " + items.details); throw new RackspaceException(items); } else { if (code == HttpServletResponse.SC_ACCEPTED) { HttpEntity entity = response.getEntity(); String json = null; if (entity != null) { try { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } if (json != null && !json.trim().equals("")) { return json; } } return null; } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + RackspaceCloud.class.getName() + ".putStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
From source file:com.ephesoft.dcma.webservice.service.EphesoftWebService.java
/** * To modify the password./*from w w w . j a va 2s .c o m*/ * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} */ @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST) @ResponseBody public void modifyPassword(final HttpServletRequest request, final HttpServletResponse response) { final String userName = request.getParameter("userName"); final String newPassword = request.getParameter("newPassword"); try { LOGGER.info("Modifying password for username: " + userName + " and password: " + newPassword); userConnectivityService.modifyUserPassword(userName, newPassword); LOGGER.info("LDAP account update, now updating DB"); User user = userService.getUser(userName); user.setPassword(newPassword); user = userService.updateUser(user); LOGGER.info("DB updated and now sendin mail"); wizardMailService.sendResetPasswordMail(user); } catch (NamingException namingException) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException ioException) { LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE + ioException.toString()); } } catch (WizardMailException wizardMailException) { try { response.sendError(HttpServletResponse.SC_CREATED); } catch (IOException ioMailException) { LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE + ioMailException.toString()); } } }
From source file:com.ephesoft.dcma.webservice.service.EphesoftWebService.java
/** * To change the password./* www. ja v a 2 s .com*/ * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} */ @RequestMapping(value = "/changePassword", method = RequestMethod.POST) @ResponseBody public void changePassword(final HttpServletRequest request, final HttpServletResponse response) { final String userName = request.getParameter("userName"); final String oldPassword = request.getParameter("oldPassword"); final String newPassword = request.getParameter("newPassword"); try { LOGGER.info("Change password for username: " + userName + " and old password: " + newPassword + " with new password: " + newPassword); userConnectivityService.verifyandmodifyUserPassword(userName, oldPassword, newPassword); LOGGER.info("LDAP account updated, now updating DB"); User user = userService.getUser(userName); user.setPassword(newPassword); user = userService.updateUser(user); LOGGER.info("DB updated and now sending mail"); wizardMailService.sendChangePasswordMail(user); } catch (InvalidCredentials invalidCredentialException) { try { response.sendError(HttpServletResponse.SC_FORBIDDEN); } catch (IOException ioException) { LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE + ioException.toString()); } } catch (NamingException namingException) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException ioException) { LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE + ioException.toString()); } } catch (WizardMailException wizardMailException) { try { response.sendError(HttpServletResponse.SC_CREATED); } catch (IOException ioMailException) { LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE + ioMailException.toString()); } } }
From source file:com.janrain.backplane2.server.Backplane2ControllerTest.java
@Test public void testMessagePost3() throws Exception { // Create source token for the channel String testBus = "testbus"; TokensAndChannel tokensAndChannel = anonTokenRequest(testBus); // Create appropriate token saveGrant(new Grant.Builder(GrantType.CLIENT_CREDENTIALS, GrantState.ACTIVE, "fakeOwnerId", testClient.getClientId(),// w w w.j a v a 2 s . co m Scope.getEncodedScopesAsString(BackplaneMessage.Field.BUS, "testbus otherbus")).buildGrant()); String token2 = privTokenRequest( Scope.getEncodedScopesAsString(BackplaneMessage.Field.BUS, "testbus otherbus")); boolean success = false; int numberOfPostedMessages = 0; refreshRequestAndResponse(); for (int i = 0; i < bpConfig.getDefaultMaxMessageLimit() + 1; i++) { // Make the call request.setRequestURI("/v2/message"); request.setMethod("POST"); setOauthBearerTokenAuthorization(request, token2); request.addHeader("Content-type", "application/json"); //request.setContentType("application/json"); //request.setParameter("messages", TEST_MSG_1); HashMap<String, Object> msg = new HashMap<String, Object>(); Map<String, Object> postMesssage = new ObjectMapper().readValue(TEST_MSG_1, new TypeReference<Map<String, Object>>() { }); postMesssage.put(BackplaneMessage.Field.BUS.getFieldName(), testBus); postMesssage.put(BackplaneMessage.Field.CHANNEL.getFieldName(), tokensAndChannel.channel); msg.put("message", postMesssage); String msgsString = new ObjectMapper().writeValueAsString(msg); logger.info(msgsString); request.setContent(msgsString.getBytes()); try { handlerAdapter.handle(request, response, controller); logger.info("testMessagePost3 => " + response.getContentAsString()); assertFalse("Unexpected error: " + response.getContentAsString(), response.getContentAsString().contains("invalid_request")); assertTrue(response.getStatus() == HttpServletResponse.SC_CREATED); logger.info("Messages posted: " + ++numberOfPostedMessages); } catch (InvalidRequestException expected) { // should fail if we're over quota if (i >= bpConfig.getDefaultMaxMessageLimit() && expected.getMessage().contains("Message limit of")) { success = true; } else { fail("Unexpected error: " + expected.getMessage()); } } catch (Exception e) { fail("Error: " + e.getMessage()); } Thread.sleep(500); refreshRequestAndResponse(); } assertTrue("Limit should have been reached, but " + numberOfPostedMessages + "<=" + bpConfig.getDefaultMaxMessageLimit(), success); TokenDAO tokenDAO = daoFactory.getTokenDao(); tokenDAO.delete(tokensAndChannel.bearerToken); tokenDAO.delete(tokensAndChannel.refreshToken); }
From source file:org.opencms.webdav.CmsWebdavServlet.java
/** * Process a POST request for the specified resource.<p> * * @param req the servlet request we are processing * @param resp the servlet response we are creating * * @throws IOException if an input/output error occurs *///from w ww . j a v a 2 s . c o m @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = getRelativePath(req); // Check if webdav is set to read only if (m_readOnly) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0)); } return; } // Check if resource is locked if (isLocked(req)) { resp.setStatus(CmsWebdavStatus.SC_LOCKED); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path)); } return; } boolean exists = m_session.exists(path); boolean result = true; // Temp. content file used to support partial PUT File contentFile = null; CmsWebdavRange range = parseContentRange(req, resp); InputStream 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(req, range, path); resourceInputStream = new FileInputStream(contentFile); } else { resourceInputStream = req.getInputStream(); } try { // FIXME: Add attributes(from Apache Tomcat) if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SAVE_ITEM_0)); } m_session.save(path, resourceInputStream, exists); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "PUT", path), e); } result = false; resp.setStatus(HttpServletResponse.SC_CONFLICT); } // Bugzilla 40326: at this point content file should be safe to delete // as it's no longer referenced. Let's not rely on deleteOnExit because // it's a memory leak, as noted in this Bugzilla issue. if (contentFile != null) { try { contentFile.delete(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_DELETE_TEMP_FILE_0), e); } } } if (result) { if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SAVE_SUCCESS_0)); } if (exists) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.setStatus(HttpServletResponse.SC_CREATED); } } }