javax.ws.rs.core.Response.ResponseBuilder#build()源码实例Demo

下面列出了javax.ws.rs.core.Response.ResponseBuilder#build() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: io   文件: DavMoveResource.java
/**
 * MOVEメソッドの処理.
 * @return JAX-RS応答オブジェクト
 */
public Response doMove() {

    // リクエストヘッダのバリデート
    validateHeaders();

    // 移動先のBox情報を取得する
    BoxRsCmp boxRsCmp = getBoxRsCmp();

    // 移動先の情報を生成
    DavDestination davDestination;
    try {
        davDestination = new DavDestination(destination, this.getAccessContext().getBaseUri(), boxRsCmp);
    } catch (URISyntaxException e) {
        // URI 形式でない
        throw DcCoreException.Dav.INVALID_REQUEST_HEADER.params(org.apache.http.HttpHeaders.DESTINATION,
                destination);
    }

    // データの更新・削除
    ResponseBuilder response = this.davCmp.move(this.ifMatch, this.overwrite, davDestination);

    return response.build();
}
 
源代码2 项目: io   文件: DcCoreAuthzException.java
@Override
public Response createResponse() {
    ResponseBuilder rb = Response.status(HttpStatus.SC_UNAUTHORIZED)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .entity(new ODataErrorMessage(code, message));

    // レルム値が設定されていれば、WWW-Authenticateヘッダーを返却する。
    if (null != this.realm) {
        switch (this.authScheme) {
        case BEARER:
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BEARER + " realm=\"" + this.realm + "\"");
            break;
        case BASIC:
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BASIC + " realm=\"" + this.realm + "\"");
            break;
        default: // デフォルトとして、Bearer/Basicの両方を返却する。
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BEARER + " realm=\"" + this.realm + "\"");
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BASIC + " realm=\"" + this.realm + "\"");
            break;
        }
    }
    return rb.build();
}
 
源代码3 项目: iaf   文件: ApiExceptionHandler.java
@Override
@Produces(MediaType.TEXT_PLAIN)
public Response toResponse(Exception exception) {
	//If the message has already been wrapped in an exception we don't need to `convert` it!
	if(exception instanceof ApiException) {
		return ((ApiException) exception).getResponse();
	}

	ResponseBuilder response = Response.status(Status.INTERNAL_SERVER_ERROR);
	String message = exception.getMessage();

	if(message != null) {
		message = message.replace("\"", "\\\"").replace("\n", " ").replace(System.getProperty("line.separator"), " ");
		Map<String, Object> entity = new HashMap<String, Object>(3);
		entity.put("status", "error");
		entity.put("error", message);
		entity.put("stackTrace", exception.getStackTrace());

		response.entity(entity).type(MediaType.APPLICATION_JSON);
	}

	return response.build();
}
 
源代码4 项目: commafeed   文件: FeedREST.java
@GET
@Path("/favicon/{id}")
@UnitOfWork
@ApiOperation(value = "Fetch a feed's icon", notes = "Fetch a feed's icon")
@Timed
public Response getFeedFavicon(@ApiParam(hidden = true) @SecurityCheck User user,
		@ApiParam(value = "subscription id", required = true) @PathParam("id") Long id) {

	Preconditions.checkNotNull(id);
	FeedSubscription subscription = feedSubscriptionDAO.findById(user, id);
	if (subscription == null) {
		return Response.status(Status.NOT_FOUND).build();
	}
	Feed feed = subscription.getFeed();
	Favicon icon = feedService.fetchFavicon(feed);

	ResponseBuilder builder = Response.ok(icon.getIcon(), Optional.ofNullable(icon.getMediaType()).orElse("image/x-icon"));

	CacheControl cacheControl = new CacheControl();
	cacheControl.setMaxAge(2592000);
	cacheControl.setPrivate(false);
	builder.cacheControl(cacheControl);

	Calendar calendar = Calendar.getInstance();
	calendar.add(Calendar.MONTH, 1);
	builder.expires(calendar.getTime());
	builder.lastModified(CommaFeedApplication.STARTUP_TIME);

	return builder.build();
}
 
