List of usage examples for javax.servlet.http HttpServletResponse SC_NO_CONTENT
int SC_NO_CONTENT
To view the source code for javax.servlet.http HttpServletResponse SC_NO_CONTENT.
Click Source Link
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
@Override public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path, @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp, @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters) throws RestException, IOException { try {// w w w .jav a2 s .c om String locationId = (path.length > 1 ? path[1] : null); Location location = null; if (locationId != null) { location = Location.getLocation(locationId); } if (location == null) { throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT, "The location " + locationId + " does not exist."); } BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder source = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { source.append(line); source.append(" "); } JSONObject object = new JSONObject(source.toString()); String action; if (object.has("action") && !object.isNull("action")) { action = object.getString("action"); } else { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION, "An invalid action was specified (or not specified) in the PUT"); } if (object.has("location")) { object = object.getJSONObject("location"); } else { object = null; } if (action.equalsIgnoreCase("initializePairing")) { HashMap<String, Object> json = new HashMap<String, Object>(); String pairingCode = location.readyForPairing(); json.put("pairingCode", pairingCode); resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println((new JSONObject(json)).toString()); resp.getWriter().flush(); } else if (action.equalsIgnoreCase("modify")) { if (object == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT, "No location was specified in the PUT"); } String name, description; TimeZone timeZone; if (object.has("name") && !object.isNull("name")) { name = object.getString("name"); } else { name = location.getName(); } if (object.has("description") && !object.isNull("description")) { description = object.getString("description"); } else { description = location.getName(); } if (object.has("timeZone") && !object.isNull("timeZone")) { String tz = object.getString("timeZone"); timeZone = TimeZone.getTimeZone(tz); } else { timeZone = location.getTimeZone(); } location.modify(name, description, timeZone); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION, "The action " + action + " is not a valid action."); } } catch (JSONException e) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON, "Invalid JSON in request"); } catch (PersistenceException e) { throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR, e.getMessage()); } }
From source file:org.ednovo.gooru.controllers.v2.api.ResourceRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_RESOURCE_DELETE }) @RequestMapping(method = { RequestMethod.DELETE, RequestMethod.PUT }, value = "/{id}/taxonomy") public void deleteTaxonomyResource(@RequestBody final String data, @PathVariable(value = ID) final String resourceId, final HttpServletRequest request, final HttpServletResponse response) throws Exception { request.setAttribute(PREDICATE, RESOURCE_DELETE_RESOURCE_TAXONOMY); final User user = (User) request.getAttribute(Constants.USER); final JSONObject json = requestData(data); this.getResourceService().deleteTaxonomyResource(resourceId, this.buildResourceFromInputParameters(getValue(RESOURCE, json)), user); SessionContextSupport.putLogParameter(EVENT_NAME, "taxonomy-resource-delete"); SessionContextSupport.putLogParameter(GOORU_OID, resourceId); SessionContextSupport.putLogParameter(USER_ID, user.getUserId()); SessionContextSupport.putLogParameter(GOORU_UID, user.getPartyUid()); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:org.eclipse.userstorage.tests.util.USSServer.java
protected void deleteBlob(HttpServletRequest request, HttpServletResponse response, File blobFile, File etagFile, boolean exists) throws IOException { if (exists) { String etag = IOUtil.readUTF(etagFile); String ifMatch = getETag(request, "If-Match"); if (ifMatch != null && !ifMatch.equals(etag)) { response.sendError(HttpServletResponse.SC_CONFLICT); return; }//w w w . j a va 2 s . c o m } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } IOUtil.delete(blobFile); IOUtil.delete(etagFile); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:org.opencastproject.episode.endpoint.AbstractEpisodeServiceRestEndpoint.java
@POST @Path("apply/{wfDefId}") @RestQuery(name = "apply", description = "Apply a workflow to a list of media packages.", pathParameters = { @RestParameter(name = "wfDefId", type = RestParameter.Type.STRING, description = "The ID of the workflow to apply", isRequired = true) }, restParameters = { @RestParameter(name = "mediaPackageIds", type = RestParameter.Type.STRING, description = "A list of media package ids.", isRequired = true) }, reponses = { @RestResponse(description = "The workflows have been started.", responseCode = HttpServletResponse.SC_NO_CONTENT) }, returnDescription = "No content is returned.") public Response applyWorkflow(@PathParam("wfDefId") final String wfId, @FormParam("mediaPackageIds") final List<String> mpIds, @Context final HttpServletRequest req) { return handleException(new Function0.X<Response>() { @Override//from w w w.ja v a 2 s . c om public Response xapply() throws Exception { final Map<String, String[]> params = (Map<String, String[]>) req.getParameterMap(); // filter and reduce String[] to String final Map<String, String> wfp = mlist(params.entrySet().iterator()).foldl( Collections.<String, String>map(), new Function2<Map<String, String>, Map.Entry<String, String[]>, Map<String, String>>() { @Override public Map<String, String> apply(Map<String, String> wfConf, Map.Entry<String, String[]> param) { final String key = param.getKey(); if (!"mediaPackageIds".equalsIgnoreCase(key)) wfConf.put(key, param.getValue()[0]); return wfConf; } }); final WorkflowDefinition wfd = getWorkflowService().getWorkflowDefinitionById(wfId); getEpisodeService().applyWorkflow(workflow(wfd, wfp), uriRewriter, mpIds); return Response.noContent().build(); } }); }
From source file:org.ednovo.gooru.controllers.v2.api.ApplicationRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_APPLICATION_DELETE }) @RequestMapping(method = { RequestMethod.DELETE }, value = "/{apiKey}/item/{id}") public void deleteApplicationItemByItemId(@PathVariable(value = API_KEY) String apikey, @PathVariable(value = ID) String applicationItemId, HttpServletRequest request, HttpServletResponse response) throws Exception { this.getApplicationService().deleteApplicationItemByItemId(apikey, applicationItemId); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java
public static String processFileUpload(HttpServletRequest request, HttpServletResponse response, RequestModel req) {// ww w. j a v a 2 s . c o m // Create a factory for disk-based file items Map<String, String> paraMap = new HashMap<String, String>(); File uploadedFile = null; boolean uploaded = false; DiskFileItemFactory factory = new DiskFileItemFactory(); String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads"); FileOps.createDir(uploadDirName); File storageDir = new File(uploadDirName); factory.setRepository(storageDir); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); paraMap.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName.length() > 0) { String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); uploadedFile = new File(storageDir, fileName); try { item.write(uploadedFile); uploaded = true; } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } } } if (uploaded) { return SpServerLogic.getDocUploadResponse(req, uploadedFile); } else { if (paraMap.containsKey("xmlName")) { return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName")); } } } catch (FileUploadException ex) { LOG.log(Level.SEVERE, null, ex); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); return ""; }
From source file:jp.aegif.alfresco.online_webdav.PutMethod.java
/** * Execute the WebDAV request/*from ww w.j av a 2 s. co m*/ * * @exception WebDAVServerException */ protected void executeImpl() throws WebDAVServerException, Exception { if (logger.isDebugEnabled()) { String path = getPath(); String userName = getDAVHelper().getAuthenticationService().getCurrentUserName(); logger.debug("Put node: \n" + " user: " + userName + "\n" + " path: " + path + "\n" + "noContent: " + noContent); } FileFolderService fileFolderService = getFileFolderService(); // Get the status for the request path LockInfo nodeLockInfo = null; try { //contentNodeInfo = getNodeForPath(getRootNodeRef(), getPath(), getServletPath()); contentNodeInfo = getDAVHelper().getFileInfoFromRequestPath(m_request); // make sure that we are not trying to use a folder if (contentNodeInfo.isFolder()) { throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST); } nodeLockInfo = checkNode(contentNodeInfo); // 'Unhide' nodes hidden by us and behave as though we created them NodeRef contentNodeRef = contentNodeInfo.getNodeRef(); if (fileFolderService.isHidden(contentNodeRef) && !getDAVHelper().isRenameShuffle(getPath())) { fileFolderService.setHidden(contentNodeRef, false); created = true; } } catch (FileNotFoundException e) { // // the file doesn't exist - create it // String[] paths = getDAVHelper().splitPath(getPath()); // try // { // FileInfo parentNodeInfo = getNodeForPath(getRootNodeRef(), paths[0], getServletPath()); // // create file // contentNodeInfo = fileFolderService.create(parentNodeInfo.getNodeRef(), paths[1], ContentModel.TYPE_CONTENT); // created = true; // // } // catch (FileNotFoundException ee) // { // // bad path // throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST); // } // catch (FileExistsException ee) // { // // ALF-7079 fix, retry: it looks like concurrent access (file not found but file exists) // throw new ConcurrencyFailureException("Concurrent access was detected.", ee); // } throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST); } String userName = getDAVHelper().getAuthenticationService().getCurrentUserName(); LockInfo lockInfo = getDAVLockService().getLockInfo(contentNodeInfo.getNodeRef()); if (lockInfo != null) { if (lockInfo.isLocked() && !lockInfo.getOwner().equals(userName)) { if (logger.isDebugEnabled()) { String path = getPath(); String owner = lockInfo.getOwner(); logger.debug("Node locked: path=[" + path + "], owner=[" + owner + "], current user=[" + userName + "]"); } // Indicate that the resource is locked throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED); } } // ALF-16808: We disable the versionable aspect if we are overwriting // empty content because it's probably part of a compound operation to // create a new single version boolean disabledVersioning = false; try { // Disable versioning if we are overwriting an empty file with content NodeRef nodeRef = contentNodeInfo.getNodeRef(); ContentData contentData = (ContentData) getNodeService().getProperty(nodeRef, ContentModel.PROP_CONTENT); if ((contentData == null || contentData.getSize() == 0) && getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) { getDAVHelper().getPolicyBehaviourFilter().disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE); disabledVersioning = true; } // ALF-16756: To avoid firing inbound rules too early (while a node is still locked) apply the no content aspect if (nodeLockInfo != null && nodeLockInfo.isExclusive() && !ContentData.hasContent(contentData)) { getNodeService().addAspect(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_NO_CONTENT, null); } // Access the content ContentWriter writer = fileFolderService.getWriter(contentNodeInfo.getNodeRef()); // set content properties writer.guessMimetype(contentNodeInfo.getName()); writer.guessEncoding(); // Get the input stream from the request data InputStream is = m_request.getInputStream(); // Write the new data to the content node writer.putContent(is); // Ask for the document metadata to be extracted Action extract = getActionService().createAction(ContentMetadataExtracter.EXECUTOR_NAME); if (extract != null) { extract.setExecuteAsynchronously(false); getActionService().executeAction(extract, contentNodeInfo.getNodeRef()); } // If the mime-type determined by the repository is different // from the original specified in the request, update it. if (m_strContentType == null || !m_strContentType.equals(writer.getMimetype())) { String oldMimeType = m_strContentType; m_strContentType = writer.getMimetype(); if (logger.isDebugEnabled()) { logger.debug("Mimetype originally specified as " + oldMimeType + ", now guessed to be " + m_strContentType); } } // Record the uploaded file's size fileSize = writer.getSize(); // Set the response status, depending if the node existed or not m_response.setStatus(created ? HttpServletResponse.SC_CREATED : HttpServletResponse.SC_NO_CONTENT); } catch (Throwable e) { // check if the node was marked with noContent aspect previously by lock method AND // we are about to give up if (noContent && RetryingTransactionHelper.extractRetryCause(e) == null) { // remove the 0 bytes content if save operation failed or was cancelled final NodeRef nodeRef = contentNodeInfo.getNodeRef(); getTransactionService().getRetryingTransactionHelper() .doInTransaction(new RetryingTransactionCallback<String>() { public String execute() throws Throwable { getNodeService().deleteNode(nodeRef); if (logger.isDebugEnabled()) { logger.debug("Put failed. DELETE " + getPath()); } return null; } }, false, true); } throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { if (disabledVersioning) { getDAVHelper().getPolicyBehaviourFilter().enableBehaviour(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_VERSIONABLE); } } postActivity(); }
From source file:org.sakaiproject.sdata.tool.JCRHandler.java
@Override public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// w w w .j a v a 2s .c o m snoopRequest(request); ResourceDefinition rp = resourceDefinitionFactory.getSpec(request); Node n = jcrNodeFactory.getNode(rp.getRepositoryPath()); if (n == null) { response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } NodeType nt = n.getPrimaryNodeType(); long lastModifiedTime = -10; if (JCRConstants.NT_FILE.equals(nt.getName())) { Node resource = n.getNode(JCRConstants.JCR_CONTENT); Property lastModified = resource.getProperty(JCRConstants.JCR_LASTMODIFIED); lastModifiedTime = lastModified.getDate().getTimeInMillis(); if (!checkPreconditions(request, response, lastModifiedTime, String.valueOf(lastModifiedTime))) { return; } } Session s = n.getSession(); n.remove(); s.save(); response.setStatus(HttpServletResponse.SC_NO_CONTENT); } catch (Exception e) { sendError(request, response, e); snoopRequest(request); LOG.error("Failed TO service Request ", e); } }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
private void loadOrg(@Nonnull String endpoint, @Nonnull Org org, @Nonnull String orgId) throws CloudException, InternalException { String xml;/*from ww w .ja v a2 s . co m*/ if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [GET (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { HttpClient client = getClient(false); HttpGet get = new HttpGet(endpoint); get.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(get, org.token); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "GET org"); response = client.execute(get); 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 || code == HttpServletResponse.SC_FORBIDDEN) { throw new CloudException("Org URL is invalid"); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); loadOrg(endpoint, org, orgId); return; } else if (code == HttpServletResponse.SC_NO_CONTENT) { throw new CloudException("No content from org URL"); } else if (code == HttpServletResponse.SC_OK) { try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } else { xml = null; } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } } else { logger.error("Expected OK for GET request, got " + code); try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } else { xml = null; } } 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 (wire.isDebugEnabled()) { wire.debug("<<< [GET (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } if (xml == null) { throw new CloudException("No content from org URL"); } Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList orgList = doc.getElementsByTagName(nsString + "Org"); for (int i = 0; i < orgList.getLength(); i++) { Node orgNode = orgList.item(i); if (orgNode.hasAttributes()) { Node type = orgNode.getAttributes().getNamedItem("type"); if (type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg())) { Node name = orgNode.getAttributes().getNamedItem("name"); if (name != null && name.getNodeValue().trim().equals(orgId)) { Node href = orgNode.getAttributes().getNamedItem("href"); if (href != null) { Region region = new Region(); String url = href.getNodeValue().trim(); region.setActive(true); region.setAvailable(true); if (provider.isCompat()) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/api/org")); org.region = region; org.url = url; return; } } } } } throw new CloudException("Could not find " + orgId + " among listed orgs"); }
From source file:org.artifactory.webapp.wicket.page.config.repos.remote.HttpRepoPanel.java
protected boolean remoteRepoTestValidStatus(int status) { return status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_NO_CONTENT; }