javax.ws.rs.core.Response.ResponseBuilder源码实例Demo

javax.ws.rs.core.Variant.VariantListBuilder#javax.ws.rs.core.Response.ResponseBuilder源码实例Demo

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

源代码1 项目: olingo-odata2   文件: RestUtil.java
public static Response convertResponse(final ODataResponse odataResponse, final boolean omitResponseBody) {
  try {
    ResponseBuilder responseBuilder =
        Response.noContent().status(odataResponse.getStatus().getStatusCode());
    if(!omitResponseBody) {
      responseBuilder.entity(odataResponse.getEntity());
    }

    for (final String name : odataResponse.getHeaderNames()) {
      responseBuilder = responseBuilder.header(name, odataResponse.getHeader(name));
    }

    return responseBuilder.build();
  } catch (RuntimeException e) {
    if (odataResponse != null) {
      try {
        odataResponse.close();
      } catch (IOException inner) {
        // if close throw an exception we ignore these and re-throw our exception
        throw e;
      }
    }
    throw e;
  }
}
 
源代码2 项目: govpay   文件: BaseController.java
private Response handleUnprocessableEntityException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, UnprocessableEntityException e, String transactionId) {
	this.log.info("Errore ("+e.getClass().getSimpleName()+") durante "+methodName+": "+ e.getMessage());
	
	FaultBean respKo = new FaultBean();
	respKo.setCategoria(CategoriaEnum.RICHIESTA);
	respKo.setCodice("SEMANTICA");
	respKo.setDescrizione("Richiesta non valida");
	respKo.setDettaglio(e.getDetails());

	String respJson = this.getRespJson(respKo);
	ResponseBuilder responseBuilder = Response.status(e.getTransportErrorCode()).type(MediaType.APPLICATION_JSON).entity(respJson);
	if(e.getTransportErrorCode() > 499)
		this.handleEventoFail(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	else 
		this.handleEventoKo(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	
	return handleResponseKo(responseBuilder, transactionId).build();
}
 
private Response authenticate(UriInfo info, String user, String password) {
    
    _LOG.debug("Received a login request for user {}", user);
    
    Subject currentUser = SecurityUtils.getSubject();
    
    ResponseBuilder rb;
    
    if (!currentUser.isAuthenticated()) {
        _LOG.debug("Authenticating user {}", user);
        UsernamePasswordToken token = new UsernamePasswordToken(user, password);
        token.setRememberMe(true);
        currentUser.login(token);
        
        rb = Response.ok()
                .cookie(new NewCookie(SESSION_COOKIE_NAME, currentUser.getSession().getId().toString(), 
                        info.getBaseUri().getPath(), null, -1, null, -1, null, false, true));
    } else {
        _LOG.debug("The login request for user {} was already authenticated as user {}", user, currentUser.getPrincipal());
        rb = Response.status(Status.CONFLICT);
    }
    return rb.build();
}
 
源代码4 项目: cxf   文件: RequestImpl.java
private ResponseBuilder evaluateIfNotModifiedSince(Date lastModified) {
    List<String> ifNotModifiedSince = headers.getRequestHeader(HttpHeaders.IF_UNMODIFIED_SINCE);

    if (ifNotModifiedSince == null || ifNotModifiedSince.isEmpty()) {
        return null;
    }

    SimpleDateFormat dateFormat = HttpUtils.getHttpDateFormat();

    dateFormat.setLenient(false);
    Date dateSince = null;
    try {
        dateSince = dateFormat.parse(ifNotModifiedSince.get(0));
    } catch (ParseException ex) {
        // invalid header value, request should continue
        return Response.status(Response.Status.PRECONDITION_FAILED);
    }

    if (dateSince.before(lastModified)) {
        return Response.status(Response.Status.PRECONDITION_FAILED);
    }

    return null;
}
 
源代码5 项目: secure-data-service   文件: BasicClient.java
@Override
public Response getHomeResource(Entity home) throws URISyntaxException, MessageProcessingException, IOException {

    URL url = URLBuilder.create(restClient.getBaseURL()).addPath(PathConstants.HOME).build();

    Response response = restClient.getRequest(url);
    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
        try {
            JsonNode element = mapper.readValue(response.readEntity(String.class), JsonNode.class);
            Map<String, List<Link>> links = mapper.readValue(element,
                    new TypeReference<Map<String, List<BasicLink>>>() {
                    });
            home.getData().putAll(links);
        } catch (JsonParseException e) {
            // invalid Json, or non-Json response?
            ResponseBuilder builder = Response.fromResponse(response);
            builder.status(Response.Status.INTERNAL_SERVER_ERROR);
            return builder.build();
        }
    }
    return response;
}
 
源代码6 项目: govpay   文件: BaseController.java
private Response handleUnprocessableEntityException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, UnprocessableEntityException e, String transactionId) {
	this.log.info("Errore ("+e.getClass().getSimpleName()+") durante "+methodName+": "+ e.getMessage());
	
	FaultBean respKo = new FaultBean();
	respKo.setCategoria(CategoriaEnum.RICHIESTA);
	respKo.setCodice("SEMANTICA");
	respKo.setDescrizione("Richiesta non valida");
	respKo.setDettaglio(e.getDetails());

	String respJson = this.getRespJson(respKo);
	ResponseBuilder responseBuilder = Response.status(e.getTransportErrorCode()).type(MediaType.APPLICATION_JSON).entity(respJson);
	if(e.getTransportErrorCode() > 499)
		this.handleEventoFail(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	else 
		this.handleEventoKo(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	
	return handleResponseKo(responseBuilder, transactionId).build();
}
 
protected Response buildViolationReportResponse(ResteasyViolationException exception, Status status) {
    ResponseBuilder builder = Response.status(status);
    builder.header(Validation.VALIDATION_HEADER, "true");

    // Check standard media types.
    MediaType mediaType = getAcceptMediaType(exception.getAccept());
    if (mediaType != null) {
        builder.type(mediaType);
        builder.entity(new ViolationReport(exception));
        return builder.build();
    }

    // Default media type.
    builder.type(MediaType.TEXT_PLAIN);
    builder.entity(exception.toString());
    return builder.build();
}
 
源代码8 项目: io   文件: MessageODataResource.java
/**
 * 受信/送信メッセージEntityを作成する.
 * @param uriInfo URL情報
 * @param reader リクエストボディ
 * @return response情報
 */
protected Response createMessage(UriInfo uriInfo,
        Reader reader) {

    // response用URLに__ctlを追加する
    UriInfo resUriInfo = DcCoreUtils.createUriInfo(uriInfo, 2, "__ctl");

    // Entityの作成を Producerに依頼
    OEntityWrapper oew = getOEntityWrapper(reader, odataResource, CtlSchema.getEdmDataServicesForMessage().build());
    EntityResponse res = getOdataProducer().createEntity(getEntitySetName(), oew);

    // レスポンスボディを生成する
    OEntity ent = res.getEntity();
    MediaType outputFormat = MediaType.APPLICATION_JSON_TYPE;
    List<MediaType> contentTypes = new ArrayList<MediaType>();
    contentTypes.add(MediaType.APPLICATION_JSON_TYPE);
    String key = AbstractODataResource.replaceDummyKeyToNull(ent.getEntityKey().toKeyString());
    String responseStr = renderEntityResponse(resUriInfo, res, "json", contentTypes);

    // 制御コードのエスケープ処理
    responseStr = escapeResponsebody(responseStr);

    ResponseBuilder rb = getPostResponseBuilder(ent, outputFormat, responseStr, resUriInfo, key);
    return rb.build();
}
 
源代码9 项目: org.openntf.domino   文件: FramedResource.java
private ResponseBuilder getBuilder(final String jsonEntity, final Date lastMod, final boolean includeEtag, final Request request) {
	String etagSource = DominoUtils.md5(jsonEntity);
	EntityTag etag = new EntityTag(etagSource);
	ResponseBuilder berg = null;
	if (request != null) {
		berg = request.evaluatePreconditions(etag);
	}
	if (berg == null) {
		// System.out.println("TEMP DEBUG creating a new builder");
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE);
		berg.entity(jsonEntity);
		berg.lastModified(lastMod);
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	}
	return berg;
}
 
源代码10 项目: secure-data-service   文件: BulkExtractTest.java
@Test
public void testFailedEvaluatePreconditions() throws Exception {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    mockBulkExtractEntity(null);

    HttpRequestContext context = new HttpRequestContextAdapter() {
        @Override
        public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag eTag) {
            return Responses.preconditionFailed();
        }
    };

    Response res = bulkExtract.getEdOrgExtractResponse(context, null, null);
    assertEquals(412, res.getStatus());
}
 
