Java Code Examples for javax.ws.rs.core.CacheControl#setPrivate()

The following examples show how to use javax.ws.rs.core.CacheControl#setPrivate() . 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 File: BookStore.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/books/response3/{bookId}/")
@Produces("application/xml")
public Response getBookAsResponse3(@PathParam("bookId") String id,
                                   @HeaderParam("If-Modified-Since") String modifiedSince
) throws BookNotFoundFault {
    Book entity = doGetBook(id);

    EntityTag etag = new EntityTag(Integer.toString(entity.hashCode()));

    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(1);
    cacheControl.setPrivate(true);

    if (modifiedSince != null) {
        return Response.status(304).tag(etag)
            .cacheControl(cacheControl).lastModified(new Date()).build();
    } else {
        return Response.ok().tag(etag).entity(entity)
            .cacheControl(cacheControl).lastModified(new Date()).build();
    }
}
 
Example 2
Source File: TermsResource.java    From org.openntf.domino with 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) {
		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 3
Source File: FramedResource.java    From org.openntf.domino with 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 4
Source File: SearchResource.java    From org.openntf.domino with 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) {
		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 5
Source File: MCRViewerResource.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private Response showViewer(HttpServletRequest request, Request jaxReq) throws Exception {
    MCRContent content = getContent(request);
    String contentETag = content.getETag();
    Response.ResponseBuilder responseBuilder = null;
    EntityTag eTag = contentETag == null ? null : new EntityTag(contentETag);
    if (eTag != null) {
        responseBuilder = jaxReq.evaluatePreconditions(eTag);
    }
    if (responseBuilder == null) {
        responseBuilder = Response.ok(content.asByteArray(), MediaType.valueOf(content.getMimeType()));
    }
    if (eTag != null) {
        responseBuilder.tag(eTag);
    }
    if (content.isUsingSession()) {
        CacheControl cc = new CacheControl();
        cc.setPrivate(true);
        cc.setMaxAge(0);
        cc.setMustRevalidate(true);
        responseBuilder.cacheControl(cc);
    }
    return responseBuilder.build();
}
 
Example 6
Source File: CacheControlHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiplePrivateFields() {
    CacheControl cc = new CacheControl();
    cc.setPrivate(true);
    cc.getPrivateFields().add("a");
    cc.getPrivateFields().add("b");
    assertTrue(cc.toString().contains("private=\"a,b\""));
}
 
Example 7
Source File: ProcessorWebUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
static Response.ResponseBuilder applyCacheControl(Response.ResponseBuilder response) {
    CacheControl cacheControl = new CacheControl();
    cacheControl.setPrivate(true);
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    return response.cacheControl(cacheControl);
}
 
Example 8
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books/response2/{bookId}/")
@Produces("application/xml")
public Response getBookAsResponse2(@PathParam("bookId") String id) throws BookNotFoundFault {
    Book entity = doGetBook(id);
    EntityTag etag = new EntityTag(Integer.toString(entity.hashCode()));

    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(1);
    cacheControl.setPrivate(true);

    return Response.ok().tag(etag).entity(entity).cacheControl(cacheControl).build();
}
 
Example 9
Source File: ProcessorWebUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
static Response.ResponseBuilder applyCacheControl(Response.ResponseBuilder response) {
    CacheControl cacheControl = new CacheControl();
    cacheControl.setPrivate(true);
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    return response.cacheControl(cacheControl);
}
 
Example 10
Source File: SwaggerYamlApi.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves swagger definition of Publisher REST API and returns
 * 
 * @return swagger definition of Publisher REST API in yaml format
 */
@GET
@Consumes({ "text/yaml" })
@Produces({ "text/yaml" })
@io.swagger.annotations.ApiOperation(value = "Get Swagger Definition", notes = "Get Swagger Definition of Publisher REST API.", response = Void.class)
@io.swagger.annotations.ApiResponses(value = {
        @io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nSwagger Definition is returned."),

        @io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource."),

        @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported") })

public Response swaggerYamlGet() throws APIManagementException {
    try {
        if (openAPIDef == null) {
            synchronized (LOCK_PUBLISHER_OPENAPI_DEF) {
                if (openAPIDef == null) {
                    String definition = IOUtils
                            .toString(this.getClass().getResourceAsStream("/publisher-api.yaml"), "UTF-8");
                    openAPIDef = new OAS2Parser().removeExamplesFromSwagger(definition);
                }
            }
        }
        RESTAPICacheConfiguration restapiCacheConfiguration = APIUtil.getRESTAPICacheConfig();
        if (restapiCacheConfiguration.isCacheControlHeadersEnabled()) {
            CacheControl cacheControl = new CacheControl();
            cacheControl.setMaxAge(restapiCacheConfiguration.getCacheControlHeadersMaxAge());
            cacheControl.setPrivate(true);
            return Response.ok().entity(openAPIDef).cacheControl(cacheControl).build();
        } else {
            return Response.ok().entity(openAPIDef).build();
        }
    } catch (IOException e) { 
        String errorMessage = "Error while retrieving the swagger definition of the Publisher API";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 11
Source File: MCRCacheFilter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private void addAuthorizationHeaderException(CacheControl cc, boolean isPrivate, boolean isNoCache) {
    cc.setPrivate(true);
    if (!cc.getPrivateFields().contains(HttpHeaders.AUTHORIZATION) && !isPrivate) {
        cc.getPrivateFields().add(HttpHeaders.AUTHORIZATION);
    }
    cc.setNoCache(true);
    if (!cc.getNoCacheFields().contains(HttpHeaders.AUTHORIZATION) && !isNoCache) {
        cc.getNoCacheFields().add(HttpHeaders.AUTHORIZATION);
    }
}
 
Example 12
Source File: RuleResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
private ResponseBuilder noCache(ResponseBuilder response) {
    CacheControl cacheControl = new CacheControl();
    cacheControl.setPrivate(true);
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    return response.cacheControl(cacheControl);
}
 
Example 13
Source File: FeedREST.java    From commafeed with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 14
Source File: AdminResource.java    From Graphene with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("version")
@Produces(MediaType.APPLICATION_JSON)
public Response getVersionInfo() {

	CacheControl cc = new CacheControl();
	cc.setMaxAge(60 * 60 * 24); // seconds
	cc.setPrivate(true);

	return Response
               .status(Response.Status.OK)
               .cacheControl(cc)
               .entity(graphene.getVersionInfo())
               .build();
   }
 
Example 15
Source File: DataManagementImpl.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Response getDictItemByItemCode(HttpServletRequest request, HttpHeaders header, Company company,
		Locale locale, User user, ServiceContext serviceContext, String code, String itemCode) {
	DictcollectionInterface dictItemDataUtil = new DictCollectionActions();

	long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));

	DictItem dictItem = dictItemDataUtil.getDictItemByItemCode(code, itemCode, groupId, serviceContext);

	if (Validator.isNotNull(dictItem)) {

		DictItemModel dictItemModel = DataManagementUtils.mapperDictItemModel(dictItem, dictItemDataUtil,
				user.getUserId(), company.getCompanyId(), groupId, serviceContext);
		CacheControl cc = new CacheControl();
		cc.setMaxAge(86400);
		cc.setPrivate(true);	
		return Response.status(200).entity(dictItemModel).cacheControl(cc).build();

	} else {

		ErrorMsg error = new ErrorMsg();

		error.setMessage("not found!");
		error.setCode(404);
		error.setDescription("not found!");

		return Response.status(409).entity(error).build();

	}
}
 
Example 16
Source File: DataManagementImpl.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Response getDictCollectionDetail(HttpServletRequest request, HttpHeaders header, Company company,
		Locale locale, User user, ServiceContext serviceContext, String code, Request requestCC) {
	DictcollectionInterface dictItemDataUtil = new DictCollectionActions();
	long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));

	DictCollection dictCollection = dictItemDataUtil.getDictCollectionDetail(code, groupId);
	EntityTag etag = new EntityTag(Integer.toString(Long.valueOf(groupId).hashCode()));
    ResponseBuilder builder = requestCC.evaluatePreconditions(etag);	
    
	if (Validator.isNotNull(dictCollection)) {
		DictCollectionModel dictCollectionModel = DataManagementUtils.mapperDictCollectionModel(dictCollection);
		if (OpenCPSConfigUtil.isHttpCacheEnable() && builder == null) {
			builder = Response.status(200);
			CacheControl cc = new CacheControl();
			cc.setMaxAge(OpenCPSConfigUtil.getHttpCacheMaxAge());
			cc.setPrivate(true);	
			// return json object after update

			return builder.entity(dictCollectionModel).cacheControl(cc).build();				
		}
		else {
			return builder.entity(dictCollectionModel).build();
		}

	} else {
		return null;
	}
}
 
Example 17
Source File: FramedCollectionResource.java    From org.openntf.domino with Apache License 2.0 5 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) {
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE).entity(jsonEntity);
		berg.lastModified(lastMod);
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	} else {
		// System.out.println("TEMP DEBUG got a hit for etag " +
		// etagSource);
	}
	return berg;
}
 
