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:edu.slu.action.ObjectAction.java
/** * TODO @see batchSaveMetadataForm. Do both methods need to exist? Combine if possible. This is the method we use for generic bulk saving. * Each canvas has an annotation list with 0 - infinity annotations. A copy requires a new annotation list with the copied annotations and a new @id. * Mongo allows us to bulk save. //from ww w . j av a 2 s .c om * The content is from an HTTP request posting in an array filled with annotations to copy. * @throws java.io.UnsupportedEncodingException * @throws javax.servlet.ServletException * @see MongoDBAbstractDAO.bulkSaveFromCopy(String collectionName, BasicDBList entity_array); * @see MongoDBAbstractDAO.bulkSetIDProperty(String collectionName, BasicDBObject[] entity_array); */ public void batchSaveFromCopy() throws UnsupportedEncodingException, IOException, ServletException, Exception { System.out.println("batch save"); if (null != processRequestBody(request, false) && methodApproval(request, "create")) { JSONArray received_array = JSONArray.fromObject(content); for (int b = 0; b < received_array.size(); b++) { //Configure __rerum on each object JSONObject configureMe = received_array.getJSONObject(b); configureMe = configureRerumOptions(configureMe, false); //configure this object received_array.set(b, configureMe); //Replace the current iterated object in the array with the configured object } BasicDBList dbo = (BasicDBList) JSON.parse(received_array.toString()); //tricky cause can't use JSONArray here JSONArray newResources = new JSONArray(); //if the size is 0, no need to bulk save. Nothing is there. if (dbo.size() > 0) { //System.out.println("batch save from copy off to bulk save from copy sending"); //System.out.println(dbo.toString()); newResources = mongoDBService.bulkSaveFromCopy(Constant.COLLECTION_ANNOTATION, dbo); } else { // empty array } //bulk save will automatically call bulk update JSONObject jo = new JSONObject(); jo.element("code", HttpServletResponse.SC_CREATED); jo.element("new_resources", newResources); addLocationHeader(newResources); try { response.setStatus(HttpServletResponse.SC_CREATED); response.addHeader("Content-Type", "application/json; charset=utf-8"); out = response.getWriter(); out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo)); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:edu.slu.action.ObjectAction.java
/** * Save a new annotation provided by the user. * @throws java.io.IOException// w w w . j a v a2s .c o m * @throws javax.servlet.ServletException * @respond with new @id in Location header and the new annotation in the body. */ public void saveNewObject() throws IOException, ServletException, Exception { System.out.println("create object"); if (null != processRequestBody(request, false) && methodApproval(request, "create")) { //System.out.println("process and approval over. actually save now"); JSONObject received = JSONObject.fromObject(content); if (received.containsKey("@id") && !received.getString("@id").isEmpty()) { writeErrorResponse("Object already contains an @id " + received.containsKey("@id") + ". Either remove this property for saving or if it is a RERUM object update instead.", HttpServletResponse.SC_BAD_REQUEST); } else { JSONObject iiif_validation_response = checkIIIFCompliance(received, true); //This boolean should be provided by the user somehow. It is a intended-to-be-iiif flag received = configureRerumOptions(received, false); received.remove("_id"); DBObject dbo = (DBObject) JSON.parse(received.toString()); if (null != request.getHeader("Slug")) { // Slug is the user suggested ID for the annotation. This could be a cool RERUM thing. // cubap: if we want, we can just copy the Slug to @id, warning // if there was some mismatch, since versions are fine with that. } String newObjectID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo); //set @id from _id and update the annotation BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo); String newid = Constant.RERUM_ID_PREFIX + newObjectID; dboWithObjectID.put("@id", newid); mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID); JSONObject jo = new JSONObject(); JSONObject newObjWithID = JSONObject.fromObject(dboWithObjectID); jo.element("code", HttpServletResponse.SC_CREATED); newObjWithID.remove("_id"); jo.element("new_obj_state", newObjWithID); jo.element("iiif_validation", iiif_validation_response); //try { System.out.println("Object created: " + newid); response.addHeader("Access-Control-Allow-Origin", "*"); addWebAnnotationHeaders(newObjectID, isContainerType(received), isLD(received)); addLocationHeader(newObjWithID); response.addHeader("Content-Type", "application/json; charset=utf-8"); response.setContentType("UTF-8"); response.setStatus(HttpServletResponse.SC_CREATED); out = response.getWriter(); out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo)); // } //catch (IOException ex) { // System.out.println("Save new obj failed on IO Exception."); // Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); //} } } }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * Creates a new folder with the specified name under the folder in the provided path. * * @param req the HTTP request// w ww . java 2 s . co m * @param resp the HTTP response * @param path the parent folder path * @param folderName the name of the new folder * @throws IOException if an input/output error occurs */ private void createFolder(HttpServletRequest req, HttpServletResponse resp, String path, final String folderName) throws IOException { if (logger.isDebugEnabled()) logger.debug("Creating folder " + folderName + " in '" + path); final User user = getUser(req); User owner = getOwner(req); boolean exists = true; try { getService().getResourceAtPath(owner.getId(), path + folderName, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName); return; } if (exists) { resp.addHeader("Allow", METHOD_GET + ", " + METHOD_DELETE + ", " + METHOD_HEAD); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } Object parent; try { parent = getService().getResourceAtPath(owner.getId(), path, true); } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName); return; } try { if (parent instanceof Folder) { final Folder folderLocal = (Folder) parent; Folder newFolder = new TransactionHelper<Folder>().tryExecute(new Callable<Folder>() { @Override public Folder call() throws Exception { return getService().createFolder(user.getId(), folderLocal.getId(), folderName); } }); String newResource = getApiRoot() + newFolder.getURI(); resp.setHeader("Location", newResource); resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); out.println(newResource); } else { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } } catch (DuplicateNameException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (ObjectNotFoundException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName); return; } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } resp.setStatus(HttpServletResponse.SC_CREATED); }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * @param req/*from www . j av a 2 s. c o m*/ * @param resp * @throws IOException * @throws FileNotFoundException */ void putResource(HttpServletRequest req, HttpServletResponse resp) throws IOException, FileNotFoundException { String path = getInnerPath(req, PATH_FILES); try { path = URLDecoder.decode(path, "UTF-8"); } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } if (logger.isDebugEnabled()) logger.debug("Updating resource: " + path); final User user = getUser(req); User owner = getOwner(req); boolean exists = true; Object resource = null; FileHeader fileLocal = null; try { resource = getService().getResourceAtPath(owner.getId(), path, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (exists) if (resource instanceof FileHeader) fileLocal = (FileHeader) resource; else { resp.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder"); 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_METHOD_NOT_ALLOWED); return; } resourceInputStream = new FileInputStream(contentFile); } else resourceInputStream = req.getInputStream(); try { Folder folderLocal = null; Object parent = getService().getResourceAtPath(owner.getId(), getParentPath(path), true); if (!(parent instanceof Folder)) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } folderLocal = (Folder) parent; final String name = getLastElement(path); final String mimeType = context.getMimeType(name); File uploadedFile = null; try { uploadedFile = getService().uploadFile(resourceInputStream, user.getId()); } catch (IOException ex) { throw new GSSIOException(ex, false); } FileHeader fileTemp = null; final File uploadedf = uploadedFile; final Folder parentf = folderLocal; final FileHeader f = fileLocal; if (exists) fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().updateFileContents(user.getId(), f.getId(), mimeType, uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath()); } }); else fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().createFile(user.getId(), parentf.getId(), name, mimeType, uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath()); } }); updateAccounting(owner, new Date(), fileTemp.getCurrentBody().getFileSize()); getService().removeFileUploadProgress(user.getId(), fileTemp.getName()); } catch (ObjectNotFoundException e) { result = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (IOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (GSSIOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (DuplicateNameException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } catch (QuotaExceededException e) { resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage()); 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); }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nonnull String post(@Nonnull String action, @Nonnull String endpoint, @Nullable String contentType, @Nullable String payload) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + vCloudMethod.class.getName() + ".post(" + endpoint + ")"); }/* w w w .ja v a2 s . com*/ try { HttpClient client = null; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [POST (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { Org org = authenticate(false); client = getClient(false); HttpPost post = new HttpPost(endpoint); post.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(post, org.token); if (contentType != null) { post.addHeader("Content-Type", contentType); } if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } if (payload != null) { try { //noinspection deprecation post.setEntity( new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } try { wire.debug(EntityUtils.toString(post.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "POST " + action); response = client.execute(post); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code == HttpServletResponse.SC_NOT_FOUND) { throw new CloudException("No action match for " + endpoint); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); return post(action, endpoint, contentType, payload); } else if (code == HttpServletResponse.SC_NO_CONTENT) { return ""; } else if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_CREATED || code == HttpServletResponse.SC_ACCEPTED) { String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } return xml; } else { logger.error("Expected OK or CREATED or NO_CONTENT or ACCEPTED for POST request, got " + code); String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(code, errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, code, response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + code + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (wire.isDebugEnabled()) { wire.debug("<<< [POST (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + vCloudMethod.class.getName() + ".post()"); } } }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nonnull String put(@Nonnull String action, @Nonnull String endpoint, @Nullable String contentType, @Nullable String payload) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + vCloudMethod.class.getName() + ".put(" + endpoint + ")"); }//w w w.java 2 s.c o m try { HttpClient client = null; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { Org org = authenticate(false); client = getClient(false); HttpPut put = new HttpPut(endpoint); put.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(put, org.token); if (contentType != null) { put.addHeader("Content-Type", contentType); } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } if (payload != null) { try { //noinspection deprecation put.setEntity( new StringEntity(payload == null ? "" : payload, "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } try { wire.debug(EntityUtils.toString(put.getEntity())); } catch (IOException ignore) { } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "PUT " + action); 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) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code == HttpServletResponse.SC_NOT_FOUND) { throw new CloudException("No action match for " + endpoint); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); return post(action, endpoint, contentType, payload); } else if (code == HttpServletResponse.SC_NO_CONTENT) { return ""; } else if (code == HttpServletResponse.SC_OK || code == HttpServletResponse.SC_CREATED || code == HttpServletResponse.SC_ACCEPTED) { String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } return xml; } else { logger.error("Expected OK or CREATED or NO_CONTENT or ACCEPTED for POST request, got " + code); String xml = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(code, errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, code, response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + code + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (wire.isDebugEnabled()) { wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + vCloudMethod.class.getName() + ".put()"); } } }
From source file:org.sakaiproject.dav.DavServlet.java
/** * MKCOL Method.//from w w w. ja v a2 s .c o m */ protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Is there a body in the response which we don't understand? If so, return error code // as per rfc2518 8.3.1 if (req.getContentLength() > 0) { resp.sendError(SakaidavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; } if (readOnly) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(SakaidavStatus.SC_LOCKED); return; } String path = getRelativePathSAKAI(req); if (prohibited(path) || (path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } String name = justName(path); if ((name.toUpperCase().startsWith("/WEB-INF")) || (name.toUpperCase().startsWith("/META-INF"))) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } // Check to see if the parent collection exists. ContentHosting will create a parent folder if it // does not exist, but the WebDAV spec requires this operation to fail (rfc2518, 8.3.1). String parentId = isolateContainingId(adjustId(path)); try { contentHostingService.getCollection(parentId); } catch (IdUnusedException e1) { resp.sendError(SakaidavStatus.SC_CONFLICT); return; } catch (TypeException e1) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } catch (PermissionException e1) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } String adjustedId = adjustId(path); // Check to see if collection with this name already exists try { contentHostingService.getProperties(adjustedId); // return error (litmus: MKCOL on existing collection should fail, RFC2518:8.3.1 / 8.3.2) resp.sendError(SakaidavStatus.SC_METHOD_NOT_ALLOWED); return; } catch (IdUnusedException e) { // Resource not found (this is actually the normal case) } catch (PermissionException e) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } // Check to see if a resource with this name already exists if (adjustedId.endsWith("/") && adjustedId.length() > 1) try { String idToCheck = adjustedId.substring(0, adjustedId.length() - 1); contentHostingService.getProperties(idToCheck); // don't allow overwriting an existing resource (litmus: mkcol_over_plain) resp.sendError(SakaidavStatus.SC_METHOD_NOT_ALLOWED); return; } catch (IdUnusedException e) { // Resource not found (this is actually the normal case) } catch (PermissionException e) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } // Add the collection try { ContentCollectionEdit edit = contentHostingService.addCollection(adjustId(path)); ResourcePropertiesEdit resourceProperties = edit.getPropertiesEdit(); resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name); contentHostingService.commitCollection(edit); } catch (IdUsedException e) { // Should not happen because if this esists, we either return or delete above } catch (IdInvalidException e) { M_log.warn("SAKAIDavServlet.doMkcol() IdInvalid:" + e.getMessage()); resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } catch (PermissionException e) { // This is normal resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } catch (InconsistentException e) { M_log.warn("SAKAIDavServlet.doMkcol() InconsistentException:" + e.getMessage()); resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } resp.setStatus(HttpServletResponse.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Process a PUT request for the specified resource. * //from w ww. ja v a2 s . c om * @param request * The servlet request we are processing * @param response * The servlet response we are creating * @exception IOException * if an input/output error occurs * @exception ServletException * if a servlet-specified error occurs */ @SuppressWarnings("unchecked") protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Do not allow files which match patterns specified in properties if (!isFileNameAllowed(req)) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(SakaidavStatus.SC_LOCKED); return; } String path = getRelativePathSAKAI(req); if (prohibited(path) || (path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } // Looking for a Content-Range header if (req.getHeader("Content-Range") != null) { // No content range header is supported resp.sendError(SakaidavStatus.SC_NOT_IMPLEMENTED); } String name = justName(path); // Database max for id field is 255. If we allow longer, odd things happen if (path.length() > 254) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } if ((name.toUpperCase().startsWith("/WEB-INF")) || (name.toUpperCase().startsWith("/META-INF"))) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } // Don't delete the resource and add it again // Update the resource String contentType = ""; InputStream inputStream = req.getInputStream(); contentType = req.getContentType(); // For MS office, ignore the supplied content type if we can figure out one from file type // they send text/xml for doc and docx files if (contentType != null) { UsageSession session = UsageSessionService.getSession(); String agent = null; if (session != null) agent = session.getUserAgent(); if (agent != null && agent.startsWith("Microsoft Office Core Storage Infrastructure")) { String fileContentType = getServletContext().getMimeType(path); if (fileContentType != null) { contentType = fileContentType; } } } if (M_log.isDebugEnabled()) M_log.debug(" req.contentType() =" + contentType); if (contentType == null) { contentType = getServletContext().getMimeType(path); if (M_log.isDebugEnabled()) M_log.debug("Lookup contentType =" + contentType); } if (contentType == null) { if (M_log.isDebugEnabled()) M_log.debug("Unable to determine contentType"); contentType = ""; // Still cannot figure it out } try { ContentResourceEdit edit; boolean newfile = false; String resourcePath = adjustId(path); // Since editResource doesn't throw IdUnusedException correctly, try first with getResource try { contentHostingService.getResource(resourcePath); } catch (IdUnusedException e) { newfile = true; } if (newfile) { edit = contentHostingService.addResource(resourcePath); final ResourcePropertiesEdit p = edit.getPropertiesEdit(); p.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name); User user = UserDirectoryService.getCurrentUser(); final TimeBreakdown timeBreakdown = TimeService.newTime().breakdownLocal(); p.addProperty(ResourceProperties.PROP_COPYRIGHT, "copyright (c)" + " " + timeBreakdown.getYear() + ", " + user.getDisplayName() + ". All Rights Reserved. "); } else { edit = contentHostingService.editResource(resourcePath); contentType = edit.getContentType(); } edit.setContentType(contentType); edit.setContent(inputStream); // commit the change contentHostingService.commitResource(edit, NotificationService.NOTI_NONE); } catch (IdUsedException e) { // Should not happen because we deleted above (unless two requests at same time) M_log.warn("SAKAIDavServlet.doPut() IdUsedException:" + e.getMessage()); resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (IdInvalidException e) { M_log.warn("SAKAIDavServlet.doPut() IdInvalidException:" + e.getMessage()); resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (PermissionException e) { // Normal resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } catch (OverQuotaException e) { // Normal %%% what's the proper response for over-quota? resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } catch (InconsistentException e) { M_log.warn("SAKAIDavServlet.doPut() InconsistentException:" + e.getMessage()); resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (ServerOverloadException e) { M_log.warn("SAKAIDavServlet.doPut() ServerOverloadException:" + e.getMessage()); resp.setStatus(SakaidavStatus.SC_SERVICE_UNAVAILABLE); return; } catch (InUseException e) { resp.sendError(SakaidavStatus.SC_FORBIDDEN); return; } catch (TypeException e) { M_log.warn("SAKAIDavServlet.doPut() TypeException:" + e.getMessage()); resp.sendError(HttpServletResponse.SC_CONFLICT); return; } catch (IdUnusedException inconsistent) { M_log.error( "SAKAIDavServlet.doPut() Inconsistently got IdUnusedException after checking resource exists: " + inconsistent.getMessage()); resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } resp.setStatus(HttpServletResponse.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); }
From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java
@POST @Path("/new") @Consumes(MediaType.MULTIPART_FORM_DATA) @RestQuery(name = "createNewEvent", description = "Creates a new event by the given metadata as JSON and the files in the body", returnDescription = "The workflow identifier", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Event sucessfully added"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") }) public Response createNewEvent(@Context HttpServletRequest request) { try {/* ww w .ja v a 2s .co m*/ String result = getIndexService().createEvent(request); return Response.status(Status.CREATED).entity(result).build(); } catch (IllegalArgumentException e) { return RestUtil.R.badRequest(e.getMessage()); } catch (Exception e) { return RestUtil.R.serverError(); } }
From source file:edu.slu.action.ObjectAction.java
/** * Internal helper method to handle put_update.action on an external object. The goal is to make a copy of object as denoted by the PUT request * as a RERUM object (creating a new object) then have that new root object reference the @id of the external object in its history.previous. * * @param externalObj the external object as it existed in the PUT request to be saved. *///ww w.ja v a 2 s.c o m private void updateExternalObject(JSONObject externalObj) { System.out.println("update on external object"); //System.out.println(externalObj); externalObj.remove("_id"); //Make sure not to pass this along to any save/update scenario. try { JSONObject jo = new JSONObject(); JSONObject iiif_validation_response = checkIIIFCompliance(externalObj, true); JSONObject newObjState = configureRerumOptions(externalObj, true); DBObject dbo = (DBObject) JSON.parse(newObjState.toString()); String exernalObjID = newObjState.getString("@id"); String newRootID; String newObjectID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo); //set @id from _id and update the annotation BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo); newRootID = Constant.RERUM_ID_PREFIX + newObjectID; dboWithObjectID.append("@id", newRootID); newObjState.element("@id", newRootID); mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID); newObjState = configureRerumOptions(newObjState, false); newObjState = alterHistoryPrevious(newObjState, exernalObjID); //update history.previous of the new object to contain the external object's @id. newObjState.remove("_id"); jo.element("code", HttpServletResponse.SC_CREATED); jo.element("original_object_id", exernalObjID); jo.element("new_obj_state", newObjState); jo.element("iiif_validation", iiif_validation_response); addWebAnnotationHeaders(newRootID, isContainerType(newObjState), isLD(newObjState)); addLocationHeader(newObjState); response.addHeader("Access-Control-Allow-Origin", "*"); response.setStatus(HttpServletResponse.SC_CREATED); response.addHeader("Content-Type", "application/json; charset=utf-8"); System.out.println("Object now internal to rerum: " + newRootID); out = response.getWriter(); out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo)); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } }