Java 类javax.ws.rs.ext.ContextResolver 实例源码

项目:holon-json    文件:JacksonJsonPropertyBoxProvider.java   
/**
 * Get the {@link PropertySetRefIntrospector} instance to use.
 * @return The {@link PropertySetRefIntrospector} instance to use, from {@link ContextResolver} if available or the
 *         default one
 */
private PropertySetRefIntrospector getPropertySetRefIntrospector() {
    if (propertySetRefIntrospector == null) {
        // init using a contextresolver, if available
        ContextResolver<PropertySetRefIntrospector> contextResolver = providers
                .getContextResolver(PropertySetRefIntrospector.class, MediaType.APPLICATION_JSON_TYPE);
        if (contextResolver != null) {
            propertySetRefIntrospector = contextResolver.getContext(PropertySetRefIntrospector.class);
        }
        if (propertySetRefIntrospector == null) {
            // use default
            propertySetRefIntrospector = PropertySetRefIntrospector.getDefault();
        }
    }
    return propertySetRefIntrospector;
}
项目:holon-json    文件:GsonJsonProvider.java   
/**
 * Get the {@link Gson} instance to use.
 * @return The {@link Gson} instance to use, from {@link ContextResolver} if available or the default one
 */
private Gson getGson() {
    if (gson == null) {
        // init using a contextresolver, if available
        ContextResolver<Gson> contextResolver = providers.getContextResolver(Gson.class,
                MediaType.APPLICATION_JSON_TYPE);
        if (contextResolver != null) {
            gson = contextResolver.getContext(Gson.class);
        }
        if (gson == null) {
            // use default
            gson = GsonConfiguration.builder().create();
        }
    }
    return gson;
}
项目:holon-json    文件:GsonJsonProvider.java   
/**
 * Get the {@link PropertySetRefIntrospector} instance to use.
 * @return The {@link PropertySetRefIntrospector} instance to use, from {@link ContextResolver} if available or the
 *         default one
 */
private PropertySetRefIntrospector getPropertySetRefIntrospector() {
    if (propertySetRefIntrospector == null) {
        // init using a contextresolver, if available
        ContextResolver<PropertySetRefIntrospector> contextResolver = providers
                .getContextResolver(PropertySetRefIntrospector.class, MediaType.APPLICATION_JSON_TYPE);
        if (contextResolver != null) {
            propertySetRefIntrospector = contextResolver.getContext(PropertySetRefIntrospector.class);
        }
        if (propertySetRefIntrospector == null) {
            // use default
            propertySetRefIntrospector = PropertySetRefIntrospector.getDefault();
        }
    }
    return propertySetRefIntrospector;
}
项目:holon-jaxrs    文件:ExampleAuth.java   
public void configureJaxrsApplication() {

        AccountProvider provider = id -> { // <5>
            // a test provider wich always returns an Account with given id and s3cr3t as password
            return Optional.ofNullable(Account.builder(id).credentials(Credentials.builder().secret("s3cr3t").build())
                    .enabled(true).build());
        };

        Realm realm = Realm.builder() // <6>
                .resolver(AuthenticationToken.httpBasicResolver()) // <7>
                .authenticator(Account.authenticator(provider)) // <8>
                .withDefaultAuthorizer().build();

        ContextResolver<Realm> realmContextResolver = new ContextResolver<Realm>() { // <9>

            @Override
            public Realm getContext(Class<?> type) {
                return realm;
            }
        };

        register(realmContextResolver); // <10>
    }
项目:holon-jaxrs    文件:PropertyBoxFormDataProvider.java   
/**
 * Get the {@link PropertySetRefIntrospector} instance to use.
 * @return The {@link PropertySetRefIntrospector} instance to use, from {@link ContextResolver} if available or the
 *         default one
 */
