List of usage examples for javax.servlet.http HttpServletResponse SC_CREATED
int SC_CREATED
To view the source code for javax.servlet.http HttpServletResponse SC_CREATED.
Click Source Link
From source file:com.sun.faban.harness.webclient.Deployer.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from www .j a va 2s .c o m*/ List<String> deployNames = new ArrayList<String>(); List<String> cantDeployNames = new ArrayList<String>(); List<String> errDeployNames = new ArrayList<String>(); List<String> invalidNames = new ArrayList<String>(); List<String> errHeaders = new ArrayList<String>(); List<String> errDetails = new ArrayList<String>(); String user = null; String password = null; boolean clearConfig = false; boolean hasPermission = true; // Check whether we have to return text or html boolean acceptHtml = false; String acceptHeader = request.getHeader("Accept"); if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0) acceptHtml = true; DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); StringWriter messageBuffer = new StringWriter(); PrintWriter messageWriter = new PrintWriter(messageBuffer); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("user".equals(fieldName)) { user = item.getString(); } else if ("password".equals(fieldName)) { password = item.getString(); } else if ("clearconfig".equals(fieldName)) { String value = item.getString(); clearConfig = Boolean.parseBoolean(value); } continue; } if (!"jarfile".equals(fieldName)) continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; if (Config.SECURITY_ENABLED) { if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0 || !Config.DEPLOY_USER.equals(user)) { hasPermission = false; break; } if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0 || !Config.DEPLOY_PASSWORD.equals(password)) { hasPermission = false; break; } } // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) { invalidNames.add(fileName); continue; } String deployName = fileName.substring(0, fileName.length() - 4); if (deployName.indexOf('.') > -1) { invalidNames.add(deployName); continue; } // Check if we can deploy benchmark or service. // If running or queued, we won't deploy benchmark. // If service being used by current run,we won't deploy service. if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) { cantDeployNames.add(deployName); continue; } File uploadFile = new File(Config.BENCHMARK_DIR, fileName); if (uploadFile.exists()) FileHelper.recursiveDelete(uploadFile); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } try { DeployUtil.processUploadedJar(uploadFile, deployName); } catch (Exception e) { messageWriter.println("\nError deploying " + deployName + ".\n"); e.printStackTrace(messageWriter); errDeployNames.add(deployName); continue; } deployNames.add(deployName); } if (clearConfig) for (String benchName : deployNames) DeployUtil.clearConfig(benchName); if (!hasPermission) response.setStatus(HttpServletResponse.SC_FORBIDDEN); else if (cantDeployNames.size() > 0) response.setStatus(HttpServletResponse.SC_CONFLICT); else if (errDeployNames.size() > 0) response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); else if (invalidNames.size() > 0) response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); else if (deployNames.size() > 0) response.setStatus(HttpServletResponse.SC_CREATED); else response.setStatus(HttpServletResponse.SC_NOT_FOUND); StringBuilder b = new StringBuilder(); if (deployNames.size() > 0) { if (deployNames.size() > 1) b.append("Benchmarks/services "); else b.append("Benchmark/service "); for (int i = 0; i < deployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) deployNames.get(i)); } b.append(" deployed."); errHeaders.add(b.toString()); b.setLength(0); } if (invalidNames.size() > 0) { if (invalidNames.size() > 1) b.append("Invalid deploy files "); else b.append("Invalid deploy file "); for (int i = 0; i < invalidNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) invalidNames.get(i)); } b.append(". Deploy files must have .jar extension."); errHeaders.add(b.toString()); b.setLength(0); } if (cantDeployNames.size() > 0) { if (cantDeployNames.size() > 1) b.append("Cannot deploy benchmarks/services "); else b.append("Cannot deploy benchmark/services "); for (int i = 0; i < cantDeployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) cantDeployNames.get(i)); } b.append(". Benchmark/services being used or " + "queued up for run."); errHeaders.add(b.toString()); b.setLength(0); } if (errDeployNames.size() > 0) { if (errDeployNames.size() > 1) { b.append("Error deploying benchmarks/services "); for (int i = 0; i < errDeployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) errDeployNames.get(i)); } } errDetails.add(messageBuffer.toString()); errHeaders.add(b.toString()); b.setLength(0); } if (!hasPermission) errHeaders.add("Permission denied!"); Writer writer = response.getWriter(); if (acceptHtml) writeHtml(request, writer, errHeaders, errDetails); else writeText(writer, errHeaders, errDetails); writer.flush(); writer.close(); } catch (ServletException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new ServletException(e); } }
From source file:com.cognitivabrasil.repositorio.web.FileController.java
@RequestMapping(value = "/{id}/thumbnail", method = RequestMethod.GET) public void getThumbnail(@PathVariable("id") Long id, HttpServletResponse response) throws IOException { if (id == null || id == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "O arquivo solicitado no foi encontrado."); } else {//w w w . ja va2 s . c o m String fileName = Config.FILE_PATH + id + "/thumbnail"; try { // get your file as InputStream InputStream is = new FileInputStream(new File(fileName)); response.setHeader("Content-Disposition", "attachment; filename= thumbnail" + id); response.setStatus(HttpServletResponse.SC_CREATED); // copy it to response's OutputStream IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); } catch (FileNotFoundException fe) { // get your file as InputStream InputStream is = new FileInputStream(new File(DEFAULT_THUMBNAIL_PATH)); response.setHeader("Content-Disposition", "attachment; filename=default-thumbnail.png"); response.setContentType(MediaType.IMAGE_PNG_VALUE); response.setStatus(HttpServletResponse.SC_CREATED); // copy it to response's OutputStream IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); LOG.error("Imagen solicitada no foi encontrada.", fe); } catch (IOException ex) { LOG.error("Error writing file to output stream. Filename was '" + fileName + "'"); throw ex; } } }
From source file:org.eclipse.userstorage.tests.util.USSServer.java
protected void updateBlob(HttpServletRequest request, HttpServletResponse response, File blobFile, File etagFile, boolean exists) throws IOException { String ifMatch = getETag(request, "If-Match"); if (exists) { String etag = IOUtil.readUTF(etagFile); if (StringUtil.isEmpty(ifMatch) || !ifMatch.equals(etag)) { response.setHeader("ETag", "\"" + etag + "\""); response.sendError(HttpServletResponse.SC_CONFLICT); return; }//from www . ja v a2 s .co m } String etag = UUID.randomUUID().toString(); IOUtil.mkdirs(blobFile.getParentFile()); FileOutputStream out = new FileOutputStream(blobFile); InputStream body = null; try { Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), "value"); body = (InputStream) requestObject.get("value"); IOUtil.copy(body, out); } finally { IOUtil.closeSilent(body); IOUtil.close(out); } IOUtil.writeUTF(etagFile, etag); response.setStatus(exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED); response.setHeader("ETag", "\"" + etag + "\""); }
From source file:org.apache.qpid.systest.rest.RestTestHelper.java
public void createGroup(String groupName, String groupProviderName) throws IOException { createGroup(groupName, groupProviderName, HttpServletResponse.SC_CREATED); }
From source file:org.bibsonomy.rest.RestServlet.java
/** * @param request// w w w. ja va 2 s .c om * the servletrequest * @param response * the servletresponse * @param method * httpMethod to use, see {@link HttpMethod} * @throws IOException */ private void handle(final HttpServletRequest request, final HttpServletResponse response, final HttpMethod method) throws IOException { log.debug("Incoming Request: " + method.name() + " " + request.getRequestURL() + " from IP " + request.getHeader("x-forwarded-for")); final long start = System.currentTimeMillis(); try { // validate the requesting user's authorization final LogicInterface logic = validateAuthorization(request); // parse the request object to retrieve a list with all items of the // http request final MultiPartRequestParser parser = new MultiPartRequestParser(request); // choose rendering format (defaults to xml) final RenderingFormat renderingFormat = RESTUtils.getRenderingFormatForRequest( request.getParameterMap(), request.getHeader(HeaderUtils.HEADER_ACCEPT), request.getContentType()); // create Context final Reader reader = RESTUtils.getInputReaderForStream(request.getInputStream(), REQUEST_ENCODING); final Context context = new Context(method, getPathInfo(request), renderingFormat, this.urlRenderer, reader, parser.getList(), logic, request.getParameterMap(), additionalInfos); // validate request context.canAccess(); // set some response headers final String userAgent = request.getHeader(HeaderUtils.HEADER_USER_AGENT); log.debug("[USER-AGENT] " + userAgent); response.setContentType(context.getContentType(userAgent)); response.setCharacterEncoding(RESPONSE_ENCODING); // send answer if (method.equals(HttpMethod.POST)) { // if a POST request completes successfully this means that a // resource has been created response.setStatus(HttpServletResponse.SC_CREATED); } else { response.setStatus(HttpServletResponse.SC_OK); } // just define an ByteArrayOutputStream to store all outgoing data final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream(); context.perform(cachingStream); /* * XXX: note: cachingStream.size() != * cachingStream.toString().length() !! the correct value is the * first one! */ response.setContentLength(cachingStream.size()); // some more logging log.debug("Size of output sent:" + cachingStream.size()); final long elapsed = System.currentTimeMillis() - start; log.debug("Processing time: " + elapsed + " ms"); cachingStream.writeTo(response.getOutputStream()); } catch (final AuthenticationException e) { log.warn(e.getMessage()); response.setHeader("WWW-Authenticate", "Basic realm=\"" + RestProperties.getInstance().getBasicRealm() + "\""); sendError(request, response, HttpURLConnection.HTTP_UNAUTHORIZED, e.getMessage()); } catch (final InternServerException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (final NoSuchResourceException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } catch (final BadRequestOrResponseException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (final AccessDeniedException e) { log.error(e.getMessage()); sendError(request, response, HttpServletResponse.SC_FORBIDDEN, e.getMessage()); } catch (final ResourceMovedException e) { log.error(e.getMessage()); /* * sending new location TODO: add date using */ response.setHeader("Location", urlRenderer.createHrefForResource(e.getUserName(), e.getNewIntraHash())); sendError(request, response, HttpServletResponse.SC_MOVED_PERMANENTLY, e.getMessage()); } catch (final DatabaseException e) { final StringBuilder returnMessage = new StringBuilder(""); for (final String hash : e.getErrorMessages().keySet()) { for (final ErrorMessage em : e.getErrorMessages(hash)) { log.error(em.toString()); returnMessage.append(em.toString() + "\n "); } } sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, returnMessage.toString()); } catch (final Exception e) { log.error(e, e); // well, lets fetch each and every error... sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.sakaiproject.nakamura.files.pool.NewCreateContentPoolServlet.java
@Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String userId = request.getRemoteUser(); RequestPathInfo rpi = request.getRequestPathInfo(); String poolId = rpi.getExtension(); String[] selectors = rpi.getSelectors(); String alternativeStream = null; if (selectors != null && selectors.length > 0) { alternativeStream = poolId;//from w ww . j a v a 2 s . c o m poolId = selectors[0]; } Session adminSession = null; try { // Grab an admin session so we can create files in the pool space. adminSession = sparseRepository.loginAdministrative(); AuthorizableManager authorizableManager = adminSession.getAuthorizableManager(); // We need the authorizable for the user node that we'll create under the file. Authorizable au = authorizableManager.findAuthorizable(userId); // Loop over all the parameters // All the ones that are files will be stored. int statusCode = HttpServletResponse.SC_BAD_REQUEST; boolean fileUpload = false; Map<String, Object> results = new HashMap<String, Object>(); for (Entry<String, RequestParameter[]> e : request.getRequestParameterMap().entrySet()) { for (RequestParameter p : e.getValue()) { if (!p.isFormField()) { // This is a file upload. // Generate an ID and store it. String fileName = FilenameUtils.getName(p.getFileName()); // IE still sends in an absolute path sometimes. FileParams params = new FileParams(); params.setCreator(userId); params.setFilename(fileName); params.setContentType(getContentType(p)); params.setInputStream(p.getInputStream()); params.setPoolID(poolId); params.setAlternativeStream(alternativeStream); File thisFile; boolean isNew = false; fileUpload = true; if (poolId == null) { thisFile = fileService.createFile(params); statusCode = HttpServletResponse.SC_CREATED; isNew = true; } else if (alternativeStream != null && alternativeStream .indexOf(FilesConstants.ALTERNATIVE_STREAM_SELECTOR_SEPARATOR) > 0) { thisFile = fileService.createAlternativeStream(params); statusCode = HttpServletResponse.SC_OK; } else { thisFile = fileService.updateFile(params); statusCode = HttpServletResponse.SC_OK; } results.put(fileName, ImmutableMap.of("poolId", thisFile.getPoolID(), "item", thisFile.getProperties())); notifyFileUploadHandlers(results, adminSession, thisFile.getPoolID(), p, au.getId(), isNew); } } } if (!fileUpload) { // not a file upload, ok, create an item and use all the request parameters, only // if there was no poolId specified if (poolId == null) { File streamlessFile = createStreamlessFile(request, userId); results.put(streamlessFile.getFilename(), ImmutableMap.of("poolId", streamlessFile.getPoolID(), "item", streamlessFile.getProperties())); statusCode = HttpServletResponse.SC_CREATED; } } this.authorizableCountChanger.notify(UserConstants.CONTENT_ITEMS_PROP, userId); // Make sure we're outputting proper json. if (statusCode == HttpServletResponse.SC_BAD_REQUEST) { response.setStatus(statusCode); } else { response.setStatus(statusCode); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); JSONWriter jsonWriter = new JSONWriter(response.getWriter()); ExtendedJSONWriter.writeValueMap(jsonWriter, results); } } catch (ClientPoolException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (StorageClientException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (AccessDeniedException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (JSONException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (StorageException e) { LOGGER.warn(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } finally { // Make sure we're logged out. try { if (adminSession != null) { adminSession.logout(); } } catch (ClientPoolException e) { LOGGER.warn(e.getMessage(), e); } } }
From source file:org.opendaylight.iotdm.onem2m.protocols.http.Onem2mHttpProvider.java
private int mapCoreResponseToHttpResponse(HttpServletResponse httpResponse, String rscString) { httpResponse.setHeader(Onem2m.HttpHeaders.X_M2M_RSC, rscString); switch (rscString) { case Onem2m.ResponseStatusCode.OK: return HttpServletResponse.SC_OK; case Onem2m.ResponseStatusCode.CREATED: return HttpServletResponse.SC_CREATED; case Onem2m.ResponseStatusCode.CHANGED: return HttpServletResponse.SC_OK; case Onem2m.ResponseStatusCode.DELETED: return HttpServletResponse.SC_OK; case Onem2m.ResponseStatusCode.NOT_FOUND: return HttpServletResponse.SC_NOT_FOUND; case Onem2m.ResponseStatusCode.OPERATION_NOT_ALLOWED: return HttpServletResponse.SC_METHOD_NOT_ALLOWED; case Onem2m.ResponseStatusCode.CONTENTS_UNACCEPTABLE: return HttpServletResponse.SC_BAD_REQUEST; case Onem2m.ResponseStatusCode.CONFLICT: return HttpServletResponse.SC_CONFLICT; case Onem2m.ResponseStatusCode.INTERNAL_SERVER_ERROR: return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; case Onem2m.ResponseStatusCode.NOT_IMPLEMENTED: return HttpServletResponse.SC_NOT_IMPLEMENTED; case Onem2m.ResponseStatusCode.TARGET_NOT_REACHABLE: return HttpServletResponse.SC_NOT_FOUND; case Onem2m.ResponseStatusCode.ALREADY_EXISTS: return HttpServletResponse.SC_FORBIDDEN; case Onem2m.ResponseStatusCode.TARGET_NOT_SUBSCRIBABLE: return HttpServletResponse.SC_FORBIDDEN; case Onem2m.ResponseStatusCode.NON_BLOCKING_REQUEST_NOT_SUPPORTED: return HttpServletResponse.SC_NOT_IMPLEMENTED; case Onem2m.ResponseStatusCode.INVALID_ARGUMENTS: return HttpServletResponse.SC_BAD_REQUEST; case Onem2m.ResponseStatusCode.INSUFFICIENT_ARGUMENTS: return HttpServletResponse.SC_BAD_REQUEST; }// ww w. j av a2 s . c o m return HttpServletResponse.SC_BAD_REQUEST; }
From source file:org.ednovo.gooru.controllers.v2.api.TaskManagementRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_TASK_MANAGEMENT_ADD }) @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(method = RequestMethod.POST, value = { "/{id}/item" }) public ModelAndView createTaskResourceAssociation(HttpServletRequest request, @PathVariable(ID) String gooruOid, @RequestBody String data, HttpServletResponse response) throws Exception { User user = (User) request.getAttribute(Constants.USER); JSONObject json = requestData(data); ActionResponseDTO<TaskResourceAssoc> task = getTaskService().createTaskResourceAssociation( this.buildTaskResourceFromInputParameters(getValue(TASK_RESOURCE_ASSOC, json)), user, gooruOid); if (task.getErrors().getErrorCount() > 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else {/*from w w w .ja v a 2s .c o m*/ response.setStatus(HttpServletResponse.SC_CREATED); } String[] includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null; String includes[] = (String[]) ArrayUtils .addAll(includeFields == null ? TASK_CREATE_RESOURCE_ASSOC_INCLUDES : includeFields, ERROR_INCLUDE); includes = (String[]) ArrayUtils.addAll(includes, RESOURCE_INCLUDE_FIELDS); SessionContextSupport.putLogParameter(EVENTNAME, CREATE_TASK_RESOURCE_ASSOCIATION); SessionContextSupport.putLogParameter(TASK_ASSOCIATED_DATE, task.getModel().getAssociationDate()); SessionContextSupport.putLogParameter(TASK_RESOURCE_ASSOCIATOR, task.getModel().getAssociatedBy() != null ? task.getModel().getAssociatedBy().getPartyUid() : null); SessionContextSupport.putLogParameter(TASK_RESOURCE_UID, task.getModel().getTaskResourceAssocUid()); SessionContextSupport.putLogParameter(RESOURCE, task.getModel().getResource().getGooruOid()); return toModelAndViewWithIoFilter(task.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes); }
From source file:org.apache.qpid.systest.rest.RestTestHelper.java
public void createOrUpdateUser(String username, String password) throws IOException { createOrUpdateUser(username, password, HttpServletResponse.SC_CREATED); }
From source file:org.ednovo.gooru.controllers.v2.api.QuizRestV2Controller.java
@AuthorizeOperations(operations = { GooruOperationConstants.OPERATION_QUIZ_V2_ITEM_ADD }) @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(value = "/{qid}/item", method = RequestMethod.POST) public ModelAndView createQuizItem(@PathVariable(value = QUESTION_ID) String quizId, @RequestBody String data, HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getAttribute(Constants.USER); JSONObject json = requestData(data); ActionResponseDTO<CollectionItem> responseDTO = this.getQuizSerivce().createQuizItem( getValue(RESOURCE_ID, json), quizId, this.buildQuizItemFromInputParameters(getValue(COLLECTION_ITEM, json), user), user, CollectionType.USER_QUIZ.getCollectionType()); if (responseDTO.getErrors().getErrorCount() > 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else {/*from w w w . jav a2s.c o m*/ response.setStatus(HttpServletResponse.SC_CREATED); } String[] includeFields = getValue(FIELDS, json) != null ? getFields(getValue(FIELDS, json)) : null; String includesDefault[] = (String[]) ArrayUtils.addAll(QUIZ_INCLUDES, COLLECTION_ITEM_INCLUDE_FILEDS); String includes[] = (String[]) ArrayUtils.addAll(includeFields == null ? includesDefault : includeFields, ERROR_INCLUDE); return toModelAndView(serialize(responseDTO.getModelData(), RESPONSE_FORMAT_JSON, EXCLUDE_ALL, includes)); }