Java Code Examples for javax.ws.rs.core.Response.ResponseBuilder

The following examples show how to use javax.ws.rs.core.Response.ResponseBuilder. These examples are extracted from open source projects. 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 Project: govpay   Author: link-it   File: BaseController.java    License: GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #2
Source Project: aries-jax-rs-whiteboard   Author: apache   File: SecurityManagerAssociatingFilter.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #3
Source Project: cxf   Author: apache   File: RequestImpl.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source Project: secure-data-service   Author: inbloom   File: BasicClient.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #5
Source Project: govpay   Author: link-it   File: BaseController.java    License: GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #6
Source Project: quarkus   Author: quarkusio   File: ResteasyViolationExceptionMapper.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #7
Source Project: io   Author: fujitsu-pio   File: MessageODataResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 受信/送信メッセージ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();
}
 
Example #8
Source Project: org.openntf.domino   Author: OpenNTF   File: FramedResource.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source Project: secure-data-service   Author: inbloom   File: BulkExtractTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source Project: XPagesExtensionLibrary   Author: OpenNTF   File: EventResource.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #11
Source Project: io   Author: fujitsu-pio   File: AbstractODataResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source Project: iaf   Author: ibissource   File: ShowConfigurationStatus.java    License: Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example #13
Source Project: gossip   Author: syhily   File: GossipValidateErrorProvider.java    License: MIT License 6 votes vote down vote up
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();
}
 
Example #14
Source Project: apicurio-studio   Author: Apicurio   File: DesignsResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #15
Source Project: hadoop-ozone   Author: apache   File: ObjectEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
private void addLastModifiedDate(
    ResponseBuilder responseBuilder, OzoneKeyDetails key) {

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

  responseBuilder
      .header(LAST_MODIFIED,
          RFC1123Util.FORMAT.format(lastModificationTime));
}
 
Example #16
Source Project: aerogear-unifiedpush-server   Author: aerogear   File: PushApplicationEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #17
Source Project: Knowage-Server   Author: KnowageLabs   File: DossierActivityResource.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@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);
	}

}
 
Example #18
Source Project: syncope   Author: apache   File: GroupServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #19
Source Project: ctsms   Author: phoenixctms   File: ProbandAddressResource.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@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();
}
 
Example #20
Source Project: everrest   Author: codenvy   File: ContainerRequest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source Project: FHIR   Author: IBM   File: Delete.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #22
Source Project: cxf   Author: apache   File: ResponseBuilderImpl.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #23
Source Project: govpay   Author: link-it   File: BaseController.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected ResponseBuilder handleResponseOk(ResponseBuilder responseBuilder, String transactionId) {
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId);
	else 
		return responseBuilder;
}
 
Example #24
Source Project: everrest   Author: codenvy   File: ResponseImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ResponseBuilder contentLocation(URI location) {
    if (location == null) {
        headers.remove(CONTENT_LOCATION);
    } else {
        headers.putSingle(CONTENT_LOCATION, location);
    }
    return this;
}
 
Example #25
Source Project: guacamole-client   Author: apache   File: StreamResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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();

}
 
Example #26
Source Project: iaf   Author: ibissource   File: ShowConfigurationStatus.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #27
Source Project: quarkus-quickstarts   Author: quarkusio   File: FruitResource.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source Project: movieapp-dialog   Author: germanattanasio   File: WDSBlueMixProxyResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source Project: nifi   Author: apache   File: ApplicationResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #30
Source Project: cxf   Author: apache   File: RequestImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBeforeDate() throws Exception {
    metadata.putSingle("If-Modified-Since", "Tue, 21 Oct 2008 14:00:00 GMT");
    Date serverDate = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH)
        .parse("Tue, 21 Oct 2008 17:00:00 GMT");

    ResponseBuilder rb =
        new RequestImpl(m).evaluatePreconditions(serverDate);
    assertNull("Precondition must be met", rb);
}