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:de.thm.arsnova.controller.SessionController.java
@RequestMapping(value = "/", method = RequestMethod.GET) public List<Session> getSessions( @RequestParam(value = "ownedonly", defaultValue = "false") final boolean ownedOnly, @RequestParam(value = "visitedonly", defaultValue = "false") final boolean visitedOnly, @RequestParam(value = "sortby", defaultValue = "name") final String sortby, final HttpServletResponse response) { List<Session> sessions = null; /* TODO implement all parameter combinations, implement use of user parameter */ try {//from w w w . j a v a 2 s.c om if (ownedOnly && !visitedOnly) { sessions = sessionService.getMySessions(); } else if (visitedOnly && !ownedOnly) { sessions = sessionService.getMyVisitedSessions(); } else { response.setStatus(HttpStatus.NOT_IMPLEMENTED.value()); return null; } } catch (final AccessDeniedException e) { throw new UnauthorizedException(); } if (sessions == null || sessions.isEmpty()) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); return null; } if (sortby != null && sortby.equals("shortname")) { Collections.sort(sessions, new SessionShortNameComparator()); } else { Collections.sort(sessions, new SessionNameComparator()); } return sessions; }
From source file:org.ednovo.gooru.controllers.v1.api.TaxonomyCourseRestController.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_COURSE_DELETE }) @RequestMapping(value = RequestMappingUri.ID, method = RequestMethod.DELETE) public void deleteCourse(@PathVariable(value = ID) Integer courseId, HttpServletRequest request, HttpServletResponse response) {// www . java 2 s. c o m getTaxonomyCourseService().deleteTaxonomyCourse(courseId); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:com.aaasec.sigserv.csspserver.SpServlet.java
/** * Processes requests for both HTTP// w w w . j a v a2 s .c o m * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); SpSession session = getSession(request, response); RequestModel req = reqFactory.getRequestModel(request, session); AuthData authdata = req.getAuthData(); // Supporting devmode login if (SpModel.isDevmode()) { authdata = TestIdentities.getTestID(request, req); req.setAuthData(authdata); if (authdata.getAuthType().length() == 0) { authdata.setAuthType("devlogin"); } session.setIdpEntityId(authdata.getIdpEntityID()); session.setSignerAttribute(RequestModelFactory.getAttrOidString(authdata.getIdAttribute())); session.setSignerId(authdata.getId()); } //Terminate if no valid request data if (req == null) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); response.getWriter().write(""); return; } // Handle form post from web page boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { response.getWriter().write(SpServerLogic.processFileUpload(request, response, req)); return; } // Handle auth data request if (req.getAction().equals("authdata")) { response.setContentType("application/json"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(gson.toJson(authdata)); return; } // Get list of serverstored xml documents if (req.getAction().equals("doclist")) { response.setContentType("application/json"); response.getWriter().write(SpServerLogic.getDocList()); return; } // Provide info about the session for logout handling if (req.getAction().equals("logout")) { response.setContentType("application/json"); Logout lo = new Logout(); lo.authType = (request.getAuthType() == null) ? "" : request.getAuthType(); lo.devmode = String.valueOf(SpModel.isDevmode()); response.getWriter().write(gson.toJson(lo)); return; } // Respons to a client alive check to test if the server session is alive if (req.getAction().equals("alive")) { response.setContentType("application/json"); response.getWriter().write("[]"); return; } // Handle sign request and return Xhtml form with post data to the signature server if (req.getAction().equals("sign")) { boolean addSignMessage = (req.getParameter().equals("message")); String xhtml = SpServerLogic.prepareSignRedirect(req, addSignMessage); response.getWriter().write(xhtml); return; } // Get status data about the current session if (req.getAction().equals("status")) { response.setContentType("application/json"); response.getWriter().write(gson.toJson(session.getStatus())); return; } // Handle a declined sign request if (req.getAction().equals("declined")) { if (SpModel.isDevmode()) { response.sendRedirect("index.jsp?declined=true"); return; } response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp?declined=true"); return; } // Return Request and response data as a file. if (req.getAction().equalsIgnoreCase("getReqRes")) { response.setContentType("text/xml;charset=UTF-8"); byte[] data = TestCases.getRawData(req); BufferedInputStream fis = new BufferedInputStream(new ByteArrayInputStream(data)); ServletOutputStream output = response.getOutputStream(); if (req.getParameter().equalsIgnoreCase("download")) { response.setHeader("Content-Disposition", "attachment; filename=" + req.getId() + ".xml"); } int readBytes = 0; byte[] buffer = new byte[10000]; while ((readBytes = fis.read(buffer, 0, 10000)) != -1) { output.write(buffer, 0, readBytes); } output.flush(); output.close(); fis.close(); return; } // Return the signed document if (req.getAction().equalsIgnoreCase("getSignedDoc") || req.getAction().equalsIgnoreCase("getUnsignedDoc")) { // If the request if for a plaintext document, or only if the document has a valid signature if (session.getStatus().signedDocValid || req.getAction().equalsIgnoreCase("getUnsignedDoc")) { response.setContentType(session.getDocumentType().getMimeType()); switch (session.getDocumentType()) { case XML: response.getWriter().write(new String(session.getSignedDoc(), Charset.forName("UTF-8"))); return; case PDF: File docFile = session.getDocumentFile(); if (req.getAction().equalsIgnoreCase("getSignedDoc") && session.getStatus().signedDocValid) { docFile = session.getSigFile(); } FileInputStream fis = new FileInputStream(docFile); ServletOutputStream output = response.getOutputStream(); if (req.getParameter().equalsIgnoreCase("download")) { response.setHeader("Content-Disposition", "attachment; filename=" + "signedPdf.pdf"); } int readBytes = 0; byte[] buffer = new byte[10000]; while ((readBytes = fis.read(buffer, 0, 10000)) != -1) { output.write(buffer, 0, readBytes); } output.flush(); output.close(); fis.close(); return; } return; } else { if (SpModel.isDevmode()) { response.sendRedirect("index.jsp"); return; } response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp"); return; } } // Process a sign response from the signature server if (req.getSigResponse().length() > 0) { try { byte[] sigResponse = Base64Coder.decode(req.getSigResponse().trim()); // Handle response SpServerLogic.completeSignedDoc(sigResponse, req); } catch (Exception ex) { } if (SpModel.isDevmode()) { response.sendRedirect("index.jsp"); return; } response.sendRedirect("https://eid2cssp.3xasecurity.com/sign/index.jsp"); return; } // Handle testcases if (req.getAction().equals("test")) { boolean addSignMessage = (req.getParameter().equals("message")); String xhtml = TestCases.prepareTestRedirect(request, response, req, addSignMessage); respond(response, xhtml); return; } // Get test data for display such as request data, response data, certificates etc. if (req.getAction().equals("info")) { switch (session.getDocumentType()) { case PDF: File returnFile = null; if (req.getId().equalsIgnoreCase("document")) { respond(response, getDocIframe("getUnsignedDoc", needPdfDownloadButton(request))); } if (req.getId().equalsIgnoreCase("formSigDoc")) { respond(response, getDocIframe("getSignedDoc", needPdfDownloadButton(request))); } respond(response, TestCases.getTestData(req)); return; default: respond(response, TestCases.getTestData(req)); return; } } if (req.getAction().equals("verify")) { response.setContentType("text/xml;charset=UTF-8"); String sigVerifyReport = TestCases.getTestData(req); if (sigVerifyReport != null) { respond(response, sigVerifyReport); return; } } nullResponse(response); }
From source file:de.tu_dortmund.ub.hb_ng.middleware.MiddlewareHbNgEndpoint.java
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { // CORS ORIGIN RESPONSE HEADER httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER)); String authorization = ""; String contenttype = ""; Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerNameKey = headerNames.nextElement(); this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = " + httpServletRequest.getHeader(headerNameKey)); if (headerNameKey.equals("Authorization")) { authorization = httpServletRequest.getHeader(headerNameKey); }//from w ww .j a va2s.c om if (headerNameKey.equals("Content-Type")) { contenttype = httpServletRequest.getHeader(headerNameKey); } } this.logger.info("contenttype = " + contenttype); try { // TODO validate Content-Type String data = httpServletRequest.getReader().lines() .collect(Collectors.joining(System.lineSeparator())); if (data == null || data.equals("")) { this.logger.error(HttpServletResponse.SC_NO_CONTENT + " - No Content"); httpServletResponse.sendError(HttpServletResponse.SC_NO_CONTENT, "No Content"); } else { String postableData = null; // TODO bind interface Preprocessing if (Lookup.lookupAll(PreprocessingInterface.class).size() > 0) { PreprocessingInterface preprocessingInterface = Lookup.lookup(PreprocessingInterface.class); // init Authorization Service preprocessingInterface.init(this.config); postableData = preprocessingInterface.process(data); } else { // TODO correct error handling this.logger.error("[" + this.config.getProperty("service.name") + "] " + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } if (postableData != null) { // TODO if successful then POST as application/sparql-update to LinkedDataPlatform String sparql_url = this.config.getProperty("ldp.sparql-endpoint"); // HTTP Request int timeout = Integer.parseInt(this.config.getProperty("ldp.timeout")); RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build(); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultRequestConfig(defaultRequestConfig).build(); try { HttpPost httpPost = new HttpPost(sparql_url); httpPost.addHeader("Content-Type", "application/sparql-update"); httpPost.addHeader("Authorization", this.config.getProperty("ldp.authorization")); httpPost.setEntity(new StringEntity(postableData)); CloseableHttpResponse httpResponse = null; long start = System.nanoTime(); try { httpResponse = httpclient.execute(httpPost); } catch (ConnectTimeoutException | SocketTimeoutException e) { this.logger.info("[" + this.getClass().getName() + "] " + e.getClass().getName() + ": " + e.getMessage()); httpResponse = httpclient.execute(httpPost); } long elapsed = System.nanoTime() - start; this.logger.info("[" + this.getClass().getName() + "] LDP request - " + (elapsed / 1000.0 / 1000.0 / 1000.0) + " s"); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); // TODO httpServletResponse.setStatus(statusCode); httpServletResponse.getWriter().println(httpResponse.getStatusLine().getReasonPhrase()); EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } finally { httpclient.close(); } } } } catch (Exception e) { this.logger.error("something went wrong", e); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "something went wrong"); } }
From source file:org.osaf.cosmo.mc.MorseCodeServlet.java
/** * Handles delete requests./*w w w .j ava 2s .co m*/ */ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (log.isDebugEnabled()) log.debug("handling DELETE for " + req.getPathInfo()); CollectionPath cp = CollectionPath.parse(req.getPathInfo()); if (cp != null) { try { controller.deleteCollection(cp.getUid()); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } catch (CosmoSecurityException e) { if (e instanceof ItemSecurityException) { InsufficientPrivilegesException ipe = new InsufficientPrivilegesException( (ItemSecurityException) e); handleGeneralException(ipe, resp); } else { resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } } catch (MorseCodeException e) { handleGeneralException(e, resp); return; } catch (RuntimeException e) { handleGeneralException(new MorseCodeException(e), resp); return; } } resp.setStatus(HttpServletResponse.SC_NOT_FOUND); }
From source file:org.dasein.cloud.rackspace.AbstractMethod.java
public synchronized @Nullable AuthenticationContext authenticate() 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() + ".authenticate()"); }//from w ww .jav a 2s. c o m if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------> " + provider.getEndpoint()); wire.debug(""); } try { ProviderContext ctx = provider.getContext(); HttpClient client = getClient(); HttpGet get = new HttpGet(provider.getEndpoint()); try { get.addHeader("Content-Type", "application/json"); get.addHeader("X-Auth-User", new String(ctx.getAccessPublic(), "utf-8")); get.addHeader("X-Auth-Key", new String(ctx.getAccessPrivate(), "utf-8")); } catch (UnsupportedEncodingException e) { std.error("authenticate(): Unsupported encoding when building request headers: " + e.getMessage()); if (std.isTraceEnabled()) { e.printStackTrace(); } throw new InternalException(e); } if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { 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) { 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_NO_CONTENT) { if (code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED) { return null; } std.error("authenticate(): Expected NO CONTENT for an authentication 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; if (json == null) { items = RackspaceException.parseException(code, "{}"); } else { items = RackspaceException.parseException(code, json); } if (items.type.equals(CloudErrorType.AUTHENTICATION)) { return null; } std.error("authenticate(): [" + code + " : " + items.message + "] " + items.details); throw new RackspaceException(items); } else { AuthenticationContext authContext = new AuthenticationContext(); for (Header h : response.getAllHeaders()) { if (h.getName().equalsIgnoreCase("x-auth-token")) { authContext.setAuthToken(h.getValue().trim()); } else if (h.getName().equalsIgnoreCase("x-server-management-url")) { authContext.setServerUrl(h.getValue().trim()); } else if (h.getName().equalsIgnoreCase("x-storage-url")) { authContext.setStorageUrl(h.getValue().trim()); } else if (h.getName().equalsIgnoreCase("x-cdn-management-url")) { authContext.setCdnUrl(h.getValue().trim()); } else if (h.getName().equalsIgnoreCase("x-storage-token")) { authContext.setStorageToken(h.getValue().trim()); } } if (authContext.getAuthToken() == null) { std.warn("authenticate(): No authentication token in response"); throw new CloudException("No authentication token in cloud response"); } return authContext; } } finally { if (std.isTraceEnabled()) { std.trace("exit - " + AbstractMethod.class.getName() + ".authenticate()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> " + provider.getEndpoint()); } } }
From source file:com.sap.dirigible.runtime.registry.RepositoryServlet.java
@Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String repositoryPath = null; final OutputStream out = response.getOutputStream(); try {//from w w w. j av a 2 s . c o m repositoryPath = extractRepositoryPath(request); IEntity entity = getEntity(repositoryPath, request); if (entity == null) { doPost(request, response); } else { if (entity instanceof IResource) { ByteArrayOutputStream buff = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), buff); byte[] data = buff.toByteArray(); IResource resource = (IResource) entity; resource.setContent(data); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, THERE_IS_AN_EXISTING_COLLECTION_AT_THE_SAME_LOCATION); } } } catch (IllegalArgumentException ex) { logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()); } catch (MissingResourceException ex) { logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage()); response.sendError(HttpServletResponse.SC_NO_CONTENT, ex.getMessage()); } finally { out.flush(); out.close(); } }
From source file:org.opencastproject.inspection.impl.endpoints.MediaInspectionRestEndpoint.java
@POST @Produces(MediaType.TEXT_XML)// w ww. j a v a 2 s. c o m @Path("enrich") @RestQuery(name = "enrich", description = "Analyze and add missing metadata of a given media file, returning a receipt to check on the status and outcome of the job.", restParameters = { @RestParameter(description = "MediaPackage Element, that should be enriched with metadata ", isRequired = true, name = "mediaPackageElement", type = RestParameter.Type.TEXT), @RestParameter(description = "Should the existing metadata values remain", isRequired = true, name = "override", type = RestParameter.Type.BOOLEAN) }, reponses = { @RestResponse(description = "XML encoded receipt is returned.", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "Service unavailabe or not currently present", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE), @RestResponse(description = "Problem retrieving media file or invalid media file or URL.", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "") public Response enrichTrack(@FormParam("mediaPackageElement") String mediaPackageElement, @FormParam("override") boolean override) { checkNotNull(service); try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.parse(IOUtils.toInputStream(mediaPackageElement, "UTF-8")); MediaPackageElement mpe = MediaPackageElementBuilderFactory.newInstance().newElementBuilder() .elementFromManifest(doc.getDocumentElement(), new DefaultMediaPackageSerializerImpl()); Job job = service.enrich(mpe, override); return Response.ok(new JaxbJob(job)).build(); } catch (Exception e) { logger.info(e.getMessage(), e); return Response.serverError().build(); } }
From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java
/** * {@inheritDoc}//from w w w . j a v a 2 s .c o m */ @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // only handle requests to / if (!target.equals("/webhook")) { return; } // verify whether the call comes directly from GitHub using the X-GitHub-Event, // X-Hub-Signature and X-GitHub-Delivery headers String eventType = request.getHeader("X-GitHub-Event"); String signature = request.getHeader("X-Hub-Signature"); String deliveryId = request.getHeader("X-GitHub-Delivery"); if (eventType == null || eventType.isEmpty() || (this.secret != null && (signature == null || signature.isEmpty())) || deliveryId == null || deliveryId.isEmpty()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); baseRequest.setHandled(true); return; } if (signature != null) { // strip sha1= // TODO: Decide upon signature method based on this parameter signature = signature.substring(5); } logger.info("Processing GitHub request " + deliveryId + "."); // decode the data passed in the request body String data; try (InputStream inputStream = request.getInputStream()) { data = new String(ByteStreams.toByteArray(inputStream), Charset.forName(request.getCharacterEncoding())); } // verify the signature supplied to us (as long as a secret key was configured) try { if (!verifySignature(data, signature)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); baseRequest.setHandled(true); return; } } catch (IllegalStateException ex) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); baseRequest.setHandled(true); return; } // find correct event message eventType = eventType.replace('_', '.'); // de-serialize and handle event data Map<String, Object> context = new HashMap<>(); context.put("color", COLOR_MAP); context.put("event", reader.readValue(data)); String message = this.getMessage(eventType, context); if (message != null) { this.bridge.sendMessage(message); } // answer with 204 at all times response.setStatus(HttpServletResponse.SC_NO_CONTENT); baseRequest.setHandled(true); }
From source file:netinf.node.cache.peerside.PeersideServlet.java
@Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String elementKey = req.getPathInfo(); if (elementKey.startsWith("/") && elementKey.length() >= 1) { elementKey = elementKey.substring(1); }//from ww w. ja v a2 s .c o m if (elementKey.equals("*")) { cache.removeAll(); } else { cache.remove(elementKey); } resp.setStatus(HttpServletResponse.SC_NO_CONTENT); }