下面列出了javax.ws.rs.core.Response#ResponseBuilder() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@PUT
@RolesAllowed({"IbisAdmin", "IbisTester"})
@Path("/configurations")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response fullReload(LinkedHashMap<String, Object> json) throws ApiException {
Response.ResponseBuilder response = Response.status(Response.Status.NO_CONTENT); //PUT defaults to no content
for (Entry<String, Object> entry : json.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if(key.equalsIgnoreCase("action")) {
if(value.equals("reload")) {
getIbisManager().handleAdapter("FULLRELOAD", "", "", "", null, true);
}
response.entity("{\"status\":\"ok\"}");
}
}
return response.build();
}
private Response buildPreflightResponse(String origin, String accessControlRequestMethod,
String accessControlRequestHeaders) {
Response.ResponseBuilder builder = Response.ok();
if (anyOriginAllowed && !allowCredentials) {
builder.header(ACCESS_CONTROL_ALLOW_ORIGIN, ANY_ORIGIN);
} else {
builder.header(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
builder.header(HttpHeaders.VARY, ORIGIN);
}
if (allowCredentials) {
builder.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.TRUE.toString());
}
if (maxAge > 0) {
builder.header(ACCESS_CONTROL_MAX_AGE, maxAge);
}
builder.header(ACCESS_CONTROL_ALLOW_METHODS, accessControlRequestMethod);
if (!isBlank(accessControlRequestHeaders)) {
builder.header(ACCESS_CONTROL_ALLOW_HEADERS, accessControlRequestHeaders);
}
return builder.build();
}
private Response internalHeadAutoAckSubscription(UriInfo uriInfo, String consumerId) {
QueueConsumer consumer = findAutoAckSubscription(consumerId);
Response.ResponseBuilder builder = Response.noContent();
String pathToPullSubscriptions = uriInfo.getMatchedURIs().get(1);
headAutoAckSubscriptionResponse(uriInfo, consumer, builder, pathToPullSubscriptions);
return builder.build();
}
public Response method() {
Response.ResponseBuilder builder = Response.ok();
if (otherMethod()) {
builder.header("X-Test", "Hello World");
}
System.out.println("Test");
return builder.build();
}
@Test
void testDeleteError() {
when(mockResourceService.delete(any(Metadata.class))).thenReturn(asyncException());
final DeleteHandler handler = new DeleteHandler(mockTrellisRequest, mockBundler, extensions, baseUrl);
final CompletionStage<Response.ResponseBuilder> builder = handler.deleteResource(handler.initialize(mockParent,
mockResource));
assertThrows(CompletionException.class, () -> unwrapAsyncError(builder),
"No exception thrown when the backend reports an exception!");
}
@Path("v1/owner/{owner}/matchCollection/{matchCollection}/pGroup/{pGroupId}/matchCounts")
@PUT
@ApiOperation(
value = "Update match counts for all pairs with specified pGroup")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "match counts successfully updated"),
@ApiResponse(code = 404, message = "Match collection not found")
})
public Response updateMatchCountsForPGroup(@PathParam("owner") final String owner,
@PathParam("matchCollection") final String matchCollection,
@PathParam("pGroupId") final String pGroupId,
@Context final UriInfo uriInfo) {
LOG.info("updateMatchCountsForPGroup: entry, owner={}, matchCollection={}, pGroupId={}",
owner, matchCollection, pGroupId);
final MatchCollectionId collectionId = getCollectionId(owner, matchCollection);
try {
matchDao.updateMatchCountsForPGroup(collectionId, pGroupId);
} catch (final Throwable t) {
RenderServiceUtil.throwServiceException(t);
}
final Response.ResponseBuilder responseBuilder = Response.created(uriInfo.getRequestUri());
LOG.info("updateMatchCountsForPGroup: exit, pGroupId={}", pGroupId);
return responseBuilder.build();
}
@Override
public Response toResponse(final ValidationException exception) {
if (exception instanceof ConstraintViolationException) {
LOGGER.log(Level.FINER, LocalizationMessages.CONSTRAINT_VIOLATIONS_ENCOUNTERED(), exception);
final ConstraintViolationException cve = (ConstraintViolationException) exception;
final Response.ResponseBuilder response = Response.status(getStatus(cve));
// Entity
final List<Variant> variants = Variant.mediaTypes(
MediaType.APPLICATION_XML_TYPE,
MediaType.APPLICATION_JSON_TYPE).build();
final Variant variant = request.get().selectVariant(variants);
if (variant != null) {
response.type(variant.getMediaType());
} else {
/*
* default media type which will be used only when none media type from {@value variants} is in
* accept header of original request.
*/
response.type(MediaType.TEXT_PLAIN_TYPE);
}
response.entity(
new GenericEntity<List<ValidationError>>(
getEntity(cve.getConstraintViolations()),
new GenericType<List<ValidationError>>() {}.getType()
)
);
return response.build();
} else {
LOGGER.log(Level.WARNING, LocalizationMessages.VALIDATION_EXCEPTION_RAISED(), exception);
return Response.serverError().entity(exception.getMessage()).build();
}
}
@GET
@Path("{fileName:.+}")
@Produces("text/css")
public Response getCSS(@PathParam("fileName") String name, @Context Request request) {
try {
MCRServletContextResourceImporter importer = new MCRServletContextResourceImporter(context);
Optional<String> cssFile = MCRSassCompilerManager.getInstance()
.getCSSFile(name, Stream.of(importer).collect(Collectors.toList()));
if (cssFile.isPresent()) {
CacheControl cc = new CacheControl();
cc.setMaxAge(SECONDS_OF_ONE_DAY);
String etagString = MCRSassCompilerManager.getInstance().getLastMD5(name).get();
EntityTag etag = new EntityTag(etagString);
Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
if (builder != null) {
return builder.cacheControl(cc).tag(etag).build();
}
return Response.ok().status(Response.Status.OK)
.cacheControl(cc)
.tag(etag)
.entity(cssFile.get())
.build();
} else {
return Response.status(Response.Status.NOT_FOUND)
.build();
}
} catch (IOException | CompilationException e) {
StreamingOutput so = (OutputStream os) -> e.printStackTrace(new PrintStream(os, true,
StandardCharsets.UTF_8));
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(so).build();
}
}
public Response.ResponseBuilder getResponseBuilder(Model model)
{
Variant variant = getRequest().selectVariant(getVariants(Model.class));
Response.ResponseBuilder builder = new com.atomgraph.core.model.impl.Response(getRequest(),
model,
null,
new EntityTag(Long.toHexString(ModelUtils.hashModel(model))),
variant).
getResponseBuilder().
header("Link", new Link(getUriInfo().getBaseUri(), LDT.base.getURI(), null));
if (getTemplateCall() != null) builder.header("Link", new Link(URI.create(getTemplateCall().getTemplate().getURI()), LDT.template.getURI(), null));
if (getOntology() != null)
{
builder.header("Link", new Link(URI.create(getOntology().getURI()), LDT.ontology.getURI(), null));
Reasoner reasoner = getOntology().getOntModel().getSpecification().getReasoner();
if (reasoner instanceof GenericRuleReasoner)
{
List<Rule> rules = ((GenericRuleReasoner)reasoner).getRules();
builder.header("Rules", RulePrinter.print(rules));
}
}
return builder;
}
@GET
@Path("/serviceactions/count")
@Produces({MediaType.APPLICATION_JSON})
@JacksonFeatures(serializationEnable = {SerializationFeature.INDENT_OUTPUT})
public Response getActionServicesCount() {
try {
Response.ResponseBuilder responseBuilder = Response.ok(repoService.getActionServices().size());
return responseBuilder.build();
} catch (Exception e) {
throw new javax.ws.rs.NotFoundException();
}
}
@Override
public Response toResponse(Throwable e) {
ErrorResponseInfo<Response.ResponseBuilder> exceptionHandled;
try {
exceptionHandled = maybeHandleException(e, request, response);
if (exceptionHandled == null) {
if (logger.isDebugEnabled()) {
logger.debug("No suitable handlers found for exception=" + e.getMessage() + ". "
+ JaxRsUnhandledExceptionHandler.class.getName() + " should handle it.");
}
exceptionHandled = jerseyUnhandledExceptionHandler.handleException(e, request, response);
}
}
catch (UnexpectedMajorExceptionHandlingError ohNoException) {
logger.error("Unexpected major error while handling exception. " +
JaxRsUnhandledExceptionHandler.class.getName() + " should handle it.", ohNoException);
exceptionHandled = jerseyUnhandledExceptionHandler.handleException(e, request, response);
}
Response.ResponseBuilder responseBuilder = setContentType(exceptionHandled, request, response, e);
// NOTE: We don't have to add headers to the response here - it's already been done in the
// ApiExceptionHandlerServletApiBase.processServletResponse(...) method.
return responseBuilder.build();
}
@Override
public Response.ResponseBuilder write(MrGeoRaster raster, int tileColumn, int tileRow,
double scale, MrsPyramid pyramid)
{
try
{
int tilesize = pyramid.getMetadata().getTilesize();
int zoom = TMSUtils.zoomForPixelSize(scale, tilesize);
Bounds bounds = TMSUtils.tileBounds(tileColumn, tileRow, zoom, tilesize);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
writeStream(raster, bounds, pyramid.getMetadata().getDefaultValue(0), byteStream);
return Response.ok().entity(byteStream.toByteArray())
.encoding(getResponseMimeType())
.header("Content-type", getResponseMimeType())
.header("Content-Disposition", "attachment; filename=" + pyramid.getName() + ".tif");
}
catch (Exception e)
{
log.error("Exception thrown", e);
if (e.getMessage() != null)
{
return Response.serverError().entity(e.getMessage());
}
return Response.serverError().entity("Internal Error");
}
}
@Test
public void prepareFrameworkRepresentationContainsEntity() {
Response.ResponseBuilder response = handlerSpy.prepareFrameworkRepresentation(new DefaultErrorContractDTO(null, null),
HttpServletResponse.SC_OK, null, null, null);
Assert.assertNotNull(response.build().getEntity());
}
static Response.ResponseBuilder applyCacheControl(Response.ResponseBuilder response) {
CacheControl cacheControl = new CacheControl();
cacheControl.setPrivate(true);
cacheControl.setNoCache(true);
cacheControl.setNoStore(true);
return response.cacheControl(cacheControl);
}
protected void setPushSubscriptionsLink(Response.ResponseBuilder response, UriInfo info) {
String uri = createPushSubscriptionsLink(info);
serviceManager.getLinkStrategy().setLinkHeader(response, "push-subscriptions", "push-subscriptions", uri, null);
}
@Override
public Response.ResponseBuilder evaluatePreconditions(Date date) {
throw new UnsupportedOperationException();
}
@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();
}
@Override
public void setCookies(Response.ResponseBuilder builder, String token, boolean secure) {
setCookies(builder, token, secure, false);
}
@Override
public Response toResponse(Exception e) {
int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
Response response = null;
if (e instanceof WebApplicationException) {
response = ((WebApplicationException) e).getResponse();
logger.debug("An exception occurred when processing REST response", e);
} else if (e instanceof Failure) { // Resteasy support
Failure failure = ((Failure) e);
if (failure.getErrorCode() > 0) {
status = failure.getErrorCode();
}
response = failure.getResponse();
logger.debug("An exception occurred when processing REST response", e);
} else {
logger.error("An exception occurred when processing REST response", e);
}
Response.ResponseBuilder builder;
if (response != null) {
builder = Response.status(response.getStatus());
// b.entity(response.getEntity());
// copy headers
for (String headerName : response.getMetadata().keySet()) {
List<Object> headerValues = response.getMetadata().get(headerName);
for (Object headerValue : headerValues) {
builder.header(headerName, headerValue);
}
}
} else {
builder = Response.status(status);
}
builder.entity(new ErrorResponseRest(e)).type(MediaType.APPLICATION_JSON);
return builder.build();
}
@POST
@Path("/imageConvert")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
// The "mimeType" parameter comes in the POST request body (encoded as XML or JSON).
public Response imageConvert(List<Attachment> atts) throws GenericException {
log.debug("imageConvert({})", atts);
String filename = null;
String srcMimeTypeIn = null;
String dstMimeType = null;
String params = null;
InputStream is = null;
FileOutputStream fos = null;
File input = null;
File output = null;
try {
for (Attachment att : atts) {
ContentDisposition contDisp = att.getContentDisposition();
if ("dstMimeType".equals(contDisp.getParameter("name"))) {
dstMimeType = att.getObject(String.class);
} else if ("params".equals(contDisp.getParameter("name"))) {
params = att.getObject(String.class);
} else if ("content".equals(contDisp.getParameter("name"))) {
filename = contDisp.getParameter("filename");
srcMimeTypeIn = MimeTypeConfig.mimeTypes.getContentType(filename.toLowerCase());
is = att.getDataHandler().getInputStream();
}
}
input = FileUtils.createTempFileFromMime(srcMimeTypeIn);
fos = new FileOutputStream(input);
IOUtils.copy(is, fos);
output = FileUtils.createTempFileFromMime(dstMimeType);
ImageUtils.ImageMagickConvert(input, output, params);
final FileInputStream fis = new FileInputStream(output);
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
IOUtils.copy(fis, os);
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(os);
}
};
Response.ResponseBuilder response = Response.ok(stream);
MimeType mt = MimeTypeDAO.findByName(dstMimeType);
String convertedFile = FileUtils.getFileName(filename) + "." + mt.getExtensions().iterator().next();
response.header("Content-Disposition", "attachment; filename=\"" + convertedFile + "\"");
log.debug("imageConvert: [BINARY]");
return response.build();
} catch (Exception e) {
throw new GenericException(e);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(fos);
FileUtils.deleteQuietly(input);
FileUtils.deleteQuietly(output);
}
}