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:org.osaf.cosmo.cmp.CmpServlet.java
private void processRecoverPassword(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException { User user = getUserFromParameter(req); if (user != null) { String passwordRecoveryKey = passwordRecoverer.createRecoveryKey(); final PasswordRecovery passwordRecovery = entityFactory.createPasswordRecovery(user, passwordRecoveryKey);/*from w ww . j ava2 s . c o m*/ userService.createPasswordRecovery(passwordRecovery); PasswordRecoveryMessageContext context = createPasswordRecoveryMessageContext(req, passwordRecovery); passwordRecoverer.sendRecovery(passwordRecovery, context); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java
private ArchivaDavResourceLocator checkLocatorIsInstanceOfRepositoryLocator(DavResourceLocator locator) throws DavException { if (!(locator instanceof ArchivaDavResourceLocator)) { throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Locator does not implement RepositoryLocator"); }/* w w w . ja va2 s .c o m*/ // Hidden paths if (locator.getResourcePath().startsWith(ArchivaDavResource.HIDDEN_PATH_PREFIX)) { throw new DavException(HttpServletResponse.SC_NOT_FOUND); } ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator; // MRM-419 - Windows Webdav support. Should not 404 if there is no content. if (StringUtils.isEmpty(archivaLocator.getRepositoryId())) { throw new DavException(HttpServletResponse.SC_NO_CONTENT); } return archivaLocator; }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
@SuppressWarnings("unused") protected @Nullable String postStream(@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() + ".postStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)"); }/*from w ww.j av a 2 s . c o m*/ if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPost post = new HttpPost(endpoint + resource); post.addHeader("Content-Type", "application/octet-stream"); post.addHeader("X-Auth-Token", authToken); post.setEntity(new InputStreamEntity(stream, -1, ContentType.APPLICATION_OCTET_STREAM)); if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); wire.debug("--> BINARY DATA <--"); } HttpResponse response; try { 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) { 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_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) { std.error("postStream(): Expected ACCEPTED or NO CONTENT for POST 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("postStream(): [" + code + " : " + items.message + "] " + items.details); throw new RackspaceException(items); } else { wire.debug(""); 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() + ".postStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
From source file:com.jpeterson.littles3.StorageEngine.java
/** * Delete/*from ww w .j a v a 2s .com*/ * * @param req * the HttpServletRequest object that contains the request the * client made of the servlet * @param resp * the HttpServletResponse object that contains the response the * servlet returns to the client * @param IOException * if an input or output error occurs while the servlet is * handling the DELETE request * @param ServletException * if the request for the DELETE cannot be handled */ public void methodDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { S3ObjectRequest or; try { or = S3ObjectRequest.create(req, resolvedHost(), (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR)); } catch (InvalidAccessKeyIdException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId"); return; } catch (InvalidSecurityException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } catch (RequestTimeTooSkewedException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed"); return; } catch (SignatureDoesNotMatchException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch"); return; } catch (AuthenticatorException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } logger.debug("S3ObjectRequest: " + or); CanonicalUser requestor = or.getRequestor(); if (or.getKey() != null) { Bucket bucket; S3Object s3Object; StorageService storageService; storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); // make sure requester can "WRITE" to the bucket try { bucket = storageService.loadBucket(or.getBucket()); bucket.canWrite(requestor); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } try { s3Object = storageService.load(bucket.getName(), or.getKey()); } catch (DataRetrievalFailureException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey"); return; } storageService.remove(s3Object); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } else if (or.getBucket() != null) { StorageService storageService; Bucket bucket; // validate bucket String bucketName = or.getBucket(); storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); try { bucket = storageService.loadBucket(bucketName); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } if (!requestor.equals(bucket.getAcp().getOwner())) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } try { storageService.deleteBucket(bucket); } catch (BucketNotEmptyException e) { resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketNotEmpty"); return; } resp.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private void processResetPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); String passwordResetKey = path.substring(URL_PASSWORD_RESET.length()); PasswordRecovery passwordRecovery = userService.getPasswordRecovery(passwordResetKey); if (passwordRecovery != null) { String newPassword = req.getParameter("password"); if (newPassword != null) { User user = passwordRecovery.getUser(); user.setPassword(newPassword); try { userService.updateUser(user); } catch (ModelValidationException e) { // can happen when password is bad handleModelValidationError(resp, e); return; }//from w w w. j a v a 2 s . co m userService.deletePasswordRecovery(passwordRecovery); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } else { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.opencastproject.adminui.endpoint.BlacklistEndpoint.java
@DELETE @Path("{periodId}") @Produces(MediaType.APPLICATION_JSON)// ww w. j a v a2 s. c om @RestQuery(name = "deleteperiod", description = "Deletes the blacklist period by the given id", returnDescription = "No content", pathParameters = { @RestParameter(name = "periodId", description = "The period id", isRequired = true, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "The blacklist period has been deleted", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "No blacklist period with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }) public Response deleteBlacklist(@PathParam("periodId") long periodId) throws NotFoundException { try { participationPersistence.deletePeriod(periodId); return Response.noContent().build(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete blacklist period with id {}: {}", periodId, ExceptionUtils.getStackTrace(e)); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } }
From source file:org.apache.openaz.xacml.rest.XACMLPapServlet.java
/** * Requests from the Admin Console to create new items or update existing ones * * @param request/*from w ww. j a v a 2 s . c o m*/ * @param response * @param groupId * @throws ServletException * @throws java.io.IOException */ private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId) throws ServletException, IOException { try { // for PUT operations the group may or may not need to exist before the operation can be done PDPGroup group = papEngine.getGroup(groupId); // determine the operation needed based on the parameters in the request // for remaining operations the group must exist before the operation can be done if (group == null) { logger.error("Unknown groupId '" + groupId + "'"); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'"); return; } if (request.getParameter("policy") != null) { // group=<groupId> policy=<policyId> contents=policy file <= Create new policy file in group // dir, or replace it if it already exists (do not touch properties) // TODO - currently this is done by the AC, but it should be done here by getting the policy // file out of the contents and saving to disk logger.error("PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! "); response.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } else if (request.getParameter("pdpId") != null) { // ARGS: group=<groupId> pdpId=<pdpId/URL> <= create a new PDP or Update an Existing one String pdpId = request.getParameter("pdpId"); // get the request content into a String String json = null; // read the inputStream into a buffer (trick found online scans entire input looking for // end-of-file) Scanner scanner = new Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); logger.info("JSON request from AC: " + json); // convert Object sent as JSON into local object ObjectMapper mapper = new ObjectMapper(); Object objectFromJSON = mapper.readValue(json, StdPDP.class); if (pdpId == null || objectFromJSON == null || !(objectFromJSON instanceof StdPDP) || ((StdPDP) objectFromJSON).getId() == null || !((StdPDP) objectFromJSON).getId().equals(pdpId)) { logger.error( "PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON=" + objectFromJSON); response.sendError(500, "Bad input, pdpid=" + pdpId + " object=" + objectFromJSON); } StdPDP pdp = (StdPDP) objectFromJSON; if (papEngine.getPDP(pdpId) == null) { // this is a request to create a new PDP object papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription()); } else { // this is a request to update the pdp papEngine.updatePDP(pdp); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); if (logger.isDebugEnabled()) { logger.debug("PDP '" + pdpId + "' created/updated"); } // adjust the group's state including the new PDP ((StdPDPGroup) group).resetStatus(); // tell the Admin Consoles there is a change notifyAC(); // this might affect the PDP, so notify it of the change pdpChanged(pdp); return; } else if (request.getParameter("pipId") != null) { // group=<groupId> pipId=<pipEngineId> contents=pip properties <= add a PIP to pip config, or // replace it if it already exists (lenient operation) // TODO logger.error("UNIMPLEMENTED "); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); return; } else { // Assume that this is an update of an existing PDP Group // ARGS: group=<groupId> <= Update an Existing Group // get the request content into a String String json = null; // read the inputStream into a buffer (trick found online scans entire input looking for // end-of-file) Scanner scanner = new Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); logger.info("JSON request from AC: " + json); // convert Object sent as JSON into local object ObjectMapper mapper = new ObjectMapper(); Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class); if (objectFromJSON == null || !(objectFromJSON instanceof StdPDPGroup) || !((StdPDPGroup) objectFromJSON).getId().equals(group.getId())) { logger.error("Group update had bad input. id=" + group.getId() + " objectFromJSON=" + objectFromJSON); response.sendError(500, "Bad input, id=" + group.getId() + " object=" + objectFromJSON); } // The Path on the PAP side is not carried on the RESTful interface with the AC // (because it is local to the PAP) // so we need to fill that in before submitting the group for update ((StdPDPGroup) objectFromJSON).setDirectory(((StdPDPGroup) group).getDirectory()); papEngine.updateGroup((StdPDPGroup) objectFromJSON); response.setStatus(HttpServletResponse.SC_NO_CONTENT); if (logger.isDebugEnabled()) { logger.debug("Group '" + group.getId() + "' updated"); } // tell the Admin Consoles there is a change notifyAC(); // Group changed, which might include changing the policies groupChanged(group); return; } } catch (PAPException e) { logger.error("AC PUT exception: " + e, e); response.sendError(500, e.getMessage()); return; } }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private void processSendActivation(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException { User user = getUserFromParameter(req); if (user != null && user.getActivationId() != null) { accountActivator.sendActivationMessage(user, createActivationContext(req)); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else {/*from w ww.jav a 2 s. c om*/ resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nullable String get(@Nonnull String resource, @Nullable String id) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + vCloudMethod.class.getName() + ".get(" + resource + "," + id + ")"); }//from w w w . j a va 2s . c o m try { Org org = authenticate(false); String endpoint = toURL(resource, id); HttpClient client = null; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [GET (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { 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 " + resource); 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) { return null; } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { if (matches(getAPIVersion(), "1.0", null)) { authenticate(true); return get(resource, id); } return null; } else if (code == HttpServletResponse.SC_NO_CONTENT) { return ""; } else if (code == HttpServletResponse.SC_OK) { 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 for GET 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("<<< [GET (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + vCloudMethod.class.getName() + ".get()"); } } }
From source file:org.opencastproject.scheduler.endpoint.SchedulerRestService.java
/** * Looks for events that are conflicting with the given event, because they use the same recorder at the same time. * /*from w w w. jav a2 s. c o m*/ * @param device * device that will be checked for conflicts * @param startDate * start date of conflict * @param endDate * end date of conflict * @param duration * duration of conflict (only used if recurrence rule is specified, otherwise duration is determined from * start and end date) * @param rrule * recurrence rule for conflict * @return An XML with the list of conflicting events */ @GET @Produces(MediaType.TEXT_XML) @Path("conflicts.xml") @RestQuery(name = "conflictingrecordingsasxml", description = "Searches for conflicting recordings based on parameters", returnDescription = "Returns NO CONTENT if no recordings are in conflict within specified period or list of conflicting recordings in XML", restParameters = { @RestParameter(name = "device", description = "Device identifier for which conflicts will be searched", isRequired = true, type = Type.TEXT), @RestParameter(name = "start", description = "Start time of conflicting period, in milliseconds", isRequired = true, type = Type.INTEGER), @RestParameter(name = "end", description = "End time of conflicting period, in milliseconds", isRequired = true, type = Type.INTEGER), @RestParameter(name = "duration", description = "If recurrence rule is specified duration of each conflicting period, in milliseconds", isRequired = false, type = Type.INTEGER), @RestParameter(name = "rrule", description = "Rule for recurrent conflicting, specified as: \"FREQ=WEEKLY;BYDAY=day(s);BYHOUR=hour;BYMINUTE=minute\". FREQ is required. BYDAY may include one or more (separated by commas) of the following: SU,MO,TU,WE,TH,FR,SA.", isRequired = false, type = Type.STRING), @RestParameter(name = "timezone", description = "The timezone of the capture device", isRequired = false, type = Type.STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No conflicting events found"), @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Found conflicting events, returned in body of response"), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid parameters") }) public Response getConflictingEventsXml(@QueryParam("device") String device, @QueryParam("start") Long startDate, @QueryParam("end") Long endDate, @QueryParam("duration") Long duration, @QueryParam("rrule") String rrule, @QueryParam("timezone") String timezone) { return getConflictingEvents(device, startDate, endDate, duration, rrule, timezone, false); }