Search in sources :

Example 1 with FeatureResponseBuilder

use of org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder in project eclipselink by eclipse-ee4j.

the class AbstractEntityResource method singleEntityResponse.

private Object singleEntityResponse(PersistenceContext context, Object entity, UriInfo uriInfo) {
    FeatureSet featureSet = context.getSupportedFeatureSet();
    FeatureResponseBuilder responseBuilder = featureSet.getResponseBuilder(Feature.NO_PAGING);
    return responseBuilder.buildSingleEntityResponse(context, getQueryParameters(uriInfo), entity, uriInfo);
}
Also used : FeatureResponseBuilder(org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder) FeatureSet(org.eclipse.persistence.jpa.rs.features.FeatureSet)

Example 2 with FeatureResponseBuilder

use of org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder in project eclipselink by eclipse-ee4j.

the class AbstractEntityResource method findAttributeInternal.

protected Response findAttributeInternal(String version, String persistenceUnit, String type, String id, String attribute, HttpHeaders headers, UriInfo uriInfo) {
    JPARSLogger.entering(CLASS_NAME, "findAttributeInternal", new Object[] { "GET", version, persistenceUnit, type, id, attribute, uriInfo.getRequestUri().toASCIIString() });
    EntityManager em = null;
    try {
        PersistenceContext context = getPersistenceContext(persistenceUnit, type, uriInfo.getBaseUri(), version, null);
        Object entityId = IdHelper.buildId(context, type, id);
        em = context.getEmf().createEntityManager(getMatrixParameters(uriInfo, persistenceUnit));
        Object entity = em.find(context.getClass(type), entityId, getQueryParameters(uriInfo));
        DatabaseSession serverSession = context.getServerSession();
        ClassDescriptor descriptor = serverSession.getClassDescriptor(context.getClass(type));
        if (descriptor == null) {
            throw JPARSException.classOrClassDescriptorCouldNotBeFoundForEntity(type, persistenceUnit);
        }
        DatabaseMapping attributeMapping = descriptor.getMappingForAttributeName(attribute);
        if ((attributeMapping == null) || (entity == null)) {
            throw JPARSException.databaseMappingCouldNotBeFoundForEntityAttribute(attribute, type, id, persistenceUnit);
        }
        if (!attributeMapping.isCollectionMapping()) {
            Object result = attributeMapping.getRealAttributeValueFromAttribute(attributeMapping.getAttributeValueFromObject(entity), entity, (AbstractSession) serverSession);
            if (result == null) {
                JPARSLogger.error(context.getSessionLog(), "jpars_could_not_find_entity_for_attribute", new Object[] { attribute, type, id, persistenceUnit });
                throw JPARSException.attributeCouldNotBeFoundForEntity(attribute, type, id, persistenceUnit);
            }
            final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
            return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, responseBuilder, null);
        }
        ReadQuery query = (ReadQuery) ((((ForeignReferenceMapping) attributeMapping).getSelectionQuery()).clone());
        if (query == null) {
            throw JPARSException.selectionQueryForAttributeCouldNotBeFoundForEntity(attribute, type, id, persistenceUnit);
        }
        final FeatureSet featureSet = context.getSupportedFeatureSet();
        final AbstractSession clientSession = context.getClientSession(em);
        // Fields filtering
        FieldsFilter fieldsFilter = null;
        if (context.getSupportedFeatureSet().isSupported(Feature.FIELDS_FILTERING)) {
            final FieldsFilteringValidator fieldsFilteringValidator = new FieldsFilteringValidator(uriInfo);
            if (fieldsFilteringValidator.isFeatureApplicable()) {
                fieldsFilter = fieldsFilteringValidator.getFilter();
            }
        }
        // Pagination
        if (featureSet.isSupported(Feature.PAGING)) {
            final PageableFieldValidator validator = new PageableFieldValidator(entity.getClass(), attribute, uriInfo);
            if (validator.isFeatureApplicable()) {
                // Adding extra one to detect are there more rows or not. It will be removed later
                // on in response processor.
                query.setMaxRows(validator.getLimit() + validator.getOffset() + 1);
                query.setFirstResult(validator.getOffset());
                // We need to add limit and offset to query parameters because request builder reads it from there
                final Map<String, Object> queryParams = getQueryParameters(uriInfo);
                queryParams.put(QueryParameters.JPARS_PAGING_LIMIT, String.valueOf(validator.getLimit()));
                queryParams.put(QueryParameters.JPARS_PAGING_OFFSET, String.valueOf(validator.getOffset()));
                // check orderBy, and generate a warning if there is none
                checkOrderBy(context, query);
                final Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
                final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.PAGING);
                return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, queryParams, headers, uriInfo, responseBuilder, fieldsFilter);
            }
        }
        final Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
        final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
        return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, responseBuilder, fieldsFilter);
    } catch (Exception ex) {
        throw JPARSException.exceptionOccurred(ex);
    } finally {
        if (em != null) {
            if (em.isOpen()) {
                em.close();
            }
        }
    }
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) DatabaseSession(org.eclipse.persistence.sessions.DatabaseSession) PersistenceContext(org.eclipse.persistence.jpa.rs.PersistenceContext) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) FieldsFilteringValidator(org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilteringValidator) JPARSException(org.eclipse.persistence.jpa.rs.exceptions.JPARSException) PageableFieldValidator(org.eclipse.persistence.jpa.rs.features.paging.PageableFieldValidator) FeatureResponseBuilder(org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder) EntityManager(jakarta.persistence.EntityManager) ForeignReferenceMapping(org.eclipse.persistence.mappings.ForeignReferenceMapping) FieldsFilter(org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilter) FeatureSet(org.eclipse.persistence.jpa.rs.features.FeatureSet) ReadQuery(org.eclipse.persistence.queries.ReadQuery) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 3 with FeatureResponseBuilder