源代码11 项目: XPagesExtensionLibrary   文件: EventResource.java
@Path(PATH_PARAM_INSTANCE + "/action") // $NON-NLS-1$
@PUT
public Response putEventInstanceAction(String requestEntity, @HeaderParam("Content-Type") String contentType, // $NON-NLS-1$
        @Context UriInfo uriInfo, @PathParam(EVENT) String id, 
        @PathParam(INSTANCE) String instanceId,  @QueryParam(URL_PARAM_RECURRENCERANGE) String range,
        @QueryParam(URL_PARAM_ACTION_TYPE) String type) {
    
    CALENDAR_SERVICE_LOGGER.traceEntry(this, "putEventActionInstance"); // $NON-NLS-1$
    CalendarService.beforeRequest(FEATURE_REST_API_CALENDAR_EVENT, STAT_MISC);

    CalendarService.verifyDatabaseContext();

    EventActionResource.putEventActionInternal(requestEntity, contentType, id, instanceId, range, type);

    ResponseBuilder builder = Response.ok();
    Response response = builder.build();

    CALENDAR_SERVICE_LOGGER.traceExit(this, "putEventActionInstance", response); // $NON-NLS-1$
    return response;
}
 
源代码12 项目: io   文件: AbstractODataResource.java
/**
 * POST用のレスポンスビルダーを作成する.
 * @param ent OEntity
 * @param outputFormat Content-Type
 * @param responseStr レスポンスボディ
 * @param resUriInfo レスポンスのUriInfo
 * @param key レスポンスのエンティティキー
 * @return レスポンスビルダー
 */