Example 18
Source File: RuleResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ResponseBuilder noCache(ResponseBuilder response) {
    CacheControl cacheControl = new CacheControl();
    cacheControl.setPrivate(true);
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    return response.cacheControl(cacheControl);
}
 
Example 19
Source File: DataManagementImpl.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Response getDictItems(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
		User user, ServiceContext serviceContext, String code, DataSearchModel query, Request requestCC) {
	DictcollectionInterface dictItemDataUtil = new DictCollectionActions();
	DictItemResults result = new DictItemResults();
	SearchContext searchContext = new SearchContext();
	searchContext.setCompanyId(company.getCompanyId());

	try {

		if (query.getEnd() == 0) {

			query.setStart(-1);

			query.setEnd(-1);

		}

		long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));
		LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

		if ("ADMINISTRATIVE_REGION".equalsIgnoreCase(code))
			groupId = 0;

		params.put("groupId", groupId);
		params.put("keywords", query.getKeywords());
		params.put("itemLv", query.getLevel());
		params.put(DictItemTerm.PARENT_ITEM_CODE, query.getParent());
		params.put(DictItemTerm.DICT_COLLECTION_CODE, code);

		Sort[] sorts = null;
		
		if (Validator.isNull(query.getSort())) {
			sorts = new Sort[] {
					SortFactoryUtil.create(DictItemTerm.SIBLING_SEARCH + "_Number_sortable", Sort.INT_TYPE, false) };
		} else {
			sorts = new Sort[] {
				SortFactoryUtil.create(query.getSort() + "_sortable", Sort.STRING_TYPE, false) };
		}
		

		JSONObject jsonData = dictItemDataUtil.getDictItems(user.getUserId(), company.getCompanyId(), groupId,
				params, sorts, query.getStart(), query.getEnd(), serviceContext);

		result.setTotal(jsonData.getLong("total"));
		result.getDictItemModel()
				.addAll(DataManagementUtils.mapperDictItemModelList((List<Document>) jsonData.get("data")));

		EntityTag etag = new EntityTag(Integer.toString(Long.valueOf(groupId).hashCode()));
		ResponseBuilder builder = requestCC.evaluatePreconditions(etag);
		if (OpenCPSConfigUtil.isHttpCacheEnable() && builder == null) {
			CacheControl cc = new CacheControl();
			cc.setMaxAge(OpenCPSConfigUtil.getHttpCacheMaxAge());
			cc.setPrivate(true);
			return Response.status(200).entity(result).cacheControl(cc).build();
		} else {
			return Response.status(200).entity(result).build();
		}

	} catch (Exception e) {
		return BusinessExceptionImpl.processException(e);
	}
}
 