private PropertySetRefIntrospector getPropertySetRefIntrospector() {
    if (_propertySetRefIntrospector == null) {
        // init using a contextresolver, if available
        ContextResolver<PropertySetRefIntrospector> contextResolver = providers
                .getContextResolver(PropertySetRefIntrospector.class, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
        if (contextResolver != null) {
            _propertySetRefIntrospector = contextResolver.getContext(PropertySetRefIntrospector.class);
        }
        if (_propertySetRefIntrospector == null) {
            // use default
            _propertySetRefIntrospector = PropertySetRefIntrospector.getDefault();
        }
    }
    return _propertySetRefIntrospector;
}
项目:holon-jaxrs    文件:PropertyBoxFormDataProvider.java   
/**
 * Get the {@link FormDataPropertyValueSerializer} instance to use.
 * @return The {@link FormDataPropertyValueSerializer} instance to use, from {@link ContextResolver} if available or
 *         the default one
 */
private FormDataPropertyValueSerializer getSerializer() {
    if (_serializer == null) {
        // init using a contextresolver, if available
        ContextResolver<FormDataPropertyValueSerializer> contextResolver = providers.getContextResolver(
                FormDataPropertyValueSerializer.class, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
        if (contextResolver != null) {
            _serializer = contextResolver.getContext(FormDataPropertyValueSerializer.class);
        }
        if (_serializer == null) {
            // use default
            _serializer = FormDataPropertyValueSerializer.getDefault();
        }
    }
    return _serializer;
}
项目:holon-jaxrs    文件:PropertyBoxFormDataProvider.java   
/**
 * Get the {@link FormDataPropertyValueDeserializer} instance to use.
 * @return The {@link FormDataPropertyValueDeserializer} instance to use, from {@link ContextResolver} if available
 *         or the default one
 */
private FormDataPropertyValueDeserializer getDeserializer() {
    if (_deserializer == null) {
        // init using a contextresolver, if available
        ContextResolver<FormDataPropertyValueDeserializer> contextResolver = providers.getContextResolver(
                FormDataPropertyValueDeserializer.class, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
        if (contextResolver != null) {
            _deserializer = contextResolver.getContext(FormDataPropertyValueDeserializer.class);
        }
        if (_deserializer == null) {
            // use default
            _deserializer = FormDataPropertyValueDeserializer.getDefault();
        }
    }
    return _deserializer;
}
项目:holon-jaxrs    文件:ResourceUtils.java   
/**
 * Lookup a resource of given <code>resourceType</code> type, either using a suitable {@link ContextResolver} if
 * <code>providers</code> is not <code>null</code> and a {@link ContextResolver} for given <code>resourceType</code>
 * is available, or trying to obtain the resource from {@link Context} using given <code>resourceType</code> as
 * context resource key.
 * @param <R> Resource type
 * @param caller Caller class
 * @param resourceType Resource type to lookup (not null)
 * @param providers JAX-RS {@link Providers}, if available
 * @return Resource instance, or an empty optional if not available
 */
public static <R> Optional<R> lookupResource(Class<?> caller, Class<R> resourceType, Providers providers) {
    ObjectUtils.argumentNotNull(resourceType, "Resource type must be not null");

    R resource = null;

    // try to use a ContextResolver, if available
    ContextResolver<R> resolver = providers.getContextResolver(resourceType, null);
    if (resolver != null) {
        resource = resolver.getContext(caller);
    }

    if (resource == null) {
        // lookup in context
        resource = Context.get()
                .resource(resourceType,
                        (caller != null) ? caller.getClassLoader() : ClassUtils.getDefaultClassLoader())
                .orElse(null);
    }

    return Optional.ofNullable(resource);
}
项目:geeMVC-Java-MVC-Framework    文件:DefaultProviderFilter.java   
protected List<ContextResolver<?>> sortedList(Map<ProviderKey, ContextResolver<?>> providerMap, MediaType targetMediaType) {
    List<ContextResolver<?>> contextResolvers = new ArrayList<>(providerMap.values());

    Collections.sort(contextResolvers, new Comparator<ContextResolver<?>>() {
        public int compare(ContextResolver<?> cr1, ContextResolver<?> cr2) {

            Set<String> providerMediaTypes1 = mediaTypes(cr1.getClass().getAnnotationsByType(Produces.class));
            Set<String> providerMediaTypes2 = mediaTypes(cr2.getClass().getAnnotationsByType(Produces.class));

            int score1 = relevanceScore(providerMediaTypes1, targetMediaType);
            int score2 = relevanceScore(providerMediaTypes2, targetMediaType);

            if (score1 == score2)
                return 0;

            return (score2 - score1) < 0 ? -1 : 1;
        }
    });

    return contextResolvers;
}
项目:oreva    文件:LinksRequestResource.java   
@POST
public Response createLink(@Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    String payload) {
  log.info(String.format(
      "createLink(%s,%s,%s,%s)",
      sourceEntity.getEntitySetName(),
      sourceEntity.getEntityKey(),
      targetNavProp,
      targetEntityKey));

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  OEntityId newTargetEntity = parseRequestUri(httpHeaders, uriInfo, payload);
  producer.createLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp, newTargetEntity);
  return noContent();
}
项目:oreva    文件:LinksRequestResource.java   
@PUT
public Response updateLink(@Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    String payload) {
  log.info(String.format(
      "updateLink(%s,%s,%s,%s)",
      sourceEntity.getEntitySetName(),
      sourceEntity.getEntityKey(),
      targetNavProp,
      targetEntityKey));

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  OEntityId newTargetEntity = parseRequestUri(httpHeaders, uriInfo, payload);
  producer.updateLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp, targetEntityKey, newTargetEntity);
  return noContent();
}
项目:oreva    文件:LinksRequestResource.java   
@DELETE
public Response deleteLink(@Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext) {
  log.info(String.format(
      "deleteLink(%s,%s,%s,%s)",
      sourceEntity.getEntitySetName(),
      sourceEntity.getEntityKey(),
      targetNavProp,
      targetEntityKey));

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  producer.deleteLink(ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).build(), sourceEntity, targetNavProp, targetEntityKey);
  return noContent();
}
项目:oreva    文件:ServiceDocumentResource.java   
@GET
@Produces({ ODataConstants.APPLICATION_XML_CHARSET_UTF8, ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
public Response getServiceDocument(
    @Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @QueryParam("$format") String format,
    @QueryParam("$callback") String callback) {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  EdmDataServices metadata = producer.getMetadata();

  StringWriter w = new StringWriter();
  FormatWriter<EdmDataServices> fw = FormatWriterFactory.getFormatWriter(EdmDataServices.class, httpHeaders.getAcceptableMediaTypes(), format, callback);
  fw.write(uriInfo, w, metadata);

  return Response.ok(w.toString(), fw.getContentType())
      .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER)
      .build();
}
项目:oreva    文件:ODataBatchPutUnit.java   
@Override
protected Response delegate(HttpHeaders httpHeaders, URI baseUri, ContextResolver<ODataProducer> producerResolver) throws Exception {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);
  OEntity entity = new BatchRequestResource().getRequestEntity(httpHeaders, getResourceHeaders(),
      getUriInfo(),
      getResourceContent(),
      producer.getMetadata(),
      getEnitySetName(),
      OEntityKey.parse(getEntityKey()), false);
  producer.updateEntity(null, getEnitySetName(), entity);
  Response response = Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER)
      .header(ODataConstants.Headers.CONTENT_TYPE, getResourceHeaders().getFirst(ODataConstants.Headers.CONTENT_TYPE))
      .header(ODataConstants.Headers.CONTENT_LENGTH, 0).build();

  return response;
}
项目:oreva    文件:ODataBatchMergeUnit.java   
@Override
protected Response delegate(HttpHeaders httpHeaders, URI baseUri, ContextResolver<ODataProducer> producerResolver) throws Exception {
  ODataProducer producer = producerResolver.getContext(ODataProducer.class);
  OEntity entity = new BatchRequestResource().getRequestEntity(httpHeaders, getResourceHeaders(),
      getUriInfo(),
      getResourceContent(),
      producer.getMetadata(),
      getEnitySetName(),
      OEntityKey.parse(getEntityKey()), false);
  producer.mergeEntity(null, getEnitySetName(), entity);
  Response response = Response.ok().header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER)
      .header(ODataConstants.Headers.CONTENT_TYPE, getResourceHeaders().getFirst(ODataConstants.Headers.CONTENT_TYPE))
      .header(ODataConstants.Headers.CONTENT_LENGTH, 0).build();

  return response;
}
项目:oreva    文件:EntityRequestResource.java   
@GET
@Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
public Response getEntity(@Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    @PathParam("entitySetName") String entitySetName,
    @PathParam("id") String id,
    @QueryParam("$format") String format,
    @QueryParam("$callback") String callback,
    @QueryParam("$expand") String expand,
    @QueryParam("$select") String select) {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);
  return getEntityImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, id, format, callback, expand, select);
}
项目:opennmszh    文件:ValidatingMessageBodyReader.java   
public T readFrom(final Class<T> clazz, final Type type, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> parameters, final InputStream stream) throws IOException, WebApplicationException {
    LogUtils.debugf(this, "readFrom: %s/%s/%s", clazz.getSimpleName(), type, mediaType);

    JAXBContext jaxbContext = null;
    final ContextResolver<JAXBContext> resolver = providers.getContextResolver(JAXBContext.class, mediaType);
    try {

        if (resolver != null) {
            jaxbContext = resolver.getContext(clazz);
        }

        if (jaxbContext == null) {
            jaxbContext = JAXBContext.newInstance(clazz);

        }

        return JaxbUtils.unmarshal(clazz, new InputSource(stream), jaxbContext);

    } catch (final JAXBException e) {
        LogUtils.warnf(this, e, "An error occurred while unmarshaling a %s object", clazz.getSimpleName());
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
项目:openstack-maven-CIET-students    文件:RESTEasyConnector.java   
public OpenStackProviderFactory() {
    super();

    addContextResolver(new ContextResolver<ObjectMapper>() {
        public ObjectMapper getContext(Class<?> type) {
            return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
        }
    });

    jsonProvider = new JacksonJsonProvider();
    addMessageBodyReader(jsonProvider);
    addMessageBodyWriter(jsonProvider);

    streamProvider = new InputStreamProvider();
    addMessageBodyReader(streamProvider);
    addMessageBodyWriter(streamProvider);
}
项目:tomee    文件:Contexts.java   
private static Set<Class<?>> contextClasses() {
    final Set<Class<?>> classes = new HashSet<>(); classes.add(UriInfo.class);
    classes.add(SecurityContext.class);
    classes.add(HttpHeaders.class);
    classes.add(ContextResolver.class);
    classes.add(Providers.class);
    classes.add(Request.class);
    /* TODO: when we have jaxrs 2
    classes.add(ResourceInfo.class);
    classes.add(ResourceContext.class);
    */
    classes.add(Application.class);
    classes.add(HttpServletRequest.class);
    classes.add(HttpServletResponse.class);
    classes.add(ServletConfig.class);
    classes.add(ServletContext.class);
    classes.add(MessageContext.class);
    return classes;
}
项目:OpenNMS    文件:ValidatingMessageBodyReader.java   
public T readFrom(final Class<T> clazz, final Type type, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> parameters, final InputStream stream) throws IOException, WebApplicationException {
    LogUtils.debugf(this, "readFrom: %s/%s/%s", clazz.getSimpleName(), type, mediaType);

    JAXBContext jaxbContext = null;
    final ContextResolver<JAXBContext> resolver = providers.getContextResolver(JAXBContext.class, mediaType);
    try {

        if (resolver != null) {
            jaxbContext = resolver.getContext(clazz);
        }

        if (jaxbContext == null) {
            jaxbContext = JAXBContext.newInstance(clazz);

        }

        return JaxbUtils.unmarshal(clazz, new InputSource(stream), jaxbContext);

    } catch (final JAXBException e) {
        LogUtils.warnf(this, e, "An error occurred while unmarshaling a %s object", clazz.getSimpleName());
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
项目:holon-jaxrs    文件:JerseyAuthAutoConfiguration.java   
@Override
public void customize(ResourceConfig config) {
    // Realm ContextResolver
    config.register(new ContextResolver<Realm>() {

        @Override
        public Realm getContext(Class<?> type) {
            return realm;
        }
    });
    // Authentication
    config.register(AuthenticationFeature.class);
    // Authorization
    config.register(RolesAllowedDynamicFeature.class);
}
项目:holon-jaxrs    文件:TestAuthzStd.java   
@Override
protected Application configure() {

    final AccountProvider provider = id -> {
        Account account = null;
        if ("a1".equals(id)) {
            account = Account.builder(id).credentials(Credentials.builder().secret("p1").build()).enabled(true)
                    .permission("R1").permission("R2").build();
        } else if ("a2".equals(id)) {
            account = Account.builder(id).credentials(Credentials.builder().secret("p2").build()).enabled(true)
                    .permission("R1").permission("R3").build();
        }
        return Optional.ofNullable(account);
    };

    final Realm realm = Realm.builder().resolver(AuthenticationToken.httpBasicResolver())
            .authenticator(Account.authenticator(provider)).withDefaultAuthorizer().build();

    return new ResourceConfig()
            .register(RolesAllowedDynamicFeature.class)
            .register(new ContextResolver<Realm>() {

                @Override
                public Realm getContext(Class<?> type) {
                    return realm;
                }
            }).register(ProtectedResource.class).register(SemiProtectedResource.class)
            .register(PublicResource.class);
}
项目:holon-jaxrs    文件:TestAuth.java   
@Override
protected Application configure() {

    final AccountProvider provider = id -> {
        Account account = null;
        if ("a1".equals(id)) {
            account = Account.builder(id).credentials(Credentials.builder().secret("p1").build()).enabled(true)
                    .permission("R1").permission("R2").build();
        } else if ("a2".equals(id)) {
            account = Account.builder(id).credentials(Credentials.builder().secret("p2").build()).enabled(true)
                    .permission("R1").permission("R3").build();
        }
        return Optional.ofNullable(account);
    };

    final Realm realm = Realm.builder().resolver(AuthenticationToken.httpBasicResolver())
            .authenticator(Account.authenticator(provider)).withDefaultAuthorizer().build();

    return new ResourceConfig()// .register(AuthenticationFeature.class) // using auto-config
            .register(RolesAllowedDynamicFeature.class).register(new ContextResolver<Realm>() {

                @Override
                public Realm getContext(Class<?> type) {
                    return realm;
                }
            }).register(ProtectedResource.class).register(SemiProtectedResource.class)
            .register(PublicResource.class);
}
项目:kladr-api-client    文件:ObjectMapperProviderTest.java   
@Test
public void testSkipUnknownFields() throws IOException {
    final ContextResolver<ObjectMapper> contextResolver = new ObjectMapperProvider();
    final ObjectMapper objectMapper = contextResolver.getContext(ObjectMapper.class);
    final TestEntity testEntity = objectMapper.readValue(JSON, TestEntity.class);
    Assert.assertEquals(TEST_NAME, testEntity.getName());
}
项目:geeMVC-Java-MVC-Framework    文件:JaxRsResolverTest.java   
@Test
public void testLocateGensonContextResolver() {
    Providers providers = instance(Providers.class);

    RuntimeDelegate.setInstance(new DefaultRuntimeDelegate());

    ContextResolver contextResolver = providers.getContextResolver(Genson.class, MediaType.APPLICATION_JSON_TYPE);

    assertNotNull(contextResolver);
    assertEquals(TestGensonContextResolver3.class, contextResolver.getClass());
}
项目:geeMVC-Java-MVC-Framework    文件:JaxRsResolverTest.java   
@Test
public void testLocateObjectContextResolver() {
    Providers providers = instance(Providers.class);

    RuntimeDelegate.setInstance(new DefaultRuntimeDelegate());

    ContextResolver contextResolver = providers.getContextResolver(Person.class, MediaType.APPLICATION_JSON_TYPE);

    assertNotNull(contextResolver);
    assertEquals(TestGensonContextResolver6.class, contextResolver.getClass());
}
项目:geeMVC-Java-MVC-Framework    文件:JaxRsResolverTest.java   
@Test
public void testLocateApplicationContextResolver() {
    Providers providers = instance(Providers.class);

    RuntimeDelegate.setInstance(new DefaultRuntimeDelegate());

    ContextResolver contextResolver = providers.getContextResolver(Application.class, MediaType.APPLICATION_JSON_TYPE);

    assertNotNull(contextResolver);
    assertEquals(TestApplicationContextResolver.class, contextResolver.getClass());
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:JerseyAutoConfiguration.java   
@Bean
public ResourceConfigCustomizer resourceConfigCustomizer(
        final ObjectMapper objectMapper) {
    addJaxbAnnotationIntrospectorIfPresent(objectMapper);
    return new ResourceConfigCustomizer() {
        @Override
        public void customize(ResourceConfig config) {
            config.register(JacksonFeature.class);
            config.register(new ObjectMapperContextResolver(objectMapper),
                    ContextResolver.class);
        }
    };
}
项目:javaone2015-cloudone    文件:GsonFeature.java   
@Override
public boolean configure(final FeatureContext context) {
    final Configuration config = context.getConfiguration();

    final String jsonFeature = CommonProperties.getValue(config.getProperties(),
            config.getRuntimeType(),
            InternalProperties.JSON_FEATURE,
            JSON_FEATURE,
            String.class);
    // Other JSON providers registered.
    if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) {
        return false;
    }

    // Disable other JSON providers.
    String propName = PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE,
                                                                 config.getRuntimeType());
    context.property(propName, JSON_FEATURE);

    // Register
    context.register(GsonProvider.class);
    if (gsonBuilder != null) {
        context.register(new ContextResolver<GsonBuilder>() {
            @Override
            public GsonBuilder getContext(Class type) {
                return gsonBuilder;
            }
        });
    }
    return true;
}
项目:javaone2015-cloudone    文件:GsonProvider.java   
@PostConstruct
public void postConstruct() {
    final ContextResolver<GsonBuilder> contextResolver = providers.getContextResolver(GsonBuilder.class, MediaType.APPLICATION_JSON_TYPE);
    if (contextResolver != null) {
        final GsonBuilder builder = contextResolver.getContext(GsonBuilder.class);
        if (builder != null) {
            gson = builder.create();
        }
    }
}
项目:oreva    文件:ODataBatchSingleUnit.java   
@Override
public final Response execute(HttpHeaders httpHeaders, ContextResolver<ODataProducer> producerResolver, URI baseUri) throws Exception {

  if (!fullResourceUri.toString().startsWith(baseUri.toString())) {
    throw new UnsupportedOperationException("the resouce url does not match base url from batch operation,\n\tbaseUri=" + baseUri +
        "\n\trequest url=" + fullResourceUri);
  }

  if (!isParsed) {
    parseUri(fullResourceUri, baseUri);
    isParsed = true;
  }
  return delegate(httpHeaders, baseUri, producerResolver);
}
项目:oreva    文件:ODataBatchSingleUnit.java   
/**
 * Creates the response for batch.
 *
 * @param httpHeaders the http headers
 * @param producerResolver the producer resolver
 * @param baseUri the base uri
 * @param requestedEntity the requested entity
 * @return the response
 * @throws Exception the exception
 */
public Response createResponseForBatch(HttpHeaders httpHeaders, ContextResolver<ODataProducer> producerResolver, URI baseUri, String requestedEntity) throws Exception {
  ODataProducer producer = producerResolver.getContext(ODataProducer.class);
  OEntityKey entityKey = null;
  //setting isResponse to true, since the entity we get from the response contain not only name and value pairs, but also metadata, relations,etc
  //so that Json parser will parse it and give you back OEntity.
  Boolean isResponse = true;
  BatchRequestResource batchRequestResource = new BatchRequestResource();
  OEntity entity = batchRequestResource.getRequestEntity(httpHeaders, getResourceHeaders(), getUriInfo(), requestedEntity, producer.getMetadata(), entitySetName, entityKey, isResponse);

  return batchRequestResource.createResponseForBatch(httpHeaders, getUriInfo(), producer, getEnitySetName(), entity, getMediaTypeListForBatch());
}
项目:oreva    文件:EntitiesRequestResource.java   
@PUT
public Response functionCallPut(
    @Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    @QueryParam("$format") String format,
    @QueryParam("$callback") String callback,
    @PathParam("entitySetName") String functionName,
    InputStream payload) throws Exception {

  Response response;
  log("functionCallDelete", "function", functionName);

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  // the OData URI scheme makes it impossible to have unique @Paths that refer
  // to functions and entity sets
  if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
    // functions that return collections of entities should support the
    // same set of query options as entity set queries so give them everything.

    QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build();
    response = FunctionResource.callFunction(ODataHttpMethod.PUT, httpHeaders, uriInfo, securityContext, producer, functionName, format, callback, query);
  } else {
    throw new NotFoundException(functionName);
  }

  return response;
}
项目:oreva    文件:EntitiesRequestResource.java   
@DELETE
public Response functionCallDelete(
    @Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    @QueryParam("$format") String format,
    @QueryParam("$callback") String callback,
    @PathParam("entitySetName") String functionName,
    InputStream payload) throws Exception {

  Response response;
  log("functionCallDelete", "function", functionName);

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  // the OData URI scheme makes it impossible to have unique @Paths that refer
  // to functions and entity sets
  if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
    // functions that return collections of entities should support the
    // same set of query options as entity set queries so give them everything.

    QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build();
    response = FunctionResource.callFunction(ODataHttpMethod.DELETE, httpHeaders, uriInfo, securityContext, producer, functionName, format, callback, query);
  } else {
    throw new NotFoundException(functionName);
  }

  return response;
}
项目:oreva    文件:EntitiesRequestResource.java   
@GET
@Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8,
    ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8,
    ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
public Response getEntities(
    @Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    @PathParam("entitySetName") String entitySetName,
    @QueryParam("$inlinecount") String inlineCount,
    @QueryParam("$top") String top,
    @QueryParam("$skip") String skip,
    @QueryParam("$filter") String filter,
    @QueryParam("$orderby") String orderBy,
    @QueryParam("$format") String format,
    @QueryParam("$callback") String callback,
    @QueryParam("$skiptoken") String skipToken,
    @QueryParam("$expand") String expand,
    @QueryParam("$select") String select)
    throws Exception {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  return getEntitiesImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, false, inlineCount, top, skip,
      filter, orderBy, format, callback, skipToken, expand, select);
}
项目:oreva    文件:EntitiesRequestResource.java   
@Path("{navProp: [^$/()]+?}")
public BaseResource getNavProperty(
    @Context ContextResolver<ODataProducer> producerResolver,
    @PathParam("entitySetName") String entitySetName,
    @PathParam("navProp") String functionName) {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);
  if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
    return new FunctionResource();
  } else {
    throw new NotFoundException(functionName);
  }
}
项目:oreva    文件:PropertyRequestResource.java   
@PUT
public Response updateEntity(
    @Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    @PathParam("entitySetName") String entitySetName,
    @PathParam("id") String id,
    @PathParam("navProp") String navProp,
    InputStream payload) {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);
  Enumerable<EdmProperty> props = producer.getMetadata().getEdmEntitySet(entitySetName).getType().getProperties();

  // only support update NamedStream property 
  for (EdmProperty prop : props) {
    if (prop.getName().equals(navProp)) {
      if (prop.getType().getFullyQualifiedTypeName().equals("Edm.Stream")) {
        QueryInfo query = new QueryInfo(
            null,
            null,
            null,
            null,
            null,
            null,
            OptionsQueryParser.parseCustomOptions(uriInfo),
            null,
            null);

        return updateNamedStreamResponse(producer, entitySetName, id, navProp, query, payload);
      }
    }
  }

  log.info("NavProp: updateEntity Not supported yet.");
  throw new NotImplementedException("NavProp: updateEntity not supported yet.");
}
项目:oreva    文件:PropertyRequestResource.java   
@DELETE
public Response deleteEntity(
    @Context ContextResolver<ODataProducer> producerResolver,
    @PathParam("entitySetName") String entitySetName,
    @PathParam("id") String id,
    @PathParam("navProp") String navProp) {
  throw new NotImplementedException("Not supported yet.");
}
项目:oreva    文件:MetadataResource.java   
@GET
@Produces({ ODataConstants.APPLICATION_XML_CHARSET_UTF8, ODataConstants.APPLICATION_ATOMSVC_XML_CHARSET_UTF8 })
public Response getMetadata(
    @Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @QueryParam("$format") String format) {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  // a request for media type atomsvc+xml means give me the service document of the metadata producer
  if ("atomsvc".equals(format) || isAtomSvcRequest(httpHeaders)) {
    MetadataProducer metadataProducer = producer.getMetadataProducer();
    if (metadataProducer == null) {
      throw newMetadataNotImplementedException();
    }
    ServiceDocumentResource r = new ServiceDocumentResource();
    return r.getServiceDocument(httpHeaders, uriInfo, producerResolver, FormatType.ATOM.name(), null);
  } else {
    StringWriter w = new StringWriter();
    ODataProducer source = "metamodel".equals(format) ? producer.getMetadataProducer() : producer;
    if (source == null) {
      throw newMetadataNotImplementedException();
    }
    EdmDataServices s = source.getMetadata();
    EdmxFormatWriter.write(s, w);

    return Response.ok(w.toString(), ODataConstants.APPLICATION_XML_CHARSET_UTF8)
        .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataConstants.DATA_SERVICE_VERSION_HEADER)
        .build();
  }
}
项目:oreva    文件:MetadataResource.java   
@GET
@Path("{entitySetName}")
@Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8,
    ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8,
    ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