protected ResponseBuilder getPostResponseBuilder(
        OEntity ent,
        MediaType outputFormat,
        String responseStr,
        UriInfo resUriInfo,
        String key) {
    ResponseBuilder rb = Response.status(HttpStatus.SC_CREATED).entity(responseStr).type(outputFormat)
            .header(HttpHeaders.LOCATION, resUriInfo.getBaseUri().toASCIIString()
                    + getEntitySetName() + key)
            .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataVersion.V2.asString);

    // 応答にETAGを付与
    if (ent instanceof OEntityWrapper) {
        OEntityWrapper oew2 = (OEntityWrapper) ent;
        String etag = oew2.getEtag();
        if (etag != null) {
            rb = rb.header(HttpHeaders.ETAG, "W/\"" + etag + "\"");
        }
    }
    return rb;
}
 
源代码13 项目: iaf   文件: ShowConfigurationStatus.java
@GET
@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
@Path("/adapters/{name}/flow")
@Produces(MediaType.TEXT_PLAIN)
public Response getAdapterFlow(@PathParam("name") String adapterName, @QueryParam("dot") boolean dot) throws ApiException {
	Adapter adapter = getAdapter(adapterName);

	FlowDiagramManager flowDiagramManager = getFlowDiagramManager();

	try {
		ResponseBuilder response = Response.status(Response.Status.OK);
		if(dot) {
			response.entity(flowDiagramManager.generateDot(adapter)).type(MediaType.TEXT_PLAIN);
		} else {
			response.entity(flowDiagramManager.get(adapter)).type("image/svg+xml");
		}
		return response.build();
	} catch (SAXException | TransformerException | IOException e) {
		throw new ApiException(e);
	}
}
 
源代码14 项目: gossip   文件: GossipValidateErrorProvider.java
private Response buildViolationReportResponse(ResteasyViolationException exception) {
    ResponseBuilder builder = Response.status(BAD_REQUEST);
    builder.header(VALIDATION_HEADER, "true");
    builder.type(APPLICATION_JSON_TYPE);

    List<ResteasyConstraintViolation> violations = exception.getViolations();

    if (violations.isEmpty()) {
        builder.entity(new ValidateErrorResponse(exception.toString()));
    } else {
        if (log.isDebugEnabled()) {
            try {
                log.debug(objectMapper.writeValueAsString(violations));
            } catch (JsonProcessingException e) {
                log.debug("", e); // Useless, just make sonar and compiler happy w(゚Д゚)w
            }
        }
        builder.entity(new ValidateErrorResponse(violations));
    }

    return builder.build();
}
 
