Java 类org.codehaus.jackson.jaxrs.JacksonJsonProvider 实例源码

项目:jrs-rest-java-client    文件:SessionStorage.java   
protected WebTarget configClient() {
    JacksonJsonProvider customRepresentationTypeProvider = new CustomRepresentationTypeProvider()
            .configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    rootTarget = client.target(configuration.getJasperReportsServerUrl());
    rootTarget
            .register(customRepresentationTypeProvider)
            .register(JacksonFeature.class)
            .register(MultiPartWriter.class);
    if (sessionId != null) {
        rootTarget.register(new SessionOutputFilter(sessionId));
    }
    if (configuration.getLogHttp()) {
        rootTarget.register(initLoggingFilter());
    }
    return rootTarget;
}
项目:jrs-rest-java-client    文件:SessionStorageTest.java   
@Test
public void should_return_client_with_configuration() throws Exception {

    //  Given
    suppress(method(SessionStorage.class, "init"));
    doReturn("http").when(configurationMock).getJasperReportsServerUrl();
    SessionStorage sessionStorage = Mockito.spy(new SessionStorage(configurationMock, credentialsMock, null, null));
    Whitebox.setInternalState(sessionStorage, "client", clientMock);
    Whitebox.setInternalState(sessionStorage, "sessionId", "sessionId");
    doReturn(targetMock).when(clientMock).target(anyString());
    doReturn(targetMock).when(targetMock).register(JacksonFeature.class);
    doReturn(targetMock).when(targetMock).register(MultiPartWriter.class);
    doReturn(targetMock).when(targetMock).register(any(JacksonJsonProvider.class));
    doReturn(targetMock).when(targetMock).register(any(SessionOutputFilter.class));
    doReturn(true).when(configurationMock).getLogHttp();
    doReturn(targetMock).when(targetMock).register(any(LoggingFilter.class));
    when(sessionStorage.getConfiguredClient()).thenReturn(targetMock);

    // When

    // When
    WebTarget configuredClient = sessionStorage.getConfiguredClient();

    // Then
    assertEquals(configuredClient, targetMock);
}
项目: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);
}
项目:asana-api-java    文件:AbstractClient.java   
/**
 * @param apiKey your Asana API key
 * @param connectionTimeout the connection timeout in MILLISECONDS
 * @param readTimeout the read timeout in MILLISECONDS
 */
