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.opencastproject.adminui.endpoint.EmailEndpoint.java
@POST @Path("preview/{templateId}") @Produces(MediaType.APPLICATION_JSON)// w w w . j a v a2s. com @RestQuery(name = "previewmail", description = "Render a mail with the current email configuration for reviewing it", returnDescription = "The renderend message as JSON", pathParameters = { @RestParameter(name = "templateId", description = "The template id", isRequired = true, type = RestParameter.Type.INTEGER) }, restParameters = { @RestParameter(name = "eventIds", description = "A comma separated list of event ids", isRequired = true, type = RestParameter.Type.TEXT), @RestParameter(name = "personIds", description = "A comma separated list of person ids", isRequired = true, type = RestParameter.Type.TEXT), @RestParameter(name = "signature", description = "Whether to include the signature", isRequired = false, type = RestParameter.Type.BOOLEAN), @RestParameter(name = "body", description = "The optional message body", isRequired = false, type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(description = "No recording or person ids have been set!", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "No message signature is configured or no PM user to perform this action!", responseCode = HttpServletResponse.SC_PRECONDITION_FAILED), @RestResponse(description = "Email has been sent", responseCode = HttpServletResponse.SC_NO_CONTENT) }) public Response previewMail(@PathParam("templateId") long template, @FormParam("eventIds") String eventIdsString, @FormParam("personIds") String personIdsString, @FormParam("signature") @DefaultValue("false") boolean signature, @FormParam("subject") String subject, @FormParam("body") String body) { if (participationDatabase == null) return Response.status(Status.SERVICE_UNAVAILABLE).build(); final Monadics.ListMonadic<String> eventIds = splitCommaSeparatedParam(option(eventIdsString)); final Monadics.ListMonadic<Long> personIds = splitCommaSeparatedParam(option(personIdsString)).map(toLong); if (eventIds.value().isEmpty() || personIds.value().isEmpty()) return badRequest(); Person creator; try { creator = participationDatabase.getPerson(securityService.getUser().getEmail()); } catch (Exception e) { logger.error("No valid participation managment user found for preview this mail! {}", ExceptionUtils.getStackTrace(e)); return Response.status(Status.PRECONDITION_FAILED).build(); } try { List<Recording> recordings = ParticipationUtils.getRecordingsByEventId(schedulerService, participationDatabase, eventIds.value()); List<Person> recipients = getPersonById(personIds.value()); MessageTemplate messageTemplate = mailService.getMessageTemplate(template); if (StringUtils.isNotBlank(body)) messageTemplate.setBody(body); MessageSignature messageSignature = null; if (signature) { try { messageSignature = mailService.getCurrentUsersSignature(); } catch (NotFoundException e) { return Response.status(Status.PRECONDITION_FAILED).build(); } if (messageSignature == null) return Response.status(Status.PRECONDITION_FAILED).build(); } else { // Create an empty message signature. messageSignature = new MessageSignature(0L, creator.getName(), securityService.getUser(), new EmailAddress(creator.getEmail(), creator.getName()), Option.<EmailAddress>none(), "", new Date(), (new ArrayList<Comment>())); } messageTemplate .setBody(messageTemplate.getBody().concat("\r\n").concat(messageSignature.getSignature())); Message message = new Message(creator, messageTemplate, messageSignature, signature); List<Val> renderArr = new ArrayList<Jsons.Val>(); for (Person recipient : recipients) { renderArr.add(Jsons.v(emailSender.renderInvitationBody(message, recordings, recipient))); } return Response.ok(Jsons.arr(renderArr).toJson()).build(); } catch (Exception e) { logger.error("Could not create a preview email: {}", ExceptionUtils.getStackTrace(e)); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } }
From source file:ORG.oclc.os.SRW.SRWServlet.java
/** * write a message to the response, set appropriate headers for content * type..etc./*from ww w . j a v a 2 s . c o m*/ * @param clientVersion client protocol, one of the HTTPConstants strings * @param res response * @param responseMsg message to write * @throws AxisFault * @throws IOException if the response stream can not be written to */ private void sendResponse(final String clientVersion, String contentType, HttpServletResponse res, Message responseMsg) throws AxisFault, IOException { if (responseMsg == null) { res.setStatus(HttpServletResponse.SC_NO_CONTENT); if (isDebug) servletLog.debug("NO AXIS MESSAGE TO RETURN!"); //String resp = Messages.getMessage("noData00"); //res.setContentLength((int) resp.getBytes().length); //res.getWriter().print(resp); } else { if (isDebug) { servletLog.debug("Returned Content-Type:" + contentType); // log.debug("Returned Content-Length:" + // responseMsg.getContentLength()); } try { res.setContentType(contentType); /* My understand of Content-Length * HTTP 1.0 * -Required for requests, but optional for responses. * HTTP 1.1 * - Either Content-Length or HTTP Chunking is required. * Most servlet engines will do chunking if content-length is not specified. * * */ //if(clientVersion == HTTPConstants.HEADER_PROTOCOL_V10) //do chunking if necessary. // res.setContentLength(responseMsg.getContentLength()); responseMsg.writeTo(res.getOutputStream()); } catch (SOAPException e) { logException(e); } } if (!res.isCommitted()) { res.flushBuffer(); // Force it right now. } }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
protected @Nullable String putHeaders(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull Map<String, String> customHeaders) 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() + ".putHeaders(" + authToken + "," + endpoint + "," + resource + "," + customHeaders + ")"); }/*from ww w. j ava2 s . c om*/ if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } try { HttpClient client = getClient(); HttpPut put = new HttpPut(endpoint + resource); put.addHeader("Content-Type", "application/json"); put.addHeader("X-Auth-Token", authToken); if (customHeaders != null) { for (Map.Entry<String, String> entry : customHeaders.entrySet()) { String val = (entry.getValue() == null ? "" : entry.getValue()); put.addHeader(entry.getKey(), val); } } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } 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) { 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); if (code != HttpServletResponse.SC_CREATED && code != HttpServletResponse.SC_ACCEPTED && code != HttpServletResponse.SC_NO_CONTENT) { std.error("putString(): Expected CREATED, ACCEPTED, or NO CONTENT for put request, got " + code); HttpEntity entity = response.getEntity(); String json = null; if (entity != null) { try { json = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(json); wire.debug(""); } } catch (IOException e) { throw new CloudException(e); } } RackspaceException.ExceptionItems items = (json == null ? null : RackspaceException.parseException(code, json)); if (items == null) { items = new RackspaceException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } std.error("putString(): [" + code + " : " + items.message + "] " + items.details); throw new RackspaceException(items); } else { if (code == HttpServletResponse.SC_ACCEPTED || code == HttpServletResponse.SC_CREATED) { 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 - " + AbstractMethod.class.getName() + ".putString()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
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 www . j a v a 2 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 * @param timezone * The timezone of the capture device * @return A JSON object with the list of conflicting events */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("conflicts.json") @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 JSON", 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 getConflictingEventsJSON(@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, true); }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private static void handleContainerDelete(HttpServletResponse response, BlobStore blobStore, String containerName) throws IOException, S3Exception { if (!blobStore.containerExists(containerName)) { throw new S3Exception(S3ErrorCode.NO_SUCH_BUCKET); }//from ww w . ja v a2 s .c o m String blobStoreType = getBlobStoreType(blobStore); if (blobStoreType.equals("b2")) { // S3 allows deleting a container with in-progress MPU while B2 does // not. Explicitly cancel uploads for B2. for (MultipartUpload mpu : blobStore.listMultipartUploads(containerName)) { blobStore.abortMultipartUpload(mpu); } } if (!blobStore.deleteContainerIfEmpty(containerName)) { throw new S3Exception(S3ErrorCode.BUCKET_NOT_EMPTY); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java
@DELETE @Path("{eventId}/comment/{commentId}") @Produces(MediaType.APPLICATION_JSON)/*from www.jav a 2s . c o m*/ @RestQuery(name = "deleteeventcomment", description = "Deletes a event related comment by its identifier", returnDescription = "No content", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "commentId", description = "The comment id", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "The event related comment has been deleted.", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "No event or comment with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }) public Response deleteEventComment(@PathParam("eventId") String eventId, @PathParam("commentId") long commentId) throws NotFoundException, Exception { Opt<Event> optEvent = getEvent(eventId); if (optEvent.isNone()) return notFound("Cannot find an event with id '%s'.", eventId); try { getEventCommentService().deleteComment(eventId, commentId); List<Comment> comments = getEventCommentService().getComments(eventId); updateCommentCatalog(optEvent.get(), comments); return Response.noContent().build(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Unable to delete comment {} on event {}: {}", new String[] { Long.toString(commentId), eventId, ExceptionUtils.getStackTrace(e) }); throw new WebApplicationException(e); } }
From source file:org.opencastproject.adminui.endpoint.EmailEndpoint.java
@POST @Path("send/{templateId}") @Produces(MediaType.APPLICATION_JSON)//from w w w .j av a2 s. com @RestQuery(name = "sendmail", description = "Render an email with the current email configuration for reviewing it", returnDescription = "The renderend message as JSON", pathParameters = { @RestParameter(name = "templateId", description = "The template id", isRequired = true, type = RestParameter.Type.INTEGER) }, restParameters = { @RestParameter(name = "eventIds", description = "A comma separated list of event ids", isRequired = true, type = RestParameter.Type.TEXT), @RestParameter(name = "personIds", description = "A comma separated list of person ids", isRequired = true, type = RestParameter.Type.TEXT), @RestParameter(name = "signature", description = "Whether to include the signature", isRequired = false, type = RestParameter.Type.BOOLEAN), @RestParameter(name = "subject", description = "The optional message subject", isRequired = false, type = RestParameter.Type.STRING), @RestParameter(name = "body", description = "The optional message body", isRequired = false, type = RestParameter.Type.TEXT), @RestParameter(name = "store", description = "Whether to store the message to the audit trail", isRequired = false, type = RestParameter.Type.BOOLEAN) }, reponses = { @RestResponse(description = "No recording or person ids have been set!", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "No message signature is configured or no PM user to perform this action!", responseCode = HttpServletResponse.SC_PRECONDITION_FAILED), @RestResponse(description = "Email has been sent", responseCode = HttpServletResponse.SC_NO_CONTENT) }) public Response sendMail(@PathParam("templateId") long template, @FormParam("eventIds") String eventIdsString, @FormParam("personIds") String personIdsString, @FormParam("signature") @DefaultValue("false") boolean signature, @FormParam("subject") String subject, @FormParam("body") String body, @FormParam("store") @DefaultValue("false") boolean store) { if (participationDatabase == null) return Response.status(Status.SERVICE_UNAVAILABLE).build(); final Monadics.ListMonadic<String> eventIds = splitCommaSeparatedParam(option(eventIdsString)); final Monadics.ListMonadic<Long> personIds = splitCommaSeparatedParam(option(personIdsString)).map(toLong); if (eventIds.value().isEmpty() || personIds.value().isEmpty()) return badRequest(); Person creator; try { creator = participationDatabase.getPerson(securityService.getUser().getEmail()); } catch (Exception e) { logger.error("No valid participation management user found for sending this mail!"); return Response.status(Status.PRECONDITION_FAILED).build(); } try { List<Recording> recordings = ParticipationUtils.getRecordingsByEventId(schedulerService, participationDatabase, eventIds.value()); List<Person> recipients = getPersonById(personIds.value()); MessageTemplate messageTemplate = mailService.getMessageTemplate(template); if (StringUtils.isNotBlank(subject)) messageTemplate.setSubject(subject); if (StringUtils.isNotBlank(body)) messageTemplate.setBody(body); MessageSignature messageSignature = mailService.getCurrentUsersSignature(); if (messageSignature == null) return Response.status(Status.PRECONDITION_FAILED).build(); Message message = new Message(creator, messageTemplate, messageSignature, signature); emailSender.sendMessagesForRecordings(recordings, recipients, message, store); for (String eventId : eventIds.value()) { try { schedulerService.updateReviewStatus(eventId, ReviewStatus.UNCONFIRMED); } catch (Exception e) { logger.error("Unable to update review status of event {}", eventId); continue; } } return Response.noContent().build(); } catch (Exception e) { logger.error("Could not update the email configuration: {}", 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 delete/remove items * * @param request/*from w w w. j av a 2s .c o m*/ * @param response * @param groupId * @throws ServletException * @throws java.io.IOException */ private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId) throws ServletException, IOException { try { // for all DELETE 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("policy") != null) { // group=<groupId> policy=<policyId> [delete=<true|false>] <= delete policy file from group // TODO logger.error("UNIMPLEMENTED "); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); return; } else if (request.getParameter("pdpId") != null) { // ARGS: group=<groupId> pdpId=<pdpId> <= delete PDP String pdpId = request.getParameter("pdpId"); PDP pdp = papEngine.getPDP(pdpId); papEngine.removePDP(pdp); // adjust the status of the group, which may have changed when we removed this PDP ((StdPDPGroup) group).resetStatus(); response.setStatus(HttpServletResponse.SC_NO_CONTENT); notifyAC(); // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP // Requests) pdpChanged(pdp); return; } else if (request.getParameter("pipId") != null) { // group=<groupId> pipId=<pipEngineId> <= delete PIP config for given engine // TODO logger.error("UNIMPLEMENTED "); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); return; } else { // ARGS: group=<groupId> movePDPsToGroupId=<movePDPsToGroupId> <= delete a group and move all // its PDPs to the given group String moveToGroupId = request.getParameter("movePDPsToGroupId"); PDPGroup moveToGroup = null; if (moveToGroupId != null) { moveToGroup = papEngine.getGroup(moveToGroupId); } // get list of PDPs in the group being deleted so we can notify them that they got changed Set<PDP> movedPDPs = new HashSet<PDP>(); movedPDPs.addAll(group.getPdps()); // do the move/remove papEngine.removeGroup(group, moveToGroup); response.setStatus(HttpServletResponse.SC_NO_CONTENT); notifyAC(); // notify any PDPs in the removed set that their config may have changed for (PDP pdp : movedPDPs) { pdpChanged(pdp); } return; } } catch (PAPException e) { logger.error("AC DELETE exception: " + e, e); response.sendError(500, e.getMessage()); return; } }
From source file:com.google.ratel.util.RatelUtils.java
public static void writeContent(HttpServletResponse response, String content, String contentType) { try {/* w w w . ja v a 2s . co m*/ RatelHttpServletResponse ratelResponse = null; if (response instanceof RatelHttpServletResponse) { ratelResponse = (RatelHttpServletResponse) response; } if (response.getContentType() == null) { response.setContentType(contentType); } if (content == null) { if (ratelResponse != null && ratelResponse.isStatusSettable()) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } return; } PrintWriter writer = response.getWriter(); IOUtils.write(content, writer); } catch (Exception e) { throw new RuntimeException(e); } }