源代码5 项目: oxAuth   文件: UmaResourceRegistrationWS.java
@GET
@Path("{rsid}")
@Produces({UmaConstants.JSON_MEDIA_TYPE})
public Response getResource(
        @HeaderParam("Authorization")
                String authorization,
        @PathParam("rsid")
                String rsid) {
    try {
        final AuthorizationGrant authorizationGrant = umaValidationService.assertHasProtectionScope(authorization);
        umaValidationService.validateRestrictedByClient(authorizationGrant.getClientDn(), rsid);
        log.debug("Getting resource description: '{}'", rsid);

        final org.gluu.oxauth.model.uma.persistence.UmaResource ldapResource = resourceService.getResourceById(rsid);

        final UmaResourceWithId response = new UmaResourceWithId();

        response.setId(ldapResource.getId());
        response.setName(ldapResource.getName());
        response.setDescription(ldapResource.getDescription());
        response.setIconUri(ldapResource.getIconUri());
        response.setScopes(umaScopeService.getScopeIdsByDns(ldapResource.getScopes()));
        response.setScopeExpression(ldapResource.getScopeExpression());
        response.setType(ldapResource.getType());
        response.setIat(ServerUtil.dateToSeconds(ldapResource.getCreationDate()));
        response.setExp(ServerUtil.dateToSeconds(ldapResource.getExpirationDate()));

        final ResponseBuilder builder = Response.ok();
        builder.entity(ServerUtil.asJson(response)); // convert manually to avoid possible conflicts between resteasy providers, e.g. jettison, jackson

        return builder.build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }

        throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, ex.getMessage());
    }
}
 
源代码6 项目: org.openntf.domino   文件: InfoResource.java
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response performRequest(@Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace)
		throws JsonException, IOException {
	String jsonEntity = null;
	ResponseBuilder builder = Response.ok();
	ParamMap pm = Parameters.toParamMap(uriInfo);
	StringWriter sw = new StringWriter();
	DFramedTransactionalGraph<?> graph = this.getGraph(namespace);
	JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, false);
	// writer.outObject(null);
	List<String> items = pm.get(Parameters.ITEM);
	if (items != null && items.size() > 0) {
		IGraphFactory factory = this.getService().getFactory(namespace);
		if (factory != null) {
			for (String item : items) {
				Object curResult = factory.processRequest(namespace, item, uriInfo.getQueryParameters());
				writer.outObject(curResult);
			}
		} else {
			System.err.println("No Factory found for namespace: " + namespace);
		}
	}
	jsonEntity = sw.toString();
	builder.type(MediaType.APPLICATION_JSON_TYPE).entity(jsonEntity);
	Response response = builder.build();
	return response;

}
 
源代码7 项目: cxf   文件: BookStore.java
@POST
@Path("/bookheaders/simple/")
@CustomHeaderAdded
@PostMatchMode
@Consumes("application/xml")
public Response echoBookByHeaderSimple(Book book,
    @HeaderParam("Content-type") String ct,
    @HeaderParam("BOOK") String headerBook,
    @HeaderParam("Simple") String headerSimple,
    @HeaderParam("ServerReaderInterceptor") String serverInterceptorHeader,
    @HeaderParam("ClientWriterInterceptor") String clientInterceptorHeader,
    @HeaderParam("EmptyRequestStreamDetected") String emptyStreamHeader) throws Exception {
    if (!"application/xml".equals(ct)) {
        throw new RuntimeException();
    }
    ResponseBuilder builder = getBookByHeaderSimpleBuilder(headerBook, headerSimple);
    if (serverInterceptorHeader != null) {
        builder.header("ServerReaderInterceptor", serverInterceptorHeader);
    }
    if (clientInterceptorHeader != null) {
        builder.header("ClientWriterInterceptor", clientInterceptorHeader);
    }
    if (emptyStreamHeader != null) {
        builder.header("EmptyRequestStreamDetected", emptyStreamHeader);
    }
    return builder.build();
}
 
源代码8 项目: pxf   文件: InvalidPathResource.java
/**
 * Returns error message
 */
private Response sendErrorMessage(String message) {
    ResponseBuilder b = Response.serverError();
    b.entity(message);
    b.type(MediaType.TEXT_PLAIN_TYPE);
    return b.build();
}
 
源代码9 项目: govpay   文件: BaseController.java
private Response handleRedirectException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, RedirectException e, String transactionId) {
	this.log.error("Esecuzione del metodo ["+methodName+"] si e' conclusa con un errore: " + e.getMessage() + ", redirect verso la url: " + e.getLocation());
	ResponseBuilder responseBuilder = Response.seeOther(e.getURILocation());
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId).build();
	else
		return responseBuilder.build();
}
 
源代码10 项目: ctsms   文件: StaffResource.java
@GET
@Path("{id}/files/pdf")
public Response aggregatePDFFiles(@PathParam("id") Long id, @Context UriInfo uriInfo) throws AuthenticationException, AuthorisationException, ServiceException {
	FilePDFVO vo = WebUtil.getServiceLocator().getFileService().aggregatePDFFiles(auth, fileModule, id, null, false, null, null, new PSFUriPart(uriInfo));
	// 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();
}
 
源代码11 项目: govpay   文件: BaseController.java
private Response handleRedirectException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, RedirectException e, String transactionId) {
	this.log.error("Esecuzione del metodo ["+methodName+"] si e' conclusa con un errore: " + e.getMessage() + ", redirect verso la url: " + e.getLocation());
	ResponseBuilder responseBuilder = Response.seeOther(e.getURILocation());
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId).build();
	else
		return responseBuilder.build();
}
 