public AbstractClient(String apiKey, int connectionTimeout, int readTimeout){
    this.apiKey = apiKey;

    ClientConfig config = new DefaultClientConfig();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    JacksonJsonProvider provider = new JacksonJsonProvider(mapper);
    config.getSingletons().add(provider);
    //config.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(config);
    client.addFilter(new HTTPBasicAuthFilter(apiKey, ""));
    client.setConnectTimeout(connectionTimeout);
    client.setReadTimeout(readTimeout);
    service = client.resource(UriBuilder.fromUri(BASE_URL).build());
}
项目:osgi-sample    文件:Activator.java   
@Override
public Object addingService(ServiceReference serviceReference) {
    final Object trackedService = context.getService(serviceReference);

    if (trackedService instanceof EntityService) {
        final EntityServiceRest restApi = new EntityServiceRest();
        restApi.setEntityService((EntityService) trackedService);

        JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
        sf.setResourceClasses(restApi.getClass());
        sf.setResourceProvider(restApi.getClass(), new SingletonResourceProvider(restApi));
        sf.setAddress("/entity");
        sf.setProvider(new JacksonJsonProvider());
        server = sf.create();
    }

    return trackedService;
}
项目:devhub-prototype    文件:WebModule.java   
@Override
protected void configureServlets() {
    bind(BuildInfo.class).toInstance(buildInfo);
    bind(ServerConfig.class).toInstance(serverConfig);

    // For metrics
    bind(InstrumentedResourceMethodDispatchAdapter.class).in(Singleton.class);

    install(new SecurityModule(servletContext));
    install(new PersistenceModule(serverConfig.getDbConfig(), ""));
    install(new MailModule(serverConfig.getMailConfig()));

    LOG.debug("Configuring servlets and URLs");
    filter("/*").through(PersistFilter.class);
    filter("/*").through(GuiceShiroFilter.class);

    bind(Provisioner.class).in(Scopes.SINGLETON);
    bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);

    final Map<String, String> params = Maps.newHashMap();
    params.put("com.sun.jersey.config.property.packages", "nl.tudelft.ewi.dea.jaxrs");
    params.put(ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX, "/.*\\.(html|js|gif|png|jpg|jpeg|css|ico)");
    filter("/*").through(GuiceContainer.class, params);
}
项目:angulardemorestful    文件:NgDemoApplicationSetup.java   
@Override
protected Injector getInjector() {
    return Guice.createInjector(new ServletModule() {

        @Override
        protected void configureServlets() {

            super.configureServlets();

            // Configuring Jersey via Guice:
            ResourceConfig resourceConfig = new PackagesResourceConfig("ngdemo/web");
            for (Class<?> resource : resourceConfig.getClasses()) {
                bind(resource);
            }

            // hook Jackson into Jersey as the POJO <-> JSON mapper
            bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);

            serve("/web/*").with(GuiceContainer.class);

            filter("/web/*").through(ResponseCorsFilter.class);
        }
    }, new UserModule());
}
项目:angulardemorestful    文件:ServerProvider.java   
public void createServer() throws IOException {
    System.out.println("Starting grizzly...");

    Injector injector = Guice.createInjector(new ServletModule() {
        @Override
        protected void configureServlets() {
            bind(UserService.class).to(UserServiceImpl.class);
            bind(UserRepository.class).to(UserMockRepositoryImpl.class);
            bind(DummyService.class).to(DummyServiceImpl.class);
            bind(DummyRepository.class).to(DummyMockRepositoryImpl.class);

            // hook Jackson into Jersey as the POJO <-> JSON mapper
            bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);
        }
    });

    ResourceConfig rc = new PackagesResourceConfig("ngdemo.web");
    IoCComponentProviderFactory ioc = new GuiceComponentProviderFactory(rc, injector);
    server = GrizzlyServerFactory.createHttpServer(BASE_URI + "web/", rc, ioc);

    System.out.println(String.format("Jersey app started with WADL available at "
            + "%srest/application.wadl\nTry out %sngdemo\nHit enter to stop it...",
            BASE_URI, BASE_URI));
}
项目:occurrence    文件:ApiClientConfiguration.java   
/**
 * @return a new jersey client using a multithreaded http client
 */
public WebResource newApiClient() {
  ClientConfig cc = new DefaultClientConfig();
  cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
  cc.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, timeout);
  cc.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout);
  cc.getClasses().add(JacksonJsonProvider.class);
  // use custom configured object mapper ignoring unknown properties
  cc.getClasses().add(ObjectMapperContextResolver.class);

  HttpClient http = HttpUtil.newMultithreadedClient(timeout, maxConnections, maxConnections);
  ApacheHttpClient4Handler hch = new ApacheHttpClient4Handler(http, null, false);
  Client client = new ApacheHttpClient4(hch, cc);

  LOG.info("Connecting to GBIF API: {}", url);
  return client.resource(url);
}
项目:USM    文件:ApplicationConfig.java   
@Override
public Set<Class<?>> getClasses() {
  Set<Class<?>> resources = new HashSet<>();
  // following code to customize Jersey 1.x JSON provider:
  resources.add(JacksonJsonProvider.class);

  addRestResourceClasses(resources);
  return resources;
}
项目:USM    文件:AuthenticationRestClient.java   
public AuthenticationRestClient(String uri) 
 {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    client = Client.create(config);
    webResource = client.resource(uri);
}
项目:USM    文件:OrganisationRestClient.java   
public OrganisationRestClient(String uri) 
{
  ClientConfig config = new DefaultClientConfig();
  config.getClasses().add(JacksonJsonProvider.class);
  client = Client.create(config);
  webResource = client.resource(uri).path("organisations");
  endpointWebResource = client.resource(uri).path("endpoint");
  channelWebResource = client.resource(uri).path("channel");
  contactWebResource = client.resource(uri).path("endpointcontact");
}
项目:USM    文件:PersonRestClient.java   
/**
 * Creates a new instance.
 * 
 * @param uri the REST service URI prefix
 */