源代码15 项目: apicurio-studio   文件: DesignsResource.java
/**
 * Generates the project and returns the result as a streaming response.
 * @param settings
 * @param generator
 */
private Response asResponse(JaxRsProjectSettings settings, final OpenApi2JaxRs generator) {
    StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            generator.generate(output);
        }
    };
    
    String fname = settings.artifactId + ".zip";
    ResponseBuilder builder = Response.ok().entity(stream)
            .header("Content-Disposition", "attachment; filename=\"" + fname + "\"")
            .header("Content-Type", "application/zip");

    return builder.build();
}
 
源代码16 项目: hadoop-ozone   文件: ObjectEndpoint.java
private void addLastModifiedDate(
    ResponseBuilder responseBuilder, OzoneKeyDetails key) {

  ZonedDateTime lastModificationTime = key.getModificationTime()
      .atZone(ZoneId.of("GMT"));

  responseBuilder
      .header(LAST_MODIFIED,
          RFC1123Util.FORMAT.format(lastModificationTime));
}
 
private void putDeviceCountIntoResponseHeaders(PushApplication app, ResponseBuilder response) {
    long appCount = 0;
    for (Variant variant : app.getVariants()) {
        long variantCount = installationDao.getNumberOfDevicesForVariantID(variant.getVariantID());
        appCount += variantCount;
        response.header("deviceCount_variant_" + variant.getVariantID(), variantCount);
    }
    response.header("deviceCount_app_" + app.getPushApplicationID(), appCount);
}
 
源代码18 项目: 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);
	}

}
 
源代码19 项目: syncope   文件: GroupServiceImpl.java
@Override
public Response delete(final String id) {
    ResponseBuilder builder = checkETag(Resource.Group, id);
    if (builder != null) {
        return builder.build();
    }

    anyLogic(Resource.Group).delete(id, false);
    return Response.noContent().build();
}
 
源代码20 项目: ctsms   文件: ProbandAddressResource.java
@GET
@Path("{id}/probandletterpdf")
public Response renderProbandLetterPDF(@PathParam("id") Long id) throws AuthenticationException,
		AuthorisationException, ServiceException {
	ProbandLetterPDFVO vo = WebUtil.getServiceLocator().getProbandService().renderProbandLetterPDF(auth, id);
	// 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();
}
 
源代码21 项目: everrest   文件: ContainerRequest.java
/**
 * Comparison for If-Match header and ETag.
 *
 * @param etag
 *         the ETag
 * @return ResponseBuilder with status 412 (precondition failed) if If-Match header does NOT MATCH to ETag or null otherwise
 */
private ResponseBuilder evaluateIfMatch(EntityTag etag) {
    String ifMatch = getRequestHeaders().getFirst(IF_MATCH);

    if (isNullOrEmpty(ifMatch)) {
        return null;
    }

    EntityTag otherEtag = EntityTag.valueOf(ifMatch);

    if (eTagsStrongEqual(etag, otherEtag)) {
        return null;
    }
    return Response.status(PRECONDITION_FAILED);
}
 
源代码22 项目: FHIR   文件: Delete.java
private Response buildResponse(FHIRRestOperationResponse ior) {
    ResponseBuilder response = Response.status(ior.getStatus());

    if (ior.getOperationOutcome() != null) {
        response.entity(ior.getOperationOutcome());
    }

    if (ior.getResource() != null) {
        addHeaders(response, ior.getResource());
    }
    return response.build();
}
 
源代码23 项目: cxf   文件: ResponseBuilderImpl.java
public ResponseBuilder location(URI loc) {
    if (!loc.isAbsolute()) {
        Message currentMessage = PhaseInterceptorChain.getCurrentMessage();
        if (currentMessage != null) {

            UriInfo ui = new UriInfoImpl(currentMessage.getExchange().getInMessage(), null);
            loc = ui.getBaseUriBuilder()
                    .path(loc.getRawPath())
                    .replaceQuery(loc.getRawQuery())
                    .fragment(loc.getRawFragment()).buildFromEncoded();
        }
    }
    return setHeader(HttpHeaders.LOCATION, loc);
}
 