源代码12 项目: XPagesExtensionLibrary   文件: EventResource.java
@PUT
@Consumes(MEDIA_TYPE_ICALENDAR)
public Response updateEvent(String requestEntity,  @Context UriInfo uriInfo,
                    @PathParam(EVENT) String id, 
                    @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, "updateEvent"); // $NON-NLS-1$
    CalendarService.beforeRequest(FEATURE_REST_API_CALENDAR_EVENT, STAT_UPDATE_EVENT);

    CalendarService.verifyDatabaseContext();

    try {
        if ( StringUtil.isEmpty(requestEntity) ) {
            throw new WebApplicationException(CalendarService.createErrorResponse("Empty request body.", Status.BAD_REQUEST)); // $NLX-EventResource.Emptyrequestbody.2-1$
        }
        
        int flags = getUpdateFlags(workflow, literally, strictSequence);
        responseEntity = StoreFactory.getEventStore().updateEvent(requestEntity, id, null, comments, flags);
    }
    catch(StoreException e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Utils.mapStatus(e), Utils.getExtraProps(e)));
    }
    
    ResponseBuilder builder = Response.ok();
    builder.type(MEDIA_TYPE_ICALENDAR).entity(responseEntity);
    Response response = builder.build();
    CALENDAR_SERVICE_LOGGER.traceExit(this, "updateEvent", response); // $NON-NLS-1$
    
    return response;
}
 
源代码13 项目: Knowage-Server   文件: DossierActivityResource.java
@GET
@Path("/activity/{activityId}/{type}")
public Response downloadPPTExists(@PathParam("activityId") Integer activityId, @PathParam("type") String type,
		@QueryParam("activityName") String activityName) {

	ISbiDossierActivityDAO sdaDAO;
	DossierActivity activity;
	byte[] file;

	Calendar cal = Calendar.getInstance();
	SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
	String formattedDate = format.format(cal.getTime());

	try {
		sdaDAO = DAOFactory.getDossierActivityDao();
		logger.debug("Downloading PPT file with activity id: " + activityId + ". Activity name: " + activityName);
		activity = sdaDAO.loadActivity(activityId);
		file = activity.getBinContent();

		ResponseBuilder response = Response.ok(file);
		response.header("Content-Disposition", "attachment; filename=" + activityName + "_" + formattedDate + "." + type);
		response.header("filename", activityName + "_" + formattedDate + "." + type);
		return response.build();

	} catch (Exception e) {
		logger.error("Error while downloading file with activity id: " + activityId + " for activity: " + activityName, e);
		throw new SpagoBIRestServiceException(getLocale(), e);
	}

}
 
源代码14 项目: nexus-repository-r   文件: RResourceITSupport.java
private Response execute(HttpEntityEnclosingRequestBase request) throws Exception {
  try (CloseableHttpResponse response = clientBuilder().build().execute(request)) {
    ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
    Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

    HttpEntity entity = response.getEntity();
    if (entity != null) {
      responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
    }
    return responseBuilder.build();
  }
}
 
源代码15 项目: ctsms   文件: ProbandResource.java
@GET
@Path("{id}/inquiryvalues/signuppdf")
public Response renderInquiriesSignup(@PathParam("id") Long id, @QueryParam("department_id") Long departmentId, @QueryParam("active_signup") Boolean activeSignup)
		throws AuthenticationException,
		AuthorisationException, ServiceException {
	InquiriesPDFVO vo = WebUtil.getServiceLocator().getProbandService().renderInquiriesSignup(auth, departmentId, id, activeSignup);
	// 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();
}
 
源代码16 项目: knox   文件: KnoxMetadataResource.java
private Response generateSuccessFileDownloadResponse(java.nio.file.Path publicCertFilePath) {
  final ResponseBuilder responseBuilder = Response.ok(publicCertFilePath.toFile());
  responseBuilder.header("Content-Disposition", "attachment;filename=" + publicCertFilePath.getFileName().toString());
  return responseBuilder.build();
}
 
源代码17 项目: SeaCloudsPlatform   文件: AbstractSLARest.java
protected Response buildResponse(int code, String payload) {

        ResponseBuilder builder = Response.status(code);
        builder.entity(payload);
        return builder.build();
    }
 