public PersonRestClient(String uri) 
{
  ClientConfig config = new DefaultClientConfig();
  config.getClasses().add(JacksonJsonProvider.class);
  client = Client.create(config);
  webResource = client.resource(uri).path("persons");
}
项目:USM    文件:ApplicationConfig.java   
@Override
public Set<Class<?>> getClasses() 
{
  Set<Class<?>> resources = new HashSet<>();
  // following code to customize Jersey 1.x JSON provider:
  resources.add(JacksonJsonProvider.class);

  addRestResourceClasses(resources);
  return resources;
}
项目:USM    文件:InformationRestClient.java   
/**
 * Creates a new instance.
 * 
 * @param uri the REST Service end-point URI. For example:
 * http://localhost:8080/usm-information/rest/
 */
public InformationRestClient(String uri) 
{
  ClientConfig config = new DefaultClientConfig();
  config.getClasses().add(JacksonJsonProvider.class);
  client = Client.create(config);
  webResource = client.resource(uri);
}
项目:USM    文件:DeploymentRestClient.java   
public DeploymentRestClient(String uri) 
 {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    client = Client.create(config);
    webResource = client.resource(uri).path("deployments");
}
项目:USM    文件:ApplicationConfig.java   
@Override
public Set<Class<?>> getClasses() 
{
  Set<Class<?>> resources = new HashSet<>();
  // following code to customize Jersey 1.x JSON provider:
  resources.add(JacksonJsonProvider.class);

  addRestResourceClasses(resources);
  return resources;
}
项目:USM    文件:SessionTrackerRestClient.java   
/**
  * Creates a new instance.
  * 
  * @param uri the REST service end-point URI
  */
public SessionTrackerRestClient(String uri) 
 {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    client = Client.create(config);
    webResource = client.resource(uri);
}
项目:USM    文件:AuthenticationRestClient.java   
public AuthenticationRestClient(String uri) 
 {
    ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    client = Client.create(config);
    webResource = client.resource(uri);
}
项目:playground    文件:RestClientFactoryImpl.java   
/**
 * Initializes the providerFactory, so that it will be ready for use in Resteasy client proxies later on.
 */