use of org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder in project eclipselink by eclipse-ee4j.

the class AbstractSingleResultQueryResource method namedQuerySingleResultInternal.

/**
 * Named query single result.
 *
 * @param version the version
 * @param persistenceUnit the persistence unit
 * @param queryName the query name
 * @param headers the http headers
 * @param uriInfo the uriInfo
 * @return the response
 */
@SuppressWarnings("rawtypes")
protected Response namedQuerySingleResultInternal(String version, String persistenceUnit, String queryName, HttpHeaders headers, UriInfo uriInfo) {
    JPARSLogger.entering(CLASS_NAME, "namedQuerySingleResultInternal", new Object[] { "GET", version, persistenceUnit, queryName, uriInfo.getRequestUri().toASCIIString() });
    try {
        final PersistenceContext context = getPersistenceContext(persistenceUnit, null, uriInfo.getBaseUri(), version, null);
        final Query query = context.buildQuery(getMatrixParameters(uriInfo, persistenceUnit), queryName, getMatrixParameters(uriInfo, queryName), getQueryParameters(uriInfo));
        final DatabaseQuery dbQuery = ((EJBQueryImpl<?>) query).getDatabaseQuery();
        final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
        if (dbQuery instanceof ReportQuery) {
            final List<ReportItem> reportItems = ((ReportQuery) dbQuery).getItems();
            final Object queryResults = query.getSingleResult();
            final Object response = responseBuilder.buildSingleResultQueryResponse(context, getQueryParameters(uriInfo), queryResults, reportItems, uriInfo);
            if (response != null && response instanceof SingleResultQuery) {
                final SingleResultQuery singleResultQuery = (SingleResultQuery) response;
                final List<JAXBElement<?>> item = singleResultQuery.getFields();
                if ((item != null) && (item.size() == 1)) {
                    // Fix for Bug 393320 - JPA-RS: Respect the Accept Header for a singleResultQuery
                    // If there is only one item in the select clause and if value of that item is binary, we will create a response with
                    // that binary data without converting its to Base64.
                    JAXBElement element = item.get(0);
                    Object elementValue = element.getValue();
                    if (elementValue instanceof byte[]) {
                        List<MediaType> acceptableMediaTypes = headers.getAcceptableMediaTypes();
                        if (acceptableMediaTypes.contains(MediaType.APPLICATION_OCTET_STREAM_TYPE)) {
                            return Response.ok(new StreamingOutputMarshaller(context, elementValue, headers.getAcceptableMediaTypes())).build();
                        }
                    }
                }
                return Response.ok(new StreamingOutputMarshaller(context, response, headers.getAcceptableMediaTypes())).build();
            } else {
                // something went wrong with the descriptors, return error
                throw JPARSException.responseCouldNotBeBuiltForNamedQueryRequest(queryName, context.getName());
            }
        }
        final Object queryResult = query.getSingleResult();
        return Response.ok(new StreamingOutputMarshaller(context, responseBuilder.buildSingleEntityResponse(context, getQueryParameters(uriInfo), queryResult, uriInfo), headers.getAcceptableMediaTypes())).build();
    } catch (Exception ex) {
        throw JPARSException.exceptionOccurred(ex);
    }
}
Also used : ReportQuery(org.eclipse.persistence.queries.ReportQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) Query(jakarta.persistence.Query) SingleResultQuery(org.eclipse.persistence.jpa.rs.util.list.SingleResultQuery) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) ReportQuery(org.eclipse.persistence.queries.ReportQuery) PersistenceContext(org.eclipse.persistence.jpa.rs.PersistenceContext) SingleResultQuery(org.eclipse.persistence.jpa.rs.util.list.SingleResultQuery) JAXBElement(jakarta.xml.bind.JAXBElement) ReportItem(org.eclipse.persistence.internal.queries.ReportItem) EJBQueryImpl(org.eclipse.persistence.internal.jpa.EJBQueryImpl) JPARSException(org.eclipse.persistence.jpa.rs.exceptions.JPARSException) FeatureResponseBuilder(org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder) MediaType(jakarta.ws.rs.core.MediaType) StreamingOutputMarshaller(org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller)

Aggregations

FeatureResponseBuilder (org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder)3 PersistenceContext (org.eclipse.persistence.jpa.rs.PersistenceContext)2 JPARSException (org.eclipse.persistence.jpa.rs.exceptions.JPARSException)2 FeatureSet (org.eclipse.persistence.jpa.rs.features.FeatureSet)2 EntityManager (jakarta.persistence.EntityManager)1 Query (jakarta.persistence.Query)1 MediaType (jakarta.ws.rs.core.MediaType)1 JAXBElement (jakarta.xml.bind.JAXBElement)1 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)1 EJBQueryImpl (org.eclipse.persistence.internal.jpa.EJBQueryImpl)1 ReportItem (org.eclipse.persistence.internal.queries.ReportItem)1 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)1 FieldsFilter (org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilter)1 FieldsFilteringValidator (org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilteringValidator)1 PageableFieldValidator (org.eclipse.persistence.jpa.rs.features.paging.PageableFieldValidator)1 StreamingOutputMarshaller (org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller)1 SingleResultQuery (org.eclipse.persistence.jpa.rs.util.list.SingleResultQuery)1 DatabaseMapping (org.eclipse.persistence.mappings.DatabaseMapping)1 ForeignReferenceMapping (org.eclipse.persistence.mappings.ForeignReferenceMapping)1 DatabaseQuery (org.eclipse.persistence.queries.DatabaseQuery)1