下面列出了javax.ws.rs.core.Response#ok() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
/**
* 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();
}
@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();
}
@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;
}
}
@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();
}
@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);
}
}
@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();
}
@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();
}
@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);
}
}
@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();
}
}
@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();
}
@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();
}
}
@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;
}
public Response expected1() {
Response.ResponseBuilder builder = Response.ok();
builder.header("X-Test", "Hello World");
return builder.build();
}
@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;
}
@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();
}
@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();
}
}
protected static Response.ResponseBuilder ok(Object obj) {
return Response.ok(obj);
}
@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);
}
}
@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);
}
}