@PostConstruct
public void initializeProviderFactory() {

    /*
     * This is a fairly annoying process where we have to --manually-- create the provider
     * factory. We'd just like to configure the object mapper that the Resteasy provider uses,
     * but ... Resteasy will discover the Jackson provider automatically via /META-INF/services

     * and load it automatically --before-- we can configure it. Once added, we can't gain
     * access to it and Resteasy will reject our customized version. So, we're going to create
     * the provider factory from scratch and do the same things that it would do by default, but
     * we won't register the built in providers until we've registered our special ones first.
     */
    providerFactory = new ResteasyProviderFactory();

    final JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
    jacksonProvider.setMapper(BasicObjectMapperProvider.getInstance().getContext(Void.class));

    providerFactory.registerProviderInstance(jacksonProvider);

    /*
     * OK, now that we have customized Jackson we let the built in (automatically discovered)
     * providers be added to our providerFactory.
     */
    RegisterBuiltin.register(providerFactory);
}
项目:rtc2jira    文件:JiraRestAccess.java   
public JiraRestAccess(String url, String user, String password) {
  this.restHome = url + JIRA_REST_API_SUFFIX;
  String userAndPassword = user + ':' + password;
  this.authentification = new String(Base64.getEncoder().encode(userAndPassword.getBytes()));

  JacksonJsonProvider jacksonJsonProvider =
      new JacksonJaxbJsonProvider().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  objectMapper = jacksonJsonProvider.locateMapper(Object.class, MediaType.APPLICATION_JSON_TYPE);

  ClientConfig cfg = new DefaultClientConfig();
  cfg.getSingletons().add(jacksonJsonProvider);
  this.client = Client.create(cfg);
  // this.client.addFilter(new LoggingFilter(System.out));
}
项目:archive    文件:ArchiveServer.java   
public ArchiveServer(String ip, int port) throws Exception {
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();

    sf.setProvider(new JacksonJsonProvider());
    sf.setResourceClasses(ArchiveService.class);
    sf.setResourceProvider(ArchiveService.class, new SingletonResourceProvider(new ArchiveService()));
    sf.setAddress(String.format("http://%s:%d/", ip, port));

    server = sf.create();
    logger.info("Start Archive Server.");
}
项目:jrs-rest-java-client    文件:SessionStorageTest.java   
@Test
public void should_invoke_init_method_with_default_configuration() throws Exception {
    // Given
    mockStatic(ClientBuilder.class);
    when(ClientBuilder.newBuilder()).thenReturn(builderMock);
    doReturn("http://54.83.98.156/jasperserver-pro").when(configurationMock).getJasperReportsServerUrl();
    doReturn(clientMock).when(builderMock).build();
    doReturn(null).when(configurationMock).getConnectionTimeout();
    doReturn(null).when(configurationMock).getReadTimeout();
    doReturn(targetMock).when(clientMock).target(anyString());
    doReturn(targetMock).when(targetMock).register(JacksonFeature.class);
    doReturn(targetMock).when(targetMock).register(MultiPartWriter.class);
    doReturn(targetMock).when(targetMock).register(any(JacksonJsonProvider.class));
    doReturn(false).when(configurationMock).getLogHttp();

    // When
    SessionStorage sessionStorage = new SessionStorage(configurationMock, credentialsMock, null, null);

    // Then
    assertEquals(Whitebox.getInternalState(sessionStorage, "configuration"), configurationMock);
    assertEquals(Whitebox.getInternalState(sessionStorage, "credentials"), credentialsMock);
    verify(configurationMock, times(2)).getJasperReportsServerUrl();
    verify(builderMock).build();
    verify(configurationMock).getConnectionTimeout();
    verify(configurationMock).getReadTimeout();
    verify(clientMock).target("http://54.83.98.156/jasperserver-pro");
    verify(targetMock).register(JacksonFeature.class);
    verify(targetMock, times(1)).register(isA(JacksonJsonProvider.class));
    verify(targetMock).register(MultiPartWriter.class);
    verify(configurationMock).getLogHttp();
    verify(targetMock, never()).register(LoggingFilter.class);
}
项目:jrs-rest-java-client    文件:SessionStorageTest.java   
@Test
public void should_invoke_init_method_with_custom_configuration() throws Exception {

    //  Given
    mockStatic(ClientBuilder.class);
    when(ClientBuilder.newBuilder()).thenReturn(builderMock);
    doReturn("http://54.83.98.156/jasperserver-pro").when(configurationMock).getJasperReportsServerUrl();
    doReturn(clientMock).when(builderMock).build();
    doReturn(1000).when(configurationMock).getConnectionTimeout();
    doReturn(clientMock).when(clientMock).property("jersey.config.client.connectTimeout", 1000);
    doReturn(200).when(configurationMock).getReadTimeout();
    doReturn(clientMock).when(clientMock).property("jersey.config.client.readTimeout", 200);
    doReturn(targetMock).when(clientMock).target(anyString());
    doReturn(targetMock).when(targetMock).register(JacksonFeature.class);
    doReturn(targetMock).when(targetMock).register(MultiPartWriter.class);
    doReturn(targetMock).when(targetMock).register(any(JacksonJsonProvider.class));
    doReturn(true).when(configurationMock).getLogHttp();
    doReturn(targetMock).when(targetMock).register(any(LoggingFilter.class));

    // When
    SessionStorage sessionStorage = new SessionStorage(configurationMock, credentialsMock, null, null);

    // Then
    assertEquals(Whitebox.getInternalState(sessionStorage, "configuration"), configurationMock);
    assertEquals(Whitebox.getInternalState(sessionStorage, "credentials"), credentialsMock);
    verify(configurationMock, times(2)).getJasperReportsServerUrl();
    verify(builderMock).build();
    verify(configurationMock).getConnectionTimeout();
    verify(configurationMock).getReadTimeout();
    verify(clientMock).property("jersey.config.client.connectTimeout", 1000);
    verify(clientMock).property("jersey.config.client.readTimeout", 200);
    verify(clientMock).target("http://54.83.98.156/jasperserver-pro");
    verify(targetMock).register(JacksonFeature.class);
    verify(targetMock, times(1)).register(isA(JacksonJsonProvider.class));
    verify(targetMock).register(MultiPartWriter.class);
    verify(configurationMock).getLogHttp();
    verify(targetMock).register(isA(LoggingFilter.class));
}
项目:geocode    文件:CountryCheckTest.java   
public CountryCheckTest() {
  ClientConfig cc = new DefaultClientConfig();
  cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
  cc.getClasses().add(JacksonJsonProvider.class);

  r = Client.create(cc).resource(api);
}
项目:jetty-jersey-guice-rxjava-scala    文件:BootstrapService.java   
@Override
protected Injector getInjector() {
  return Guice.createInjector(resources, new JerseyServletModule() {
    @Override
    protected void configureServlets() {
      //hook Jackson into Jersey as the POJO <-> JSON mapper
      bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);
      // Route all requests through GuiceContainer
      serve("/wiki/*").with(GeneralServlet.class);
      serve("/*").with(GuiceContainer.class);
    }
  });
}
项目:sip-servlets    文件:ASCCallControlClient.java   
public ASCCallControlClient(String host, int port) {
    ENDPOINT = "http://" + host + ":" + port + "/";

    clientConfig = new DefaultClientConfig();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    JacksonJsonProvider provider = new JacksonJsonProvider(mapper);
    clientConfig.getSingletons().add(provider);
}
项目:stripe-api-java    文件:Client.java   
/**
 * @param apiKey your Stripe api key
 * @param failOnUnknownProperties If true, a {@link org.codehaus.jackson.map.JsonMappingException} is thrown when
 *                                unknown Stripe response object properties are encountered. This is primarily used for
 *                                testing / debugging purposes.
 */
