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.apache.openaz.xacml.rest.XACMLPapServlet.java
/** * Requests from the Admin Console for operations not on single specific objects * * @param request/*from w w w .j a v a2s .c o m*/ * @param response * @param groupId * @throws ServletException * @throws java.io.IOException */ private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId) throws ServletException, IOException { try { String groupName = request.getParameter("groupName"); String groupDescription = request.getParameter("groupDescription"); if (groupName != null && groupDescription != null) { // Args: group=<groupId> groupName=<name> groupDescription=<description> <= create a new group String unescapedName = URLDecoder.decode(groupName, "UTF-8"); String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8"); try { papEngine.newGroup(unescapedName, unescapedDescription); } catch (Exception e) { logger.error("Unable to create new group: " + e.getLocalizedMessage()); response.sendError(500, "Unable to create new group '" + groupId + "'"); return; } response.setStatus(HttpServletResponse.SC_NO_CONTENT); if (logger.isDebugEnabled()) { logger.debug("New Group '" + groupId + "' created"); } // tell the Admin Consoles there is a change notifyAC(); // new group by definition has no PDPs, so no need to notify them of changes return; } // for all remaining POST operations the group must exist before the operation can be done PDPGroup group = papEngine.getGroup(groupId); if (group == null) { logger.error("Unknown groupId '" + groupId + "'"); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'"); return; } // determine the operation needed based on the parameters in the request if (request.getParameter("policyId") != null) { // Args: group=<groupId> policy=<policyId> <= copy file // copy a policy from the request contents into a file in the group's directory on this // machine String policyId = request.getParameter("policyId"); try { ((StdPDPGroup) group).copyPolicyToFile(policyId, request.getInputStream()); } catch (Exception e) { String message = "Policy '" + policyId + "' not copied to group '" + groupId + "': " + e; logger.error(message); response.sendError(500, message); return; } // policy file copied ok response.setStatus(HttpServletResponse.SC_NO_CONTENT); if (logger.isDebugEnabled()) { logger.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'"); } return; } else if (request.getParameter("default") != null) { // Args: group=<groupId> default=true <= make default // change the current default group to be the one identified in the request. // // This is a POST operation rather than a PUT "update group" because of the side-effect that // the current default group is also changed. // It should never be the case that multiple groups are currently marked as the default, but // protect against that anyway. try { papEngine.SetDefaultGroup(group); } catch (Exception e) { logger.error("Unable to set group: " + e.getLocalizedMessage()); response.sendError(500, "Unable to set group '" + groupId + "' to default"); return; } response.setStatus(HttpServletResponse.SC_NO_CONTENT); if (logger.isDebugEnabled()) { logger.debug("Group '" + groupId + "' set to be default"); } // Notify the Admin Consoles that something changed // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so // just notify on that // TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify // AC to update whole configuration of all groups notifyAC(); // This does not affect any PDPs in the existing groups, so no need to notify them of this // change return; } else if (request.getParameter("pdpId") != null) { // Args: group=<groupId> pdpId=<pdpId> <= move PDP to group String pdpId = request.getParameter("pdpId"); PDP pdp = papEngine.getPDP(pdpId); PDPGroup originalGroup = papEngine.getPDPGroup(pdp); papEngine.movePDP(pdp, group); response.setStatus(HttpServletResponse.SC_NO_CONTENT); if (logger.isDebugEnabled()) { logger.debug( "PDP '" + pdp.getId() + "' moved to group '" + group.getId() + "' set to be default"); } // update the status of both the original group and the new one ((StdPDPGroup) originalGroup).resetStatus(); ((StdPDPGroup) group).resetStatus(); // Notify the Admin Consoles that something changed // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so // just notify on that notifyAC(); // Need to notify the PDP that it's config may have changed pdpChanged(pdp); return; } } catch (PAPException e) { logger.error("AC POST exception: " + e, e); response.sendError(500, e.getMessage()); return; } }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private void processAccountUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w ww. j a v a 2 s. c o m*/ Document xmldoc = readXmlRequest(req); String urlUsername = usernameFromPathInfo(req.getPathInfo()); User user = getLoggedInUser(); String oldUsername = user.getUsername(); Boolean oldAdmin = user.getAdmin(); Boolean oldLocked = user.isLocked(); UserResource resource = new UserResource(user, getUrlBase(req), xmldoc, entityFactory); if (user.isUsernameChanged()) { // reset logged in user's username user.setUsername(oldUsername); log.warn("bad request for account update: " + "username may not be changed"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Username may not be changed"); return; } if (user.isAdminChanged() && !oldAdmin) { // Non admin tried to change admin status user.setAdmin(oldAdmin); log.warn("bad request for account update: " + "non-admin may not change own admin status"); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Non admin may not change own admin status."); return; } if (user.isLocked() != oldLocked) { user.setLocked(oldLocked); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "User may not changed own locked status."); } userService.updateUser(user); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); resp.setHeader("ETag", resource.getEntityTag()); } catch (SAXException e) { log.warn("error parsing request body: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error parsing request body: " + e.getMessage()); return; } catch (CmpException e) { log.warn("bad request for account update: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (ModelValidationException e) { handleModelValidationError(resp, e); } catch (InvalidStateException ise) { handleInvalidStateException(resp, ise); } }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Process a POST request for the specified resource. * * @param req Description of the Parameter * @param resp Description of the Parameter * @throws IOException if an input/output error occurs * @throws ServletException if a servlet-specified error occurs *///w w w . j a v a2 s . c om protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String path = getRelativePath(req); // Retrieve the Catalina context // Retrieve the resources DirContext resources = getResources(); if (resources == null) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } boolean exists = true; try { resources.lookup(path); } catch (NamingException e) { exists = false; } if (exists) { boolean result = true; try { resources.unbind(path); } catch (NamingException e) { result = false; } if (result) { resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.dasein.cloud.nimbula.NimbulaMethod.java
@SuppressWarnings("unused") public @Nonnegative int put(@Nonnull String targetId, @Nonnull Map<String, Object> state) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + NimbulaMethod.class.getName() + ".put(" + targetId + "," + state + ")"); }//from w w w .j a v a 2 s. co m try { authenticate(); String target = getUrl(url, targetId); if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + target + " >--------------------------------------------------------------------------------------"); } try { ProviderContext ctx = cloud.getContext(); if (ctx == null) { throw new CloudException("No context was set for this request"); } HttpClient client = getClient(ctx, target.startsWith("https")); HttpPut put = new HttpPut(target); put.addHeader("Content-Type", "application/json"); put.setHeader("Cookie", authCookie); try { //noinspection deprecation put.setEntity( new StringEntity((new JSONObject(state)).toString(), "application/json", "UTF-8")); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); try { wire.debug(EntityUtils.toString(put.getEntity())); } catch (IOException ignore) { } wire.debug(""); } 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) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code != HttpServletResponse.SC_NO_CONTENT) { HttpEntity entity = response.getEntity(); if (entity != null) { try { this.response = EntityUtils.toString(entity); } catch (IOException e) { throw new CloudException(e); } if (wire.isDebugEnabled()) { wire.debug(this.response); wire.debug(""); } } checkResponse(response, code, this.response); } else { checkResponse(response, code); } return code; } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + url + "/ <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + NimbulaMethod.class.getName() + ".put()"); } } }
From source file:info.raack.appliancelabeler.web.MainController.java
/** * HTTP request handler for updating energy cost for an energy monitor. * @throws IOException /*from w w w.ja v a 2 s . co m*/ */ @RequestMapping(value = "/energy/monitor/{monitorId}", method = RequestMethod.POST) public void updateEnergyCost(@PathVariable(value = "monitorId") int energyMonitorId, @RequestParam(value = "costPerKwh") String costPerKwhStr, HttpServletRequest request, HttpServletResponse response) throws IOException { ModelMap model = new ModelMap(); // get current energymonitor // TODO - this should be updated to allow for multiple monitors EnergyMonitor energyMonitor = getCurrentEnergyMonitor(request, response); if (energyMonitor == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } else if (energyMonitor.getId() != energyMonitorId) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write("First energy monitor id " + energyMonitor.getId() + " does not match monitor id given of " + energyMonitorId); return; } try { float costPerKwh = Float.parseFloat(costPerKwhStr); database.setEnergyCost(energyMonitor, costPerKwh); response.setStatus(HttpServletResponse.SC_NO_CONTENT); } catch (NumberFormatException e) { // could not parse number response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write("Could not parse " + costPerKwhStr + " into a number"); } }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
public @Nullable String delete(@Nonnull String resource, @Nonnull String id) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER: " + vCloudMethod.class.getName() + ".delete(" + resource + "," + id + ")"); }/*www . j a v a 2 s. c o m*/ try { Org org = authenticate(false); String endpoint = toURL(resource, id); HttpClient client = null; if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [DELETE (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { client = getClient(false); HttpDelete delete = new HttpDelete(endpoint); delete.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(delete, org.token); if (wire.isDebugEnabled()) { wire.debug(delete.getRequestLine().toString()); for (Header header : delete.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "DELETE " + resource); response = client.execute(delete); 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_UNAUTHORIZED) { authenticate(true); return delete(resource, id); } else if (code != HttpServletResponse.SC_NOT_FOUND && code != HttpServletResponse.SC_NO_CONTENT && code != HttpServletResponse.SC_OK && code != HttpServletResponse.SC_ACCEPTED) { logger.error("DELETE request got unexpected " + 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); } else { 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; } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (wire.isDebugEnabled()) { wire.debug("<<< [DELETE (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT: " + vCloudMethod.class.getName() + ".delete()"); } } }
From source file:com.imaginary.home.cloud.CloudTest.java
@Test public void pushState() throws Exception { HashMap<String, Object> action = new HashMap<String, Object>(); action.put("action", "update"); HashMap<String, Object> relay = new HashMap<String, Object>(); ArrayList<Map<String, Object>> devices = new ArrayList<Map<String, Object>>(); {//from w ww .j a va 2 s . co m HashMap<String, Object> device = new HashMap<String, Object>(); device.put("systemId", "1"); device.put("deviceId", "1"); device.put("model", "A1234"); device.put("on", true); device.put("deviceType", "light"); device.put("name", "Test Light Bulb"); device.put("description", "A test light bulb for integration tests"); device.put("supportsColorChanges", true); device.put("supportsBrightnessChanges", true); device.put("colorModes", new ColorMode[] { ColorMode.RGB }); HashMap<String, Object> color = new HashMap<String, Object>(); color.put("colorMode", ColorMode.RGB.name()); color.put("components", new float[] { 100f, 0f, 0f }); device.put("color", color); devices.add(device); device = new HashMap<String, Object>(); device.put("systemId", "2"); device.put("deviceId", "1"); device.put("model", "XYZ999"); device.put("on", false); device.put("deviceType", "powered"); device.put("name", "Test Thing"); device.put("description", "A test thing that turns off and on"); devices.add(device); device.put("systemId", "2"); device.put("deviceId", "999"); device.put("model", "XYZ900"); device.put("on", false); device.put("deviceType", "powered"); device.put("name", "Manipulation Test"); device.put("description", "A test thing that turns off and on and will be manipulated by tests"); devices.add(device); } relay.put("devices", devices); action.put("relay", relay); HttpClient client = getClient(); HttpPut method = new HttpPut(cloudAPI + "/relay/" + relayKeyId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", relayKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(relayKeySecret.getBytes("utf-8"), "put:/relay/" + relayKeyId + ":" + relayKeyId + ":" + token + ":" + timestamp + ":" + VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(action)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_NO_CONTENT) { Header h = response.getFirstHeader("x-imaginary-has-commands"); boolean commands = false; if (h != null) { String val = h.getValue(); commands = val != null && val.equalsIgnoreCase("true"); } out("Commands waiting: " + commands); } else { Assert.fail("Failed to update state for relay (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); } }
From source file:org.opencastproject.workflow.endpoint.WorkflowRestService.java
@DELETE @Path("remove/{id}") @Produces(MediaType.TEXT_PLAIN)/* w w w .java 2s. c o m*/ @RestQuery(name = "remove", description = "Danger! Permenantly removes a workflow instance. This does not remove associated jobs, and there are potential harmful effects by removing a workflow. In most circumstances, /stop is what you should use.", returnDescription = "HTTP 204 No Content", pathParameters = { @RestParameter(name = "id", isRequired = true, description = "The workflow instance identifier", type = STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No Conent."), @RestResponse(responseCode = SC_NOT_FOUND, description = "No running workflow instance with that identifier exists.") }) public Response remove(@PathParam("id") long workflowInstanceId) throws WorkflowException, NotFoundException, UnauthorizedException { service.remove(workflowInstanceId); return Response.noContent().build(); }
From source file:org.opencastproject.adminui.endpoint.EmailEndpoint.java
@DELETE @Path("signature/{signatureId}") @Produces(MediaType.APPLICATION_JSON)/* w ww.jav a2 s .c om*/ @RestQuery(name = "deleteemailtemplate", description = "Deletes the email signature by the given id", returnDescription = "No content", pathParameters = { @RestParameter(name = "signatureId", description = "The signature id", isRequired = true, type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(description = "Email signature has been deleted", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "The email signature has not been found", responseCode = HttpServletResponse.SC_NOT_FOUND) }) public Response deleteEmailSignature(@PathParam("signatureId") long signatureId) throws NotFoundException { try { mailService.deleteMessageSignature(signatureId); return Response.noContent().build(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete the email signature {}: {}", signatureId, ExceptionUtils.getStackTrace(e)); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private void processUserUpdate(HttpServletRequest req, HttpServletResponse resp, User user) throws ServletException, IOException { try {/* w w w . j a v a2 s . c o m*/ Document xmldoc = readXmlRequest(req); String urlUsername = usernameFromPathInfo(req.getPathInfo()); UserResource resource = new UserResource(user, getUrlBase(req), xmldoc, entityFactory); userService.updateUser(user); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); resp.setHeader("ETag", resource.getEntityTag()); if (!user.getUsername().equals(urlUsername)) { resp.setHeader("Content-Location", resource.getUserUrl()); } } catch (SAXException e) { log.warn("error parsing request body: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error parsing request body: " + e.getMessage()); return; } catch (CmpException e) { log.warn("bad request for user update: " + e.getMessage()); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (ModelValidationException e) { handleModelValidationError(resp, e); } catch (InvalidStateException ise) { handleInvalidStateException(resp, ise); } }