源代码24 项目: govpay   文件: BaseController.java
protected ResponseBuilder handleResponseOk(ResponseBuilder responseBuilder, String transactionId) {
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId);
	else 
		return responseBuilder;
}
 
源代码25 项目: everrest   文件: ResponseImpl.java
@Override
public ResponseBuilder contentLocation(URI location) {
    if (location == null) {
        headers.remove(CONTENT_LOCATION);
    } else {
        headers.putSingle(CONTENT_LOCATION, location);
    }
    return this;
}
 
源代码26 项目: guacamole-client   文件: StreamResource.java
/**
 * Intercepts and returns the entire contents the stream represented by
 * this StreamResource.
 *
 * @return
 *     A response through which the entire contents of the intercepted
 *     stream will be sent.
 */
@GET
public Response getStreamContents() {

    // Intercept all output
    StreamingOutput stream = new StreamingOutput() {

        @Override
        public void write(OutputStream output) throws IOException {
            try {
                tunnel.interceptStream(streamIndex, output);
            }
            catch (GuacamoleException e) {
                throw new IOException(e);
            }
        }

    };

    // Begin successful response
    ResponseBuilder responseBuilder = Response.ok(stream, mediaType);

    // Set Content-Disposition header for "application/octet-stream"
    if (mediaType.equals(MediaType.APPLICATION_OCTET_STREAM))
        responseBuilder.header("Content-Disposition", "attachment");

    return responseBuilder.build();

}
 
源代码27 项目: iaf   文件: ShowConfigurationStatus.java
@PUT
@RolesAllowed({"IbisDataAdmin", "IbisAdmin", "IbisTester"})
@Path("/adapters/{adapterName}/receivers/{receiverName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateReceiver(@PathParam("adapterName") String adapterName, @PathParam("receiverName") String receiverName, LinkedHashMap<String, Object> json) throws ApiException {

	Adapter adapter = getAdapter(adapterName);

	IReceiver receiver = adapter.getReceiverByName(receiverName);
	if(receiver == null) {
		throw new ApiException("Receiver ["+receiverName+"] not found!");
	}

	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")) {//Start or stop an adapter!
			String action = null;

			if(value.equals("stop")) { action = "stopreceiver"; }
			else if(value.equals("start")) { action = "startreceiver"; }
			else if(value.equals("incthread")) { action = "incthreads"; }
			else if(value.equals("decthread")) { action = "decthreads"; }

			if(StringUtils.isEmpty(action))
				throw new ApiException("unknown or empty action ["+action+"]");

			getIbisManager().handleAdapter(action, "", adapterName, receiverName, null, false);
			response.entity("{\"status\":\"ok\"}");
		}
	}

	return response.build();
}
 
源代码28 项目: quarkus-quickstarts   文件: FruitResource.java
@GET
@Path("{id}")
public Uni<Response> getSingle(@PathParam Long id) {
    return Fruit.findById(client, id)
            .onItem().apply(fruit -> fruit != null ? Response.ok(fruit) : Response.status(Status.NOT_FOUND))
            .onItem().apply(ResponseBuilder::build);
}
 
/**
 * Creates a mock WDSBlueMixProxyResource object with mocked status code and entity wrapped in a mock response.
 */
protected WDSBlueMixProxyResource mock_bluemix_rest_client_is_created(int status_code, Object entity) throws Exception {
    wdsresource = mock(WDSBlueMixProxyResource.class);
    ResponseBuilder responseBuilder = mock(ResponseBuilder.class);
    response = mock(Response.class);
    when(response.getStatus()).thenReturn(status_code);
    when(response.getEntity()).thenReturn(entity);
    when((responseBuilder).build()).thenReturn(response);
    return wdsresource;
}
 
源代码30 项目: nifi   文件: ApplicationResource.java
/**
 * Edit the response headers to indicating no caching.
 *
 * @param response response
 * @return builder
 */
protected ResponseBuilder noCache(final ResponseBuilder response) {
    final CacheControl cacheControl = new CacheControl();
    cacheControl.setPrivate(true);
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    return response.cacheControl(cacheControl);
}