public Client(String apiKey, boolean failOnUnknownProperties) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties);
    mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mapper.registerModule(new StripeModule());

    DefaultClientConfig config = new DefaultClientConfig();
    config.getSingletons().add(new JacksonJsonProvider(mapper));
    com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
    client.addFilter(new HTTPBasicAuthFilter(apiKey, ""));
    service = client.resource(UriBuilder.fromUri(BASE_URL + VERSION + "/").build());
}
项目:t3as-snomedct-service    文件:SnomedClient.java   
/**
 * Configure the client instance with the base URL where the web service to be used lives.
 * @param url the base URL of the web service to be used
 */
public SnomedClient(final String url) {
    final ClientConfig config = new DefaultClientConfig();
    config.getClasses().add(JacksonJsonProvider.class);
    config.getClasses().add(ObjectMapperProvider.class);
    final Client client = Client.create(config);
    service = client.resource(url + SNOMED_SERVICE_PATH);
}
项目:JavaMagazineRESTfulAPI    文件:JaxRsServerConfig.java   
@Bean
public Server jaxRsServer(){
    List<ResourceProvider> resourceProviders = new LinkedList<ResourceProvider>();
    for (String beanName : ctx.getBeanDefinitionNames()) {
        if (ctx.findAnnotationOnBean(beanName, Path.class) != null) {
            SpringResourceFactory resourceFactory = new SpringResourceFactory(beanName);
            resourceFactory.setApplicationContext(ctx);
            resourceProviders.add(resourceFactory);
        }
    }

    JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
    factory.setBus(ctx.getBean(SpringBus.class));

    JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
    ObjectMapper objectMapper = new ObjectMapper();
    //set up ISO 8601 date/time stamp format:
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss'Z'");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    objectMapper.setDateFormat(df);
    jacksonJsonProvider.setMapper(objectMapper);

    factory.setProviders(Arrays.asList(jacksonJsonProvider, new DefaultExceptionMapper()));
    factory.setResourceProviders(resourceProviders);

    return factory.create();
}
项目:osgi-sample    文件:EntityServiceRest.java   
@Activate
public void activate() {
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(getClass());
    sf.setResourceProvider(getClass(), new SingletonResourceProvider(this));
    sf.setAddress("/entity");
    sf.setProvider(new JacksonJsonProvider());
    server = sf.create();
}
项目:osgi-sample    文件:NodeServiceRest.java   
@Activate
public void activate() {
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(getClass());
    sf.setResourceProvider(getClass(), new SingletonResourceProvider(this));
    sf.setAddress("/node");
    sf.setProvider(new JacksonJsonProvider());
    server = sf.create();
}
项目:Conference    文件:ResourceTest.java   
/** Setup the test environment. */
protected void setUp() {

    ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
    factory.addMessageBodyReader(new JacksonJsonProvider());

    RegisterBuiltin.register(factory);
}
项目:kissmetrics-connector    文件:KissMetricsConnector.java   
/**
 * Connect to KissMetrics.
 *
 * @param apiKey The API Key from your KissMetrics settings screen.
 * @throws ConnectionException
 */
