Java Code Examples for javax.ws.rs.core.Request#evaluatePreconditions()

The following examples show how to use javax.ws.rs.core.Request#evaluatePreconditions() . 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: 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 2
Source File: CourseWebService.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Get the runstructure of the course by id
 * 
 * @response.representation.200.mediaType application/xml
 * @response.representation.200.doc The run structure of the course
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The course not found
 * @param courseId
 *            The course resourceable's id
 * @param httpRequest
 *            The HTTP request
 * @param request
 *            The REST request
 * @return It returns the XML representation of the <code>Structure</code> object representing the course.
 */
@GET
@Path("runstructure")
@Produces(MediaType.APPLICATION_XML)
public Response findRunStructureById(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest httpRequest, @Context final Request request) {
    if (!isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    final ICourse course = loadCourse(courseId);
    if (course == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    } else if (!isAuthorEditor(course, httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    final VFSItem runStructureItem = course.getCourseBaseContainer().resolve("runstructure.xml");
    final Date lastModified = new Date(runStructureItem.getLastModified());

    final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
    if (response == null) {
        return Response.ok(myXStream.toXML(course.getRunStructure())).build();
    }
    return response.build();
}
 
Example 3
Source File: CourseWebService.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Get the runstructure of the course by id
 * 
 * @response.representation.200.mediaType application/xml
 * @response.representation.200.doc The run structure of the course
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The course not found
 * @param courseId
 *            The course resourceable's id
 * @param httpRequest
 *            The HTTP request
 * @param request
 *            The REST request
 * @return It returns the XML representation of the <code>Structure</code> object representing the course.
 */
@GET
@Path("runstructure")
@Produces(MediaType.APPLICATION_XML)
public Response findRunStructureById(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest httpRequest, @Context final Request request) {
    if (!isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    final ICourse course = loadCourse(courseId);
    if (course == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    } else if (!isAuthorEditor(course, httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    final VFSItem runStructureItem = course.getCourseBaseContainer().resolve("runstructure.xml");
    final Date lastModified = new Date(runStructureItem.getLastModified());

    final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
    if (response == null) {
        return Response.ok(myXStream.toXML(course.getRunStructure())).build();
    }
    return response.build();
}
 
Example 4
Source File: CourseWebService.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Get the editor tree model of the course by id
 * 
 * @response.representation.200.mediaType application/xml
 * @response.representation.200.doc The editor tree model of the course
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The course not found
 * @param courseId
 *            The course resourceable's id
 * @param httpRequest
 *            The HTTP request
 * @param request
 *            The REST request
 * @return It returns the XML representation of the <code>Editor model</code> object representing the course.
 */
@GET
@Path("editortreemodel")
@Produces(MediaType.APPLICATION_XML)
public Response findEditorTreeModelById(@PathParam("courseId") final Long courseId, @Context final HttpServletRequest httpRequest, @Context final Request request) {
    if (!isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    final ICourse course = loadCourse(courseId);
    if (course == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    } else if (!isAuthorEditor(course, httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    final VFSItem editorModelItem = course.getCourseBaseContainer().resolve("editortreemodel.xml");
    final Date lastModified = new Date(editorModelItem.getLastModified());

    final Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
    if (response == null) {
        return Response.ok(myXStream.toXML(course.getEditorTreeModel())).build();
    }
    return response.build();
}
 
Example 5
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 6
Source File: CustomerResource.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@GET
@Path("{id}")
@Produces("application/xml")
public Response getCustomer(@PathParam("id") int id,
                            @HeaderParam("If-None-Match") String sent,
                            @Context Request request)
{
   Customer cust = customerDB.get(id);
   if (cust == null)
   {
      throw new WebApplicationException(Response.Status.NOT_FOUND);
   }

   if (sent == null) System.out.println("No If-None-Match sent by client");

   EntityTag tag = new EntityTag(Integer.toString(cust.hashCode()));

   CacheControl cc = new CacheControl();
   cc.setMaxAge(5);


   Response.ResponseBuilder builder = request.evaluatePreconditions(tag);
   if (builder != null)
   {
      System.out.println("** revalidation on the server was successful");
      builder.cacheControl(cc);
      return builder.build();
   }


   // Preconditions not met!

   cust.setLastViewed(new Date().toString());
   builder = Response.ok(cust, "application/xml");
   builder.cacheControl(cc);
   builder.tag(tag);
   return builder.build();
}
 
Example 7
Source File: CourseAssessmentWebService.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the results of a student at a specific assessable node
 * 
 * @response.representation.200.qname {http://www.example.com}assessableResultsVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc The result of a user at a specific node
 * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_ASSESSABLERESULTSVO}
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The identity or the course not found
 * @param courseId
 *            The course resourceable's id
 * @param nodeId
 *            The ident of the course building block
 * @param identityKey
 *            The id of the user
 * @param httpRequest
 *            The HTTP request
 * @param request
 *            The REST request
 * @return
 */
@GET
@Path("{nodeId}/users/{identityKey}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getCourseNodeResultsForNode(@PathParam("courseId") final Long courseId, @PathParam("nodeId") final Long nodeId,
        @PathParam("identityKey") final Long identityKey, @Context final HttpServletRequest httpRequest, @Context final Request request) {
    if (!RestSecurityHelper.isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    try {
        final Identity userIdentity = getBaseSecurity().loadIdentityByKey(identityKey, false);
        if (userIdentity == null) {
            return Response.serverError().status(Status.NOT_FOUND).build();
        }

        final Date lastModified = userIdentity.getLastLogin();
        Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
        if (response == null) {
            final ICourse course = CourseFactory.loadCourse(courseId);
            if (course == null) {
                return Response.serverError().status(Status.NOT_FOUND).build();
            }

            final AssessableResultsVO results = getNodeResult(userIdentity, course, nodeId);
            response = Response.ok(results).lastModified(lastModified).cacheControl(cc);
        }
        return response.build();
    } catch (final Throwable e) {
        throw new WebApplicationException(e);
    }
}
 
Example 8
Source File: CourseAssessmentWebService.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the results of a student at a specific assessable node
 * 
 * @response.representation.200.qname {http://www.example.com}assessableResultsVO
 * @response.representation.200.mediaType application/xml, application/json
 * @response.representation.200.doc The result of a user at a specific node
 * @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_ASSESSABLERESULTSVO}
 * @response.representation.401.doc The roles of the authenticated user are not sufficient
 * @response.representation.404.doc The identity or the course not found
 * @param courseId
 *            The course resourceable's id
 * @param nodeId
 *            The ident of the course building block
 * @param identityKey
 *            The id of the user
 * @param httpRequest
 *            The HTTP request
 * @param request
 *            The REST request
 * @return
 */
@GET
@Path("{nodeId}/users/{identityKey}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getCourseNodeResultsForNode(@PathParam("courseId") final Long courseId, @PathParam("nodeId") final Long nodeId,
        @PathParam("identityKey") final Long identityKey, @Context final HttpServletRequest httpRequest, @Context final Request request) {
    if (!RestSecurityHelper.isAuthor(httpRequest)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }

    try {
        final Identity userIdentity = getBaseSecurity().loadIdentityByKey(identityKey, false);
        if (userIdentity == null) {
            return Response.serverError().status(Status.NOT_FOUND).build();
        }

        final Date lastModified = userIdentity.getLastLogin();
        Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
        if (response == null) {
            final ICourse course = CourseFactory.loadCourse(courseId);
            if (course == null) {
                return Response.serverError().status(Status.NOT_FOUND).build();
            }

            final AssessableResultsVO results = getNodeResult(userIdentity, course, nodeId);
            response = Response.ok(results).lastModified(lastModified).cacheControl(cc);
        }
        return response.build();
    } catch (final Throwable e) {
        throw new WebApplicationException(e);
    }
}
 
Example 9
Source File: SimpleService.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Response perform(final Request request) {
    final Date lastModified = getLastModified();
    final EntityTag entityTag = getEntityTag();
    ResponseBuilder rb = request.evaluatePreconditions(lastModified, entityTag);
    if (rb == null) {
        rb = Response.ok();
    } else {
        // okay
    }
    return rb.build();
}
 
Example 10
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 11
Source File: AdminStaticResourceController.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Path("/{s:.+}")
@GET
@Consumes
public Response get(@Context UriInfo uriInfo, @Context Request request) throws IOException {
    String path = uriInfo.getPath();
    Optional<ConsoleBundle> consoleBundleOptional = console.findByScriptFile(path);
    Resource resource;
    if (consoleBundleOptional.isPresent()) {
        ConsoleBundle consoleBundle = consoleBundleOptional.get();
        resource = new CombinedResource(path, resourcePaths(consoleBundle), webRoot);
    } else {
        Optional<Resource> optional = webRoot.get(path);
        if (!optional.isPresent()) {
            throw new NotFoundException(String.format("missing resource, path=%s", path));
        }
        resource = optional.get();
    }
    EntityTag eTag = new EntityTag(resource.hash());
    Response.ResponseBuilder builder = request.evaluatePreconditions(eTag);
    if (builder != null) {
        return builder.build();
    }
    builder = Response.ok(resource).type(MediaTypes.getMediaType(Files.getFileExtension(path)));
    builder.tag(eTag);
    CacheControl cacheControl = new CacheControl();
    cacheControl.setMustRevalidate(true);
    builder.cacheControl(cacheControl);
    return builder.build();
}
 
Example 12
Source File: UserWebService.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the portrait of an user
 * 
 * @response.representation.200.mediaType application/octet-stream
 * @response.representation.200.doc The portrait as image
 * @response.representation.404.doc The identity or the portrait not found
 * @param identityKey
 *            The identity key of the user being searched
 * @param request
 *            The REST request
 * @return The image
 */
@GET
@Path("{identityKey}/portrait")
@Produces({ "image/jpeg", "image/jpg", MediaType.APPLICATION_OCTET_STREAM })
public Response getPortrait(@PathParam("identityKey") final Long identityKey, @Context final Request request) {
    try {
        final Identity identity = getBaseSecurity().loadIdentityByKey(identityKey, false);
        if (identity == null) {
            return Response.serverError().status(Status.NOT_FOUND).build();
        }

        final File portraitDir = DisplayPortraitManager.getInstance().getPortraitDir(identity);
        final File portrait = new File(portraitDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME);
        if (!portrait.exists()) {
            return Response.serverError().status(Status.NOT_FOUND).build();
        }

        final Date lastModified = new Date(portrait.lastModified());
        Response.ResponseBuilder response = request.evaluatePreconditions(lastModified);
        if (response == null) {
            response = Response.ok(portrait).lastModified(lastModified).cacheControl(cc);
        }
        return response.build();
    } catch (final Throwable e) {
        throw new WebApplicationException(e);
    }
}
 
Example 13
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 14
Source File: DocumentTemplateBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@GET
@ApiOperation(value = "Download document template file",
        response = File.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Download success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("/{fileName}")
@Compress
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadDocumentTemplateFile(
        @Context Request request,
        @ApiParam(required = false, value = "Range") @HeaderParam("Range") String range,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") final String workspaceId,
        @ApiParam(required = true, value = "Template id") @PathParam("templateId") final String templateId,
        @ApiParam(required = true, value = "File name") @PathParam("fileName") final String fileName,
        @ApiParam(required = false, value = "Type") @QueryParam("type") String type,
        @ApiParam(required = false, value = "Output") @QueryParam("output") String output)
        throws EntityNotFoundException, UserNotActiveException, AccessRightException, NotAllowedException,
        PreconditionFailedException, RequestedRangeNotSatisfiableException, WorkspaceNotEnabledException {


    String fullName = workspaceId + "/document-templates/" + templateId + "/" + fileName;
    BinaryResource binaryResource = documentService.getTemplateBinaryResource(fullName);
    BinaryResourceDownloadMeta binaryResourceDownloadMeta = new BinaryResourceDownloadMeta(binaryResource);

    // Check cache precondition
    Response.ResponseBuilder rb = request.evaluatePreconditions(binaryResourceDownloadMeta.getLastModified(), binaryResourceDownloadMeta.getETag());
    if (rb != null) {
        return rb.build();
    }

    InputStream binaryContentInputStream = null;

    // Set to false because templates are never historized
    boolean isToBeCached = false;


    try {
        if (output != null && !output.isEmpty()) {
            binaryContentInputStream = getConvertedBinaryResource(binaryResource, output, userLocale);
            if(range == null || range.isEmpty()){
                binaryResourceDownloadMeta.setLength(0);
            }
        } else {
            binaryContentInputStream = storageManager.getBinaryResourceInputStream(binaryResource);
        }
        return BinaryResourceDownloadResponseBuilder.prepareResponse(binaryContentInputStream, binaryResourceDownloadMeta, range, isToBeCached);
    } catch (StorageException | FileConversionException e) {
        Streams.close(binaryContentInputStream);
        return BinaryResourceDownloadResponseBuilder.downloadError(e, fullName);
    }
}
 
Example 15
Source File: ETagResponseFilter.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Filter the given container response
 *
 * @param containerResponse the response to use
 */
public void doFilter(GenericContainerResponse containerResponse) {

  // get entity of the response
  Object entity = containerResponse.getEntity();

  // no entity, skip
  if (entity == null) {
    return;
  }

  // Only handle JSON content
  if (!MediaType.APPLICATION_JSON_TYPE.equals(containerResponse.getContentType())) {
    return;
  }

  // Get the request
  ApplicationContext applicationContext = ApplicationContext.getCurrent();
  Request request = applicationContext.getRequest();

  // manage only GET requests
  if (!HttpMethod.GET.equals(request.getMethod())) {
    return;
  }

  // calculate hash with MD5
  HashFunction hashFunction = Hashing.md5();
  Hasher hasher = hashFunction.newHasher();
  boolean hashingSuccess = true;

  // Manage a list
  if (entity instanceof List) {
    List<?> entities = (List) entity;
    for (Object simpleEntity : entities) {
      hashingSuccess = addHash(simpleEntity, hasher);
      if (!hashingSuccess) {
        break;
      }
    }
  } else {
    hashingSuccess = addHash(entity, hasher);
  }

  // if we're able to handle the hash
  if (hashingSuccess) {

    // get result of the hash
    HashCode hashCode = hasher.hash();

    // Create the entity tag
    EntityTag entityTag = new EntityTag(hashCode.toString());

    // Check the etag
    Response.ResponseBuilder builder = request.evaluatePreconditions(entityTag);

    // not modified ?
    if (builder != null) {
      containerResponse.setResponse(builder.tag(entityTag).build());
    } else {
      // it has been changed, so send response with new ETag and entity
      Response.ResponseBuilder responseBuilder =
          Response.fromResponse(containerResponse.getResponse()).tag(entityTag);
      containerResponse.setResponse(responseBuilder.build());
    }
  }
}
 
Example 16
Source File: ProductInstanceBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@GET
@ApiOperation(value = "Download path data iteration file",
        response = File.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Download success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("pathdata/{pathDataId}/iterations/{iteration}/{fileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFileFromPathDataIteration(
        @Context Request request,
        @ApiParam(required = false, value = "Range") @HeaderParam("Range") String range,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") final String workspaceId,
        @ApiParam(required = true, value = "Serial number") @PathParam("serialNumber") final String serialNumber,
        @ApiParam(required = true, value = "Configuration item id") @PathParam("ciId") String configurationItemId,
        @ApiParam(required = true, value = "Path data master id") @PathParam("pathDataId") final int pathDataId,
        @ApiParam(required = true, value = "Path data iteration number") @PathParam("iteration") final int iteration,
        @ApiParam(required = true, value = "File name id") @PathParam("fileName") final String fileName,
        @ApiParam(required = false, value = "Type") @QueryParam("type") String type,
        @ApiParam(required = false, value = "Output") @QueryParam("output") String output)
        throws EntityNotFoundException, UserNotActiveException, AccessRightException, NotAllowedException,
        PreconditionFailedException, RequestedRangeNotSatisfiableException, WorkspaceNotEnabledException {


    String fullName = workspaceId + "/product-instances/" + serialNumber + "/pathdata/" + pathDataId + "/iterations/" + iteration + '/' + fileName;
    BinaryResource binaryResource = getPathDataBinaryResource(fullName);
    BinaryResourceDownloadMeta binaryResourceDownloadMeta = new BinaryResourceDownloadMeta(binaryResource, output, type);

    // Check cache precondition
    Response.ResponseBuilder rb = request.evaluatePreconditions(binaryResourceDownloadMeta.getLastModified(), binaryResourceDownloadMeta.getETag());
    if (rb != null) {
        return rb.build();
    }

    InputStream binaryContentInputStream = null;

    ProductInstanceIterationKey productInstanceIterationKey = new ProductInstanceIterationKey(serialNumber, workspaceId, configurationItemId, iteration);
    ProductInstanceIteration productInstanceIteration = productInstanceManagerLocal.getProductInstanceIteration(productInstanceIterationKey).getProductInstanceMaster().getLastIteration();
    List<PathDataMaster> pathDataMasterList = productInstanceIteration.getPathDataMasterList();

    PathDataMaster pathDataMaster = pathDataMasterList.stream()
            .filter(x -> pathDataId == x.getId())
            .findAny()
            .orElse(null);

    boolean workingCopy = false;
    if(pathDataMaster != null && pathDataMaster.getLastIteration() != null){
        workingCopy = pathDataMaster.getLastIteration().getIteration() == iteration;
    }

    boolean isToBeCached = !workingCopy;

    try {
        binaryContentInputStream = storageManager.getBinaryResourceInputStream(binaryResource);
        return BinaryResourceDownloadResponseBuilder.prepareResponse(binaryContentInputStream, binaryResourceDownloadMeta, range, isToBeCached);
    } catch (StorageException e) {
        Streams.close(binaryContentInputStream);
        return BinaryResourceDownloadResponseBuilder.downloadError(e, fullName);
    }
}
 
Example 17
Source File: ProductInstanceBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@GET
@ApiOperation(value = "Download path data file",
        response = File.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Download success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("pathdata/{pathDataId}/{fileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFileFromPathData(
        @Context Request request,
        @ApiParam(required = false, value = "Range") @HeaderParam("Range") String range,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
        @ApiParam(required = true, value = "Serial number") @PathParam("serialNumber") String serialNumber,
        @ApiParam(required = true, value = "Configuration item id") @PathParam("ciId") String configurationItemId,
        @ApiParam(required = true, value = "Path data master id") @PathParam("pathDataId") final int pathDataId,
        @ApiParam(required = true, value = "File name") @PathParam("fileName") final String fileName,
        @ApiParam(required = false, value = "Type") @QueryParam("type") String type,
        @ApiParam(required = false, value = "Output") @QueryParam("output") String output)
        throws EntityNotFoundException, UserNotActiveException, AccessRightException,
        NotAllowedException, PreconditionFailedException,
        RequestedRangeNotSatisfiableException, WorkspaceNotEnabledException {


    String fullName = workspaceId + "/product-instances/" + serialNumber + "/pathdata/" + pathDataId + "/" + fileName;
    BinaryResource binaryResource = getPathDataBinaryResource(fullName);
    BinaryResourceDownloadMeta binaryResourceDownloadMeta = new BinaryResourceDownloadMeta(binaryResource, output, type);

    // Check cache precondition
    Response.ResponseBuilder rb = request.evaluatePreconditions(binaryResourceDownloadMeta.getLastModified(), binaryResourceDownloadMeta.getETag());
    if (rb != null) {
        return rb.build();
    }

    InputStream binaryContentInputStream = null;

    // TODO : It seems this method is not used anywhere (to be confirmed). This variable is set only for refactoring consideration
    boolean isToBeCached = false;

    try {
        binaryContentInputStream = storageManager.getBinaryResourceInputStream(binaryResource);
        return BinaryResourceDownloadResponseBuilder.prepareResponse(binaryContentInputStream, binaryResourceDownloadMeta, range, isToBeCached);
    } catch (StorageException e) {
        Streams.close(binaryContentInputStream);
        return BinaryResourceDownloadResponseBuilder.downloadError(e, fullName);
    }
}
 
Example 18
Source File: ProductInstanceBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@GET
@ApiOperation(value = "Download product instance file",
        response = File.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Download success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("iterations/{iteration}/{fileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFileFromProductInstance(
        @Context Request request,
        @ApiParam(required = false, value = "Range") @HeaderParam("Range") String range,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") String workspaceId,
        @ApiParam(required = true, value = "Configuration item id") @PathParam("ciId") String configurationItemId,
        @ApiParam(required = true, value = "Serial number") @PathParam("serialNumber") String serialNumber,
        @ApiParam(required = true, value = "Product instance iteration") @PathParam("iteration") int iteration,
        @ApiParam(required = true, value = "File name") @PathParam("fileName") final String fileName,
        @ApiParam(required = false, value = "Type") @QueryParam("type") String type,
        @ApiParam(required = false, value = "Output") @QueryParam("output") String output)
        throws EntityNotFoundException, UserNotActiveException, AccessRightException,
        NotAllowedException, PreconditionFailedException,
        RequestedRangeNotSatisfiableException, WorkspaceNotEnabledException {


    String fullName = workspaceId + "/product-instances/" + serialNumber + "/iterations/" + iteration + "/" + fileName;
    BinaryResource binaryResource = getBinaryResource(fullName);
    BinaryResourceDownloadMeta binaryResourceDownloadMeta = new BinaryResourceDownloadMeta(binaryResource, output, type);

    // Check cache precondition
    Response.ResponseBuilder rb = request.evaluatePreconditions(binaryResourceDownloadMeta.getLastModified(), binaryResourceDownloadMeta.getETag());
    if (rb != null) {
        return rb.build();
    }
    InputStream binaryContentInputStream = null;

    ProductInstanceMasterKey productInstanceMasterKey = new ProductInstanceMasterKey(serialNumber, workspaceId, configurationItemId);

    boolean workingCopy = productInstanceManagerLocal.getProductInstanceIterations(productInstanceMasterKey).size() == iteration;

    boolean isToBeCached = !workingCopy;

    try {
        binaryContentInputStream = storageManager.getBinaryResourceInputStream(binaryResource);
        return BinaryResourceDownloadResponseBuilder.prepareResponse(binaryContentInputStream, binaryResourceDownloadMeta, range, isToBeCached);
    } catch (StorageException e) {
        Streams.close(binaryContentInputStream);
        return BinaryResourceDownloadResponseBuilder.downloadError(e, fullName);
    }

}
 
Example 19
Source File: PartTemplateBinaryResource.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@GET
@ApiOperation(value = "Download part template file",
        response = File.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Download success"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden"),
        @ApiResponse(code = 500, message = "Internal server error")
})
@Path("/{fileName}")
@Compress
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadPartTemplateFile(
        @Context Request request,
        @ApiParam(required = false, value = "Range") @HeaderParam("Range") String range,
        @ApiParam(required = true, value = "Workspace id") @PathParam("workspaceId") final String workspaceId,
        @ApiParam(required = true, value = "Template id") @PathParam("templateId") final String templateId,
        @ApiParam(required = true, value = "File name") @PathParam("fileName") final String fileName)
        throws EntityNotFoundException, UserNotActiveException, AccessRightException, NotAllowedException,
        PreconditionFailedException, RequestedRangeNotSatisfiableException, WorkspaceNotEnabledException {


    String fullName = workspaceId + "/part-templates/" + templateId + "/" + fileName;
    BinaryResource binaryResource = productService.getTemplateBinaryResource(fullName);
    BinaryResourceDownloadMeta binaryResourceDownloadMeta = new BinaryResourceDownloadMeta(binaryResource);

    // Check cache precondition
    Response.ResponseBuilder rb = request.evaluatePreconditions(binaryResourceDownloadMeta.getLastModified(), binaryResourceDownloadMeta.getETag());
    if (rb != null) {
        return rb.build();
    }

    InputStream binaryContentInputStream = null;

    // set to false because templates are never historized.
    boolean isToBeCached = false;

    try {
        binaryContentInputStream = storageManager.getBinaryResourceInputStream(binaryResource);
        return BinaryResourceDownloadResponseBuilder.prepareResponse(binaryContentInputStream, binaryResourceDownloadMeta, range, isToBeCached);
    } catch (StorageException e) {
        Streams.close(binaryContentInputStream);
        return BinaryResourceDownloadResponseBuilder.downloadError(e, fullName);
    }

}
 
Example 20
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);
	}
}