Java Code Examples for javax.ws.rs.core.Response#ok()
The following examples show how to use
javax.ws.rs.core.Response#ok() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SakaiReport.java From sakai with Educational Community License v2.0 | 6 votes |
@WebMethod(exclude = true) @Path("/executeQueryWithFormat") @GET public Response executeQueryWithFormat(@QueryParam("sessionid") String sessionid, @QueryParam("query") String query, @QueryParam("hash") String hash, @QueryParam("format") String format) { String responseData = executeQueryInternal(sessionid, query, hash, MAX_ROWS, convertFormatToEnum(format)); String contentType = MediaType.APPLICATION_XML; if (format.toLowerCase().startsWith("json")) { contentType = MediaType.APPLICATION_JSON; } if (format.toLowerCase().startsWith("csv")) { contentType = "text/csv"; } javax.ws.rs.core.Response.ResponseBuilder rBuild = Response.ok(responseData, contentType); return rBuild.build(); }
Example 2
Source File: RuleResource.java From localization_nifi with Apache License 2.0 | 6 votes |
@GET @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Path("/evaluation-context") public Response getEvaluationContext(@QueryParam("processorId") final String processorId) { // get the web context final NiFiWebConfigurationContext nifiWebContext = (NiFiWebConfigurationContext) servletContext.getAttribute("nifi-web-configuration-context"); // build the web context config final NiFiWebRequestContext contextConfig = getRequestContext(processorId); // load the criteria final Criteria criteria = getCriteria(nifiWebContext, contextConfig); // create the response entity final EvaluationContextEntity responseEntity = new EvaluationContextEntity(); responseEntity.setProcessorId(processorId); responseEntity.setFlowFilePolicy(criteria.getFlowFilePolicy().name()); responseEntity.setRuleOrder(criteria.getRuleOrder()); // generate the response final ResponseBuilder response = Response.ok(responseEntity); return noCache(response).build(); }
Example 3
Source File: LearningGroupWebService.java From olat with Apache License 2.0 | 6 votes |
/** * Return the group specified by the key of the group. * * @response.representation.200.qname {http://www.example.com}groupVO * @response.representation.200.mediaType application/xml, application/json * @response.representation.200.doc A business group in the OLAT system * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_GROUPVO} * @param groupKey * The key of the group * @param request * The REST request * @param httpRequest * The HTTP request * @return */ @GET @Path("{groupKey}") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response findById(@PathParam("groupKey") final Long groupKey, @Context final Request request, @Context final HttpServletRequest httpRequest) { final BusinessGroup bg = businessGroupService.loadBusinessGroup(groupKey, false); if (bg == null) { return Response.serverError().status(Status.NOT_FOUND).build(); } final Identity identity = RestSecurityHelper.getIdentity(httpRequest); if (!isGroupManager(httpRequest) && !businessGroupService.isIdentityInBusinessGroup(identity, bg)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); } final Date lastModified = bg.getLastModified(); Response.ResponseBuilder response = request.evaluatePreconditions(lastModified); if (response == null) { final GroupVO vo = ObjectFactory.get(bg); response = Response.ok(vo); } return response.build(); }
Example 4
Source File: TableScanResource.java From hbase with Apache License 2.0 | 6 votes |
@GET @Produces({ Constants.MIMETYPE_PROTOBUF, Constants.MIMETYPE_PROTOBUF_IETF }) public Response getProtobuf( final @Context UriInfo uriInfo, final @HeaderParam("Accept") String contentType) { if (LOG.isTraceEnabled()) { LOG.trace("GET " + uriInfo.getAbsolutePath() + " as " + MIMETYPE_BINARY); } servlet.getMetrics().incrementRequests(1); try { int fetchSize = this.servlet.getConfiguration().getInt(Constants.SCAN_FETCH_SIZE, 10); StreamingOutput stream = new ProtobufStreamingOutput(this.results, contentType, userRequestedLimit, fetchSize); servlet.getMetrics().incrementSucessfulScanRequests(1); ResponseBuilder response = Response.ok(stream); response.header("content-type", contentType); return response.build(); } catch (Exception exp) { servlet.getMetrics().incrementFailedScanRequests(1); processException(exp); LOG.warn(exp.toString(), exp); return null; } }
Example 5
Source File: TestClass22.java From jaxrs-analyzer with Apache License 2.0 | 6 votes |
@javax.ws.rs.GET public Response method() { Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder.header("X-Test", "Hello"); responseBuilder.cacheControl(CacheControl.valueOf("")); responseBuilder.contentLocation(URI.create("")); responseBuilder.cookie(); responseBuilder.entity(12d); responseBuilder.expires(new Date()); responseBuilder.language(Locale.ENGLISH); responseBuilder.encoding("UTF-8"); responseBuilder.lastModified(new Date()); responseBuilder.link(URI.create(""), "rel"); responseBuilder.location(URI.create("")); responseBuilder.status(433); responseBuilder.tag(new EntityTag("")); responseBuilder.type(MediaType.APPLICATION_JSON_TYPE); responseBuilder.variants(new LinkedList<>()); return responseBuilder.build(); }
Example 6
Source File: ProbandResource.java From ctsms with GNU Lesser General Public License v2.1 | 5 votes |
@GET @Path("{id}/inquiryvalues/pdf") public Response renderInquiries(@PathParam("id") Long id, @QueryParam("active") Boolean active, @QueryParam("active_signup") Boolean activeSignup, @QueryParam("blank") boolean blank) throws AuthenticationException, AuthorisationException, ServiceException { InquiriesPDFVO vo = WebUtil.getServiceLocator().getProbandService().renderInquiries(auth, null, id, active, activeSignup, blank); // http://stackoverflow.com/questions/9204287/how-to-return-a-png-image-from-jersey-rest-service-method-to-the-browser // non-streamed ResponseBuilder response = Response.ok(vo.getDocumentDatas(), vo.getContentType().getMimeType()); response.header(HttpHeaders.CONTENT_LENGTH, vo.getSize()); return response.build(); }
Example 7
Source File: RepositoryService.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@GET @Path("/services/{name}/mavendepends") @Produces({MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response getMavenDependsByServiceName(@PathParam("name") String name) { try { Response.ResponseBuilder responseBuilder = Response.ok(repoService.getServiceByName(name).getMavenDependencies()); return responseBuilder.build(); } catch (Exception e) { throw new javax.ws.rs.NotFoundException(); } }
Example 8
Source File: UserService.java From maven-framework-project with MIT License | 5 votes |
@PermitAll @GET @Path("/users/{id}") public Response getUserById(@PathParam("id") int id, @Context Request req) { Response.ResponseBuilder rb = Response.ok(UserDatabase.getUserById(id)); return rb.build(); }
Example 9
Source File: RepositoryService.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@GET @Path("/services/count") @Produces({MediaType.APPLICATION_JSON}) @JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT}) public Response getAllServicesCount() { try { Response.ResponseBuilder responseBuilder = Response.ok(repoService.getServices().size()); return responseBuilder.build(); } catch (Exception e) { throw new javax.ws.rs.NotFoundException(); } }
Example 10
Source File: FileAttachManagementImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
@Override public Response read(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user, ServiceContext serviceContext, long id, String version) { FileAttachInterface actions = new FileAttachActions(); try { File file = actions.read(id, version, serviceContext); FileEntry fileEntry = actions.getFileEntry(id, serviceContext); if (file != null && fileEntry != null) { String fileName = fileEntry.getFileName(); ResponseBuilder responseBuilder = Response.ok((Object) file); responseBuilder.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"") .header("Content-Type", fileEntry.getMimeType()); return responseBuilder.build(); } else { ErrorMsg error = new ErrorMsg(); error.setMessage("file not found!"); error.setCode(404); error.setDescription("file not found!"); return Response.status(404).entity(error).build(); } } catch (Exception e) { return BusinessExceptionImpl.processException(e); } }
Example 11
Source File: EcrfStatusEntryResource.java From ctsms with GNU Lesser General Public License v2.1 | 5 votes |
@GET @Path("{listEntryId}/ecrfpdf") public Response renderEcrfs(@PathParam("listEntryId") Long listEntryId, @QueryParam("blank") Boolean blank) throws AuthenticationException, AuthorisationException, ServiceException { ECRFPDFVO vo = WebUtil.getServiceLocator().getTrialService().renderEcrfs(auth, null, listEntryId, null, blank); // http://stackoverflow.com/questions/9204287/how-to-return-a-png-image-from-jersey-rest-service-method-to-the-browser // non-streamed ResponseBuilder response = Response.ok(vo.getDocumentDatas(), vo.getContentType().getMimeType()); response.header(HttpHeaders.CONTENT_LENGTH, vo.getSize()); return response.build(); }
Example 12
Source File: RegistrationManagementImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
@Override public Response previewFile(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user, ServiceContext serviceContext, long registrationId, String referenceUid) { BackendAuth auth = new BackendAuthImpl(); try { if (!auth.isAuth(serviceContext)) { throw new UnauthenticationException(); } long groupId = GetterUtil.getLong(header.getHeaderString("groupId")); RegistrationForm registrationForm = RegistrationFormLocalServiceUtil.findFormbyRegidRefid(groupId, registrationId, referenceUid); if (registrationForm != null && registrationForm.getFileEntryId() > 0) { FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(registrationForm.getFileEntryId()); File file = DLFileEntryLocalServiceUtil.getFile(fileEntry.getFileEntryId(), fileEntry.getVersion(), true); ResponseBuilder responseBuilder = Response.ok((Object) file); responseBuilder.header("Content-Disposition", "attachment; filename=\"" + fileEntry.getFileName() + "\""); responseBuilder.header("Content-Type", fileEntry.getMimeType()); return responseBuilder.build(); } else { return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build(); } } catch (Exception e) { return BusinessExceptionImpl.processException(e); } }
Example 13
Source File: EventResource.java From XPagesExtensionLibrary with Apache License 2.0 | 4 votes |
@PUT @Path(PATH_PARAM_INSTANCE) @Consumes(MediaType.APPLICATION_JSON) public Response updateJsonEventInstance(String requestEntity, @Context UriInfo uriInfo, @PathParam(EVENT) String id, @PathParam(INSTANCE) String instanceId, @QueryParam(URL_PARAM_WORKFLOWCOMMENT) String comments, @QueryParam(URL_PARAM_WORKFLOW) String workflow, @QueryParam(URL_PARAM_LITERALLY) String literally, @QueryParam(URL_PARAM_STRICT_SEQUENCE) String strictSequence) { String responseEntity = null; CALENDAR_SERVICE_LOGGER.traceEntry(this, "updateJsonEventInstance"); // $NON-NLS-1$ CalendarService.beforeRequest(FEATURE_REST_API_CALENDAR_EVENT, STAT_UPDATE_EVENT); CalendarService.verifyDatabaseContext(); if ( StringUtil.isEmpty(requestEntity) ) { throw new WebApplicationException(CalendarService.createErrorResponse("Empty request body.", Status.BAD_REQUEST)); // $NLX-EventResource.Emptyrequestbody.1-1$ } int flags = getUpdateFlags(workflow, literally, strictSequence); URI baseURI; try{ baseURI = UriHelper.copy(uriInfo.getAbsolutePath(),CalendarService.isUseRelativeUrls()); }catch(IllegalArgumentException e){ throw new WebApplicationException(CalendarService.createErrorResponse(e, Response.Status.BAD_REQUEST)); } // instanceId don't have special characters, don't need encode baseURI = UriHelper.trimAtLast(baseURI, PATH_SEGMENT_SEPERATOR + instanceId); baseURI = UriHelper.trimAtLast(baseURI, PATH_SEGMENT_SEPERATOR ); baseURI = CalendarService.adaptUriToScn(baseURI); responseEntity = updateJsonEventInternal(requestEntity, baseURI, id, instanceId, comments, flags); ResponseBuilder builder = Response.ok(); builder.type(MediaType.APPLICATION_JSON).entity(responseEntity); Response response = builder.build(); CALENDAR_SERVICE_LOGGER.traceExit(this, "updateJsonEventInstance", response); // $NON-NLS-1$ return response; }
Example 14
Source File: BackchannelDeviceRegistrationRestWebServiceImpl.java From oxAuth with MIT License | 4 votes |
@Override public Response requestBackchannelDeviceRegistrationPost( String idTokenHint, String deviceRegistrationToken, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) { OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_DEVICE_REGISTRATION); // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final, // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate log.debug("Attempting to request backchannel device registration: " + "idTokenHint = {}, deviceRegistrationToken = {}, isSecure = {}", idTokenHint, deviceRegistrationToken, securityContext.isSecure()); Response.ResponseBuilder builder = Response.ok(); DefaultErrorResponse cibaDeviceRegistrationValidation = cibaDeviceRegistrationValidatorService.validateParams( idTokenHint, deviceRegistrationToken); if (cibaDeviceRegistrationValidation != null) { builder = Response.status(cibaDeviceRegistrationValidation.getStatus()); builder.entity(errorResponseFactory.errorAsJson( cibaDeviceRegistrationValidation.getType(), cibaDeviceRegistrationValidation.getReason())); return builder.build(); } User user = null; AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint); if (authorizationGrant == null) { builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity(errorResponseFactory.getErrorAsJson(BackchannelAuthenticationErrorResponseType.UNKNOWN_USER_ID)); return builder.build(); } user = authorizationGrant.getUser(); if (user == null) { builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID)); return builder.build(); } userService.setCustomAttribute(user, "oxAuthBackchannelDeviceRegistrationToken", deviceRegistrationToken); userService.updateUser(user); applicationAuditLogger.sendMessage(oAuth2AuditLog); return builder.build(); }
Example 15
Source File: TestClass8.java From jaxrs-analyzer with Apache License 2.0 | 4 votes |
public Response expected1() { Response.ResponseBuilder builder = Response.ok(); builder.header("X-Test", "Hello World"); return builder.build(); }
Example 16
Source File: BackendAPIRestApplication.java From opencps-v2 with GNU Affero General Public License v3.0 | 4 votes |
@GET @Path("/barcode") @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response getBarcode(@Context HttpServletRequest request, @Context HttpHeaders header, @Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext, @QueryParam("value") String value, @QueryParam("font") String font) { try { Code128 barcode = new Code128(); barcode.setFontName("Monospaced"); barcode.setFontSize(Validator.isNotNull(font) ? Integer.valueOf(font) : ConstantUtils.DEFAULT_FONT_SIZE); barcode.setModuleWidth(2); barcode.setBarHeight(50); barcode.setHumanReadableLocation(HumanReadableLocation.BOTTOM); barcode.setContent(value); int width = barcode.getWidth(); int height = barcode.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g2d = image.createGraphics(); Java2DRenderer renderer = new Java2DRenderer(g2d, 1, Color.WHITE, Color.BLACK); renderer.render(barcode); String uuid = UUID.randomUUID().toString(); File destDir = new File("barcode"); if (!destDir.exists()) { destDir.mkdir(); } File file = new File("barcode/" + uuid + ".png"); if (!file.exists()) { file.createNewFile(); } if (file.exists()) { ImageIO.write(image, "png", file); // String fileType = Files.probeContentType(file.toPath()); ResponseBuilder responseBuilder = Response.ok((Object) file); responseBuilder.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); responseBuilder.header("Content-Type", "image/png"); return responseBuilder.build(); } else { return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build(); } } catch (Exception e) { // e.printStackTrace(); _log.debug(e); return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build(); } }
Example 17
Source File: DossierDocumentApiImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 4 votes |
@Override public void downloadDocByReferenceUid(String id, String referenceUid) { // TODO: check user is loged or password for access dossier file _log.debug("====START DOWNLOAD DOCUMENT==== "); long groupId = GetterUtil.getLong(header.getHeaderString("groupId")); Long dossierId = GetterUtil.getLong(id); try { // if (!auth.isAuth(serviceContext)) { // throw new UnauthenticationException(); // } DossierDocument dossierDoc = DossierDocumentLocalServiceUtil.getDocByReferenceUid(groupId, dossierId, referenceUid); // // download file with dossierDocumentFileId long documentFileId = 0; if (dossierDoc != null) { documentFileId = dossierDoc.getDocumentFileId(); } if (documentFileId > 0) { FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(documentFileId); File file = DLFileEntryLocalServiceUtil.getFile(fileEntry.getFileEntryId(), fileEntry.getVersion(), true); ResponseBuilder responseBuilder = Response.ok((Object) file); responseBuilder.header("Content-Disposition", "attachment; filename=\"" + fileEntry.getFileName() + "\""); responseBuilder.header("Content-Type", fileEntry.getMimeType()); // return responseBuilder.build(); _log.info("====END DOWNLOAD DOCUMENT==== "); } else { // return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build(); } } catch (Exception e) { _log.debug(e); _log.info("====DOWNLOAD DOCUMENT ERROR==== "); respones.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR); } // return null; }
Example 18
Source File: BaseResource.java From onos with Apache License 2.0 | 4 votes |
protected static Response.ResponseBuilder ok(Object obj) { return Response.ok(obj); }
Example 19
Source File: ServiceInfoManagementImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 3 votes |
@Override public Response downloadFileTemplateOfServiceInfo(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user, ServiceContext serviceContext, String id, String templateNo) { ServiceFileTemplatePK fileTemplatePK = new ServiceFileTemplatePK(GetterUtil.getLong(id), templateNo); try { ServiceFileTemplate fileTemplate = ServiceFileTemplateLocalServiceUtil .getServiceFileTemplate(fileTemplatePK); FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(fileTemplate.getFileEntryId()); File file = DLFileEntryLocalServiceUtil.getFile(fileEntry.getFileEntryId(), fileEntry.getVersion(), true); ResponseBuilder responseBuilder = Response.ok((Object) file); responseBuilder.header("Content-Disposition", "attachment; filename=\"" + fileEntry.getFileName() + "\""); responseBuilder.header("Content-Type", fileEntry.getMimeType()); return responseBuilder.build(); } catch (Exception e) { return BusinessExceptionImpl.processException(e); } }
Example 20
Source File: UserManagementImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 3 votes |
@Override public Response getUserEsignCert(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user, ServiceContext serviceContext, long id) { // HARD CODE groupId = 55301 long groupId = 55301; try { Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(groupId, id); String buildFileName = PropsUtil.get(PropsKeys.LIFERAY_HOME) + StringPool.FORWARD_SLASH + "data/cer/" + employee.getEmail() + StringPool.PERIOD + "png"; File targetFile = new File(buildFileName); ResponseBuilder responseBuilder = Response.ok((Object) targetFile); responseBuilder.header("Content-Disposition", "attachment; filename=\"" + targetFile.getName() + "\"") .header("Content-Type", "application/x-x509-user-cert"); return responseBuilder.build(); } catch (Exception e) { return BusinessExceptionImpl.processException(e); } }