@SuppressWarnings("unchecked")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createFramedObject(final String requestEntity, @Context final UriInfo uriInfo,
		@PathParam(Routes.NAMESPACE) final String namespace, @Context final Request request)
				throws JsonException, IOException {
	// org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector
	// rc;
	@SuppressWarnings("rawtypes")
	DFramedTransactionalGraph graph = this.getGraph(namespace);
	ParamMap pm = Parameters.toParamMap(uriInfo);
	StringWriter sw = new StringWriter();
	JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, true);
	// System.out.println("TEMP DEBUG Starting new POST...");
	JsonJavaObject jsonItems = null;
	List<Object> jsonArray = null;
	JsonGraphFactory factory = JsonGraphFactory.instance;
	try {
		StringReader reader = new StringReader(requestEntity);
		try {
			Object jsonRaw = JsonParser.fromJson(factory, reader);
			if (jsonRaw instanceof JsonJavaObject) {
				jsonItems = (JsonJavaObject) jsonRaw;
			} else if (jsonRaw instanceof List) {
				jsonArray = (List<Object>) jsonRaw;
				// System.out.println("TEMP DEBUG processing a POST with an
				// array of size " + jsonArray.size());
			} else {
				// System.out.println("TEMP DEBUG Got an unexpected object
				// from parser "
				// + (jsonRaw == null ? "null" :
				// jsonRaw.getClass().getName()));
			}
		} catch (Exception e) {
			throw new WebApplicationException(
					ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
		} finally {
			reader.close();
		}
	} catch (Exception ex) {
		throw new WebApplicationException(
				ErrorHelper.createErrorResponse(ex, Response.Status.INTERNAL_SERVER_ERROR));
	}
	boolean committed = true;
	Map<Object, Object> results = new LinkedHashMap<Object, Object>();
	if (jsonArray != null) {
		writer.startArray();
		for (Object raw : jsonArray) {
			if (raw instanceof JsonJavaObject) {
				writer.startArrayItem();
				committed = processJsonObject((JsonJavaObject) raw, graph, writer, results);
				writer.endArrayItem();
			} else {
				System.err.println("Raw array member isn't a JsonJavaObject. It's a "
						+ (raw == null ? "null" : raw.getClass().getName()));
			}
		}
		writer.endArray();
	} else if (jsonItems != null) {
		committed = processJsonObject(jsonItems, graph, writer, results);
	} else {
		// System.out.println("TEMP DEBUG Nothing to POST. No JSON items
		// found.");
	}

	String jsonEntity = sw.toString();
	ResponseBuilder berg = getBuilder(jsonEntity, new Date(), false, request);
	Response response = berg.build();
	if (!committed) {
		graph.rollback();
	}
	return response;
}
 
源代码19 项目: opencps-v2   文件: DossierDocumentManagementImpl.java
@Override
public Response printFileByPartNo(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
		User user, ServiceContext serviceContext, String id, String templateNo, String partNo) {

	BackendAuth auth = new BackendAuthImpl();
	long dossierId = GetterUtil.getLong(id);

	try {

		if (!auth.isAuth(serviceContext)) {
			throw new UnauthenticationException();
		}

		List<DossierFile> dossierFileList = DossierFileLocalServiceUtil.getDossierFileByDID_DPNO(dossierId, partNo,
				false);
		if (dossierFileList  != null && dossierFileList.size() > 0) {
			for (DossierFile dossierFile : dossierFileList) {
				if (dossierFile != null && Validator.isNotNull(dossierFile.getFormData())) {
					long docFileId = dossierFile.getFileEntryId();
					if (docFileId > 0) {
						FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(docFileId);

						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);
	}
	return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
}
 
/**
 * Gets a list of views and folders in a database.
 * 
 * @return
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getViews(@Context final UriInfo uriInfo,
        @QueryParam(PARAM_COMPACT) final boolean compact) {
    
    DAS_LOGGER.traceEntry(this, "getViews"); // $NON-NLS-1$
    DataService.beforeRequest(FEATURE_REST_API_DATA_VIEW_COLLECTION, STAT_VIEW_COLLECTION);

    StreamingOutput streamJsonEntity = new StreamingOutput(){

        //@Override
        public void write(OutputStream outputStream) throws IOException {
            try {
                URI baseURI = UriHelper.copy(uriInfo.getAbsolutePath(),DataService.isUseRelativeUrls());
                
                Database database = getDatabase(DB_ACCESS_VIEWS);
                if ( database == null ) {
                    // This resource should always have a database context
                    throw new WebApplicationException(ErrorHelper.createErrorResponse("URI path must include a database.", Response.Status.BAD_REQUEST)); // $NLX-ViewCollectionResource.URIpathmustincludeadatabase-1$
                }
                
                OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
                JsonWriter jwriter = new JsonWriter(streamWriter, compact);
                JsonViewCollectionContent content = new JsonViewCollectionContent(database, baseURI.toString());
                content.writeViewCollection(jwriter);
                
                streamWriter.close();
            }
            catch (ServiceException e) {
                throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
            }
        }
    };

    ResponseBuilder builder = Response.ok();
    builder.type(MediaType.APPLICATION_JSON_TYPE).entity(streamJsonEntity);
    
    Response response = builder.build();
    DAS_LOGGER.traceExit(this, "getViews", response); // $NON-NLS-1$

    return response;
}