Example 20
Source File: CacheControlHeaderProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
public CacheControl fromString(String c) {
    boolean isPrivate = false;
    List<String> privateFields = new ArrayList<>();
    boolean noCache = false;
    List<String> noCacheFields = new ArrayList<>();
    boolean noStore = false;
    boolean noTransform = false;
    boolean mustRevalidate = false;
    boolean proxyRevalidate = false;
    int maxAge = -1;
    int sMaxAge = -1;
    Map<String, String> extensions = new HashMap<>();

    String[] tokens = getTokens(c);
    for (String rawToken : tokens) {
        String token = rawToken.trim();
        if (token.startsWith(MAX_AGE)) {
            maxAge = Integer.parseInt(token.substring(MAX_AGE.length() + 1));
        } else if (token.startsWith(SMAX_AGE)) {
            sMaxAge = Integer.parseInt(token.substring(SMAX_AGE.length() + 1));
        } else if (token.startsWith(PUBLIC)) {
            // ignore
        } else if (token.startsWith(NO_STORE)) {
            noStore = true;
        } else if (token.startsWith(NO_TRANSFORM)) {
            noTransform = true;
        } else if (token.startsWith(MUST_REVALIDATE)) {
            mustRevalidate = true;
        } else if (token.startsWith(PROXY_REVALIDATE)) {
            proxyRevalidate = true;
        } else if (token.startsWith(PRIVATE)) {
            isPrivate = true;
            addFields(privateFields, token);
        }  else if (token.startsWith(NO_CACHE)) {
            noCache = true;
            addFields(noCacheFields, token);
        } else {
            String[] extPair = token.split("=");
            String value = extPair.length == 2 ? extPair[1] : "";
            extensions.put(extPair[0], value);
        }
    }

    CacheControl cc = new CacheControl();
    cc.setMaxAge(maxAge);
    cc.setSMaxAge(sMaxAge);
    cc.setPrivate(isPrivate);
    cc.getPrivateFields().addAll(privateFields);
    cc.setMustRevalidate(mustRevalidate);
    cc.setProxyRevalidate(proxyRevalidate);
    cc.setNoCache(noCache);
    cc.getNoCacheFields().addAll(noCacheFields);
    cc.setNoStore(noStore);
    cc.setNoTransform(noTransform);
    cc.getCacheExtension().putAll(extensions);

    return cc;
}