@Connect
@TestConnectivity(active=false)
public void connect(@ConnectionKey String apiKey)
    throws ConnectionException {
    this.apiKey = apiKey;

    final ClientConfig clientConfig = new ClientConfig();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);

    clientConfig.register(JacksonJsonProvider.class);
    this.client = ClientBuilder.newClient(clientConfig);
}
项目:national-biomedical-image-archive    文件:RESTUtil.java   
public static List<StudyDTO> getStudyDrillDown(List<Integer> criteria, String userToken)
{

    Form form = new Form(); 
    // Add all selected studies to the list
    for (Integer dcriteria:criteria){
        form.add("list",dcriteria.toString());
    }

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(); 
    WebResource resource = client.resource(APIURLHolder.getUrl()
            +"/nbia-api/services/getStudyDrillDown"); 
    ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).
                                                 header("Authorization",  "Bearer "+userToken).
                                              type(MediaType.APPLICATION_FORM_URLENCODED).
                                              post(ClientResponse.class, form);
       // check response status code
       if (response.getStatus() != 200) {
           throw new RuntimeException("Failed : HTTP error code : "
                   + response.getStatus());
       }

       // display response
       String output = response.getEntity(String.class);
       List<StudyDTO> myObjects;
       try {
       //   Object json = mapper.readValue(output, Object.class);
       //    String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
       //    logger.info("Returned JSON\n"+indented);
        myObjects = mapper.readValue(output, new TypeReference<List<StudyDTO>>(){});
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

       return myObjects;

}
项目:national-biomedical-image-archive    文件:RESTUtil.java   
public static DefaultOAuth2AccessToken getToken(String userName, String password)
{

    Form form = new Form(); 
    form.add("username",userName); 
    form.add("password",password); 
    form.add("client_id","nbiaRestAPIClient"); 
    form.add("client_secret","ItsBetweenUAndMe"); 
    form.add("grant_type","password");


    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(); 
    WebResource resource = client.resource(APIURLHolder.getUrl()
            +"/nbia-api/oauth/token"); 
    ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).
                                                 type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
       // check response status code
       if (response.getStatus() != 200) {
           throw new RuntimeException("Failed : HTTP error code : "
                   + response.getStatus());
       }

       // display response
       String output = response.getEntity(String.class);
       output="["+output+"]";
       List<DefaultOAuth2AccessToken> myObjects;
       try {
        myObjects = mapper.readValue(output, new TypeReference<List<DefaultOAuth2AccessToken>>(){});
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

       return myObjects.get(0);

}
项目:national-biomedical-image-archive    文件:RESTUtil.java   
public static List<ImageDTO> getImageDrillDown(List<Integer> criteria, String userToken)
{

    Form form = new Form(); 
    int i=0;
    // List of selected series
    for (Integer dcriteria:criteria){
        form.add("list",dcriteria.toString());
    }

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(JacksonJsonProvider.class);
    Client client = Client.create(); 
    WebResource resource = client.resource(APIURLHolder.getUrl()
            +"/nbia-api/services/getImageDrillDown"); 
    ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).
                                                 header("Authorization",  "Bearer "+userToken).
                                                 type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
       // check response status code
       if (response.getStatus() != 200) {
           throw new RuntimeException("Failed : HTTP error code : "
                   + response.getStatus());
       }

       // display response
       String output = response.getEntity(String.class);
       List<ImageDTO> myObjects;
       try {
       //   Object json = mapper.readValue(output, Object.class);
       //    String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
       //    logger.info("Returned JSON\n"+indented);
        myObjects = mapper.readValue(output, new TypeReference<List<ImageDTO>>(){});
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

       return myObjects;

}
项目:occurrence    文件:RegistryClientUtil.java   
/**
 * Creates an HTTP client.
 */