public Response getMetadataEntities(
    @Context HttpHeaders httpHeaders,
    @Context UriInfo uriInfo,
    @Context ContextResolver<ODataProducer> producerResolver,
    @Context SecurityContext securityContext,
    @PathParam("entitySetName") String entitySetName,
    @PathParam("optionalId") String optionalId,
    @QueryParam("$inlinecount") String inlineCount,
    @QueryParam("$top") String top,
    @QueryParam("$skip") String skip,
    @QueryParam("$filter") String filter,
    @QueryParam("$orderby") String orderBy,
    @QueryParam("$format") String format,
    @QueryParam("$callback") String callback,
    @QueryParam("$skiptoken") String skipToken,
    @QueryParam("$expand") String expand,
    @QueryParam("$select") String select) throws Exception {

  ODataProducer producer = producerResolver.getContext(ODataProducer.class);

  MetadataProducer metadataProducer = producer.getMetadataProducer();
  if (metadataProducer == null) {
    throw newMetadataNotImplementedException();
  }

  EntitiesRequestResource r = new EntitiesRequestResource();
  return r.getEntitiesImpl(httpHeaders, uriInfo, securityContext, metadataProducer, entitySetName, false, inlineCount, top, skip, filter, orderBy, format, callback, skipToken, expand, select);
}