private static ApacheHttpClient createHttpClient() {
  ClientConfig cc = new DefaultClientConfig();
  cc.getClasses().add(JacksonJsonContextResolver.class);
  cc.getClasses().add(JacksonJsonProvider.class);
  cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
  cc.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, REGISTRY_CLIENT_TO);
  JacksonJsonContextResolver.addMixIns(Mixins.getPredefinedMixins());
  return ApacheHttpClient.create(cc);
}
项目:occurrence    文件:AbstractOccurrenceRegistryMapper.java   
/**
 *
 * @param context
 * @throws IOException
 * @throws InterruptedException
 */
@Override
protected void setup(Context context) throws IOException, InterruptedException {
  super.setup(context);
  Properties props = new Properties();
  // extract the config properties from the job context
  for (Map.Entry<String, String> entry : context.getConfiguration()) {
    props.setProperty(entry.getKey(), entry.getValue());
  }

  ClientConfig cc = new DefaultClientConfig();
  cc.getClasses().add(JacksonJsonProvider.class);
  cc.getClasses().add(RegistryObjectMapperContextResolver.class);
  cc.getFeatures().put(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES.toString(), false);
  RegistryObjectMapperContextResolver.addMixIns(Mixins.getPredefinedMixins());

  httpClient = ApacheHttpClient.create(cc);
  WebResource regResource = httpClient.resource(props.getProperty(SyncCommon.REG_WS_PROPS_KEY));
  datasetService = new DatasetWsClient(regResource, null);
  orgService = new OrganizationWsClient(regResource, null);
  occurrenceMutator = new RegistryBasedOccurrenceMutator();

  OccHBaseConfiguration occHBaseConfiguration = new OccHBaseConfiguration();
  occHBaseConfiguration.occTable = props.getProperty(PROP_OCCURRENCE_TABLE_NAME_KEY);
  occHBaseConfiguration.zkConnectionString = props.getProperty(PROP_ZK_CONNECTION_STRING_KEY);

  Injector injector =
          Guice.createInjector(new PostalServiceModule("sync", props),
                  new OccurrencePersistenceModule(occHBaseConfiguration, context.getConfiguration()));
  occurrencePersistenceService = injector.getInstance(OccurrencePersistenceService.class);
  messagePublisher = injector.getInstance(MessagePublisher.class);
}
项目:neo4j-sparql-extension-yars    文件:RDFServerExtensionTest.java   
protected Client request() {
    DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
    defaultClientConfig.getClasses().add(JacksonJsonProvider.class);
    return Client.create(defaultClientConfig);
}