Java 类com.sun.jersey.api.client.Client 实例源码

项目:fuck_zookeeper    文件:Base.java   
@Before
public void setUp() throws Exception {
    super.setUp();

    RestCfg cfg = new RestCfg(new ByteArrayInputStream(String.format(
            "rest.port=%s\n" + 
            "rest.endpoint.1=%s;%s\n",
            GRIZZLY_PORT, CONTEXT_PATH, ZKHOSTPORT).getBytes()));

    rest = new RestMain(cfg);
    rest.start();

    zk = new ZooKeeper(ZKHOSTPORT, 30000, new MyWatcher());

    client = Client.create();
    znodesr = client.resource(BASEURI).path("znodes/v1");
    sessionsr = client.resource(BASEURI).path("sessions/v1/");
}
项目:https-github.com-apache-zookeeper    文件:Base.java   
@Before
public void setUp() throws Exception {
    RestCfg cfg = new RestCfg(new ByteArrayInputStream(String.format(
            "rest.port=%s\n" + 
            "rest.endpoint.1=%s;%s\n",
            GRIZZLY_PORT, CONTEXT_PATH, ZKHOSTPORT).getBytes()));

    rest = new RestMain(cfg);
    rest.start();

    zk = new ZooKeeper(ZKHOSTPORT, 30000, new MyWatcher());

    client = Client.create();
    znodesr = client.resource(BASEURI).path("znodes/v1");
    sessionsr = client.resource(BASEURI).path("sessions/v1/");
}
项目:guacamole-auth-callback    文件:CallbackAuthenticationProviderModule.java   
@Override
protected void configure() {

    // Bind core implementations of guacamole-ext classes
    bind(AuthenticationProvider.class).toInstance(authProvider);
    bind(Environment.class).toInstance(environment);

    // Bind services
    bind(ConfigurationService.class);
    bind(UserDataService.class);

    // Bind singleton ObjectMapper for JSON serialization/deserialization
    bind(ObjectMapper.class).in(Scopes.SINGLETON);

    // Bind singleton Jersey REST client
    bind(Client.class).toInstance(Client.create(CLIENT_CONFIG));

}
项目:hadoop    文件:TestRMHA.java   
private void checkActiveRMWebServices() throws JSONException {

    // Validate web-service
    Client webServiceClient = Client.create(new DefaultClientConfig());
    InetSocketAddress rmWebappAddr =
        NetUtils.getConnectAddress(rm.getWebapp().getListenerAddress());
    String webappURL =
        "http://" + rmWebappAddr.getHostName() + ":" + rmWebappAddr.getPort();
    WebResource webResource = webServiceClient.resource(webappURL);
    String path = app.getApplicationId().toString();

    ClientResponse response =
        webResource.path("ws").path("v1").path("cluster").path("apps")
          .path(path).accept(MediaType.APPLICATION_JSON)
          .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject appJson = json.getJSONObject("app");
    assertEquals("ACCEPTED", appJson.getString("state"));
    // Other stuff is verified in the regular web-services related tests
  }
项目:ZooKeeper    文件:Base.java   
@Before
public void setUp() throws Exception {
    super.setUp();

    RestCfg cfg = new RestCfg(new ByteArrayInputStream(String.format(
            "rest.port=%s\n" + 
            "rest.endpoint.1=%s;%s\n",
            GRIZZLY_PORT, CONTEXT_PATH, ZKHOSTPORT).getBytes()));

    rest = new RestMain(cfg);
    rest.start();

    zk = new ZooKeeper(ZKHOSTPORT, 30000, new MyWatcher());

    client = Client.create();
    znodesr = client.resource(BASEURI).path("znodes/v1");
    sessionsr = client.resource(BASEURI).path("sessions/v1/");
}
项目:music    文件:MusicRestClient.java   
public  Map<String,Object> readAllRows(String keyspaceName, String tableName){
    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    Client client = Client.create(clientConfig);
    String url =getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/"+tableName+"/rows";      
    WebResource webResource = client.resource(url);

    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

    if (response.getStatus() < 200 || response.getStatus() > 299) 
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());

    Map<String,Object> output = response.getEntity(Map.class);
    return output;  
}
项目:music    文件:MusicRestClient.java   
public void checkMusicVersion(){
    Client client = Client.create();

    WebResource webResource = client
            .resource(getMusicNodeURL()+"/version");

    ClientResponse response = webResource.accept("text/plain")
            .get(ClientResponse.class);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
    }

    String output = response.getEntity(String.class);
}
项目:music    文件:MicroBenchMarks.java   
public  String cassaGet(){
    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    Client client = Client.create(clientConfig);

    String url = musicurl+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+userForGets;
    WebResource webResource = client
            .resource(url);

    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

    if (response.getStatus() < 200 || response.getStatus() > 299) 
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());

    Map<String,Object> output = response.getEntity(Map.class);
    return "cassaGet:"+url; 
}
项目:conductor    文件:ConductorServer.java   
private static void createKitchenSink(int port) throws Exception {

    List<TaskDef> taskDefs = new LinkedList<>();
    for(int i = 0; i < 40; i++) {
        taskDefs.add(new TaskDef("task_" + i, "task_" + i, 1, 0));
    }
    taskDefs.add(new TaskDef("search_elasticsearch", "search_elasticsearch", 1, 0));

    Client client = Client.create();
    ObjectMapper om = new ObjectMapper();
    client.resource("http://localhost:" + port + "/api/metadata/taskdefs").type(MediaType.APPLICATION_JSON).post(om.writeValueAsString(taskDefs));

    InputStream stream = Main.class.getResourceAsStream("/kitchensink.json");
    client.resource("http://localhost:" + port + "/api/metadata/workflow").type(MediaType.APPLICATION_JSON).post(stream);

    stream = Main.class.getResourceAsStream("/sub_flow_1.json");
    client.resource("http://localhost:" + port + "/api/metadata/workflow").type(MediaType.APPLICATION_JSON).post(stream);

    String input = "{\"task2Name\":\"task_5\"}";
    client.resource("http://localhost:" + port + "/api/workflow/kitchensink").type(MediaType.APPLICATION_JSON).post(input);

    logger.info("Kitchen sink workflows are created!");
}
项目:galaxy-PROV    文件:GalaxyApiTest.java   
@Test
    public void galaxyRestConnect() throws URISyntaxException, MalformedURLException, IOException, JSONException {
        //http://galaxy.readthedocs.io/en/master/lib/galaxy.webapps.galaxy.api.html#module-galaxy.webapps.galaxy.api.histories

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        WebResource service = client.resource(new URI(gURL));

//        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
//        params.add("key", gKey);
        ClientResponse responseHist = service.path("/api/histories").queryParam("key", gApiKey).accept("application/json").type("application/json").get(ClientResponse.class);
        System.out.println("----------");
        String r = responseHist.getEntity(String.class);
        Util.jsonPP(r);
        System.out.println("----------");

//        /api/tools
        ClientResponse responseTools = service.path("/api/tools").queryParam("key", gApiKey).accept("application/json").type("application/json").get(ClientResponse.class);
        System.out.println("----------");
        r = responseTools.getEntity(String.class);
        Util.jsonPP(r);
    }
项目:music    文件:MicroBenchMarks.java   
private  String createLock(String lockName){
    Client client = Client.create();
    String msg = musicurl+"/locks/create/"+lockName;
    WebResource webResource = client.resource(msg);
    System.out.println(msg);

    WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);

    ClientResponse response = wb.post(ClientResponse.class);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
    }

    String output = response.getEntity(String.class);

    return output;
}
项目:emodb    文件:EmoModule.java   
/** Create an SOA QueueService client for forwarding non-partition-aware clients to the right server. */
@Provides @Singleton @PartitionAwareClient
QueueServiceAuthenticator provideQueueClient(QueueService queueService, Client jerseyClient,
                                             @SelfHostAndPort HostAndPort self, @Global CuratorFramework curator,
                                             MetricRegistry metricRegistry, HealthCheckRegistry healthCheckRegistry) {
    MultiThreadedServiceFactory<AuthQueueService> serviceFactory = new PartitionAwareServiceFactory<>(
            AuthQueueService.class,
            QueueClientFactory.forClusterAndHttpClient(_configuration.getCluster(), jerseyClient),
            new TrustedQueueService(queueService), self, healthCheckRegistry, metricRegistry);
    AuthQueueService client = ServicePoolBuilder.create(AuthQueueService.class)
            .withHostDiscovery(new ZooKeeperHostDiscovery(curator, serviceFactory.getServiceName(), metricRegistry))
            .withServiceFactory(serviceFactory)
            .withMetricRegistry(metricRegistry)
            .withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
            .buildProxy(new ExponentialBackoffRetry(5, 50, 1000, TimeUnit.MILLISECONDS));
    _environment.lifecycle().manage(new ManagedServicePoolProxy(client));
    return QueueServiceAuthenticator.proxied(client);
}
项目:music    文件:TestMusicE2E.java   
private  boolean acquireLock(String lockId){
    Client client = Client.create();
    String msg = musicHandle.getMusicNodeURL()+"/locks/acquire/"+lockId;
    System.out.println(msg);
    WebResource webResource = client.resource(msg);


    WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);

    ClientResponse response = wb.get(ClientResponse.class);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+msg);
    }

    String output = response.getEntity(String.class);
    Boolean status = Boolean.parseBoolean(output);
    System.out.println("Server response .... \n");
    System.out.println(output);
    return status;
}
项目:emodb    文件:EmoModule.java   
/** Provides a DataStore client that delegates to the remote system center data store. */
@Provides @Singleton @SystemDataStore
DataStore provideSystemDataStore (DataCenterConfiguration config, Client jerseyClient, @Named ("AdminKey") String apiKey, MetricRegistry metricRegistry) {

    ServiceFactory<DataStore> clientFactory = DataStoreClientFactory
            .forClusterAndHttpClient(_configuration.getCluster(), jerseyClient)
            .usingCredentials(apiKey);

    URI uri = config.getSystemDataCenterServiceUri();
    ServiceEndPoint endPoint = new ServiceEndPointBuilder()
            .withServiceName(clientFactory.getServiceName())
            .withId(config.getSystemDataCenter())
            .withPayload(new PayloadBuilder()
                    .withUrl(uri.resolve(DataStoreClient.SERVICE_PATH))
                    .withAdminUrl(uri)
                    .toString())
            .build();

    return ServicePoolBuilder.create(DataStore.class)
            .withMetricRegistry(metricRegistry)
            .withHostDiscovery(new FixedHostDiscovery(endPoint))
            .withServiceFactory(clientFactory)
            .buildProxy(new ExponentialBackoffRetry(30, 1, 10, TimeUnit.SECONDS));
}
项目:music    文件:MusicRestClient.java   
public  void createRow(String keyspaceName, String tableName,Map<String, Object> values){
    Map<String,String> consistencyInfo= new HashMap<String, String>();
    consistencyInfo.put("type", "eventual");

    JsonInsert jIns = new JsonInsert();
    jIns.setValues(values);
    jIns.setConsistencyInfo(consistencyInfo);
    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    Client client = Client.create(clientConfig);

    String url =getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/"+tableName+"/rows";
    WebResource webResource = client
            .resource(url);

    ClientResponse response = webResource.accept("application/json")
            .type("application/json").post(ClientResponse.class, jIns);

    if (response.getStatus() < 200 || response.getStatus() > 299) 
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+url+"values:"+values);


}
项目:music    文件:MusicRestClient.java   
public void createStringMapTable(String keyspaceName, String tableName,Map<String,String> fields){
    Map<String,String> consistencyInfo= new HashMap<String, String>();
    consistencyInfo.put("type", "eventual");

    JsonTable jtab = new JsonTable();
    jtab.setFields(fields);
    jtab.setConsistencyInfo(consistencyInfo);

    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    Client client = Client.create(clientConfig);
    String url = getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/"+tableName;
    WebResource webResource = client
            .resource(url);

    ClientResponse response = webResource.accept("application/json")
            .type("application/json").post(ClientResponse.class, jtab);

    if (response.getStatus() < 200 || response.getStatus() > 299) 
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());

}
项目:forge-api-java-client    文件:ApiClient.java   
/**
 * Build the Client used to make HTTP requests with the latest settings,
 * i.e. objectMapper and debugging.
 * TODO: better to use the Builder Pattern?
 */
public ApiClient rebuildHttpClient() {
  // Add the JSON serialization support to Jersey
  JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper);
  DefaultClientConfig conf = new DefaultClientConfig();
  conf.getSingletons().add(jsonProvider);
  Client client = Client.create(conf);
  if (debugging) {
    client.addFilter(new LoggingFilter());
  }

  //to solve the issue of GET:metadata/:guid with accepted encodeing is 'gzip' 
  //in the past, when clients use gzip header, actually it doesn't trigger a gzip encoding... So everything is fine 
  //After the release, the content is return in gzip, while the sdk doesn't handle it correctly
  client.addFilter(new GZIPContentEncodingFilter(false));

  this.httpClient = client;
  return this;
}
项目:music    文件:MusicHandle.java   
public static void dropKeySpace(String keyspaceName){
    Map<String,String> consistencyInfo= new HashMap<String, String>();
    consistencyInfo.put("type", "eventual");

    JsonKeySpace jsonKp = new JsonKeySpace();
    jsonKp.setConsistencyInfo(consistencyInfo);

    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    Client client = Client.create(clientConfig);

    WebResource webResource = client
            .resource(HalUtil.getMusicNodeURL()+"/keyspaces/"+keyspaceName);

    ClientResponse response = webResource.type("application/json")
            .delete(ClientResponse.class, jsonKp);

    if (response.getStatus() < 200 || response.getStatus() > 299) 
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
}
项目:motu    文件:RestUtilTest.java   
/**
 * Create a client which trust any HTTPS server
 * 
 * @return
 */
public static Client hostIgnoringClient() {
    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        DefaultClientConfig config = new DefaultClientConfig();
        Map<String, Object> properties = config.getProperties();
        HTTPSProperties httpsProperties = new HTTPSProperties(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        }, sslcontext);
        properties.put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, httpsProperties);
        // config.getClasses().add( JacksonJsonProvider.class );
        return Client.create(config);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
项目:music    文件:MusicHandle.java   
public  static String whoIsLockHolder(String lockName){
    Client client = Client.create();
    WebResource webResource = client.resource(HalUtil.getMusicNodeURL()+"/locks/enquire/"+lockName);


    WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN);

    ClientResponse response = wb.get(ClientResponse.class);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
    }

    String output = response.getEntity(String.class);
//  System.out.println("Server response .... \n");
//  System.out.println(output);
    return output;
}
项目:music    文件:VotingApp.java   
public  Map<String,Object> readVoteCountForCandidate(String candidateName){
    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    Client client = Client.create(clientConfig);
    String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+candidateName;
    WebResource webResource = client
            .resource(url);

    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

    if (response.getStatus() < 200 || response.getStatus() > 299) 
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());

    Map<String,Object> output = response.getEntity(Map.class);
    return output;  
}
项目:music    文件:VotingApp.java   
private void dropKeySpace(){
    Map<String,String> consistencyInfo= new HashMap<String, String>();
    consistencyInfo.put("type", "eventual");

    JsonKeySpace jsonKp = new JsonKeySpace();
    jsonKp.setConsistencyInfo(consistencyInfo);

    ClientConfig clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    Client client = Client.create(clientConfig);

    WebResource webResource = client
            .resource(musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName);

    ClientResponse response = webResource.type("application/json")
            .delete(ClientResponse.class, jsonKp);

    if (response.getStatus() < 200 || response.getStatus() > 299) 
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
}
项目:blog-multi-region-serverless-service    文件:JavaClient.java   
public static void main(String [] args) {
    System.out.println("Simple Java test for calling Hello Word service");

    try {
        // Get the endpoint for Hello World API
        String endpoint = args[0];

        // Create the client and call the API
        Client client = Client.create();
        WebResource webResource = client
                .resource(endpoint+"helloworld/");
        ClientResponse response = webResource.accept("application/json")
                .get(ClientResponse.class);

        // Process the result
        if (response.getStatus() != 200) {
            throw new RuntimeException("Called failed to HelloWorld : "
                    + response.getStatus());
        }

        String output = response.getEntity(String.class);

        System.out.println("Response: ");
        System.out.println(output);

    } catch (Exception e) {
        e.printStackTrace();
    }

}
项目:gw2_launcher    文件:UpdateNotifier.java   
private String getJSONData(){
    Client client = Client.create();
    WebResource webResource = client.resource(UriBuilder.fromUri("https://api.github.com/repos/"+username+"/"+repoName+"/releases").build());
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    String output = response.getEntity(String.class);
    return output;
}
项目:SigFW    文件:RestClientTest.java   
public static void main(String[] args) throws Exception {

     try {
         //Client client = Client.create();
         // Accept self-signed certificates
         Client client = createClient();

         String username = "user";
         String password = "password";
         //client.addFilter(new HTTPBasicAuthFilter(username, password));
         HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
         client.register(feature);

         WebTarget webResource = client.target("https://localhost:8443");
         WebTarget webResourceWithPath = webResource.path("ss7fw_api/1.0/eval_sccp_message_in_ids");
         WebTarget webResourceWithQueryParam = webResourceWithPath.matrixParam("sccp_raw", "12345");

         System.out.println(webResourceWithQueryParam);

         //ClientResponse response = webResourceWithQueryParam.accept("text/plain").get(ClientResponse.class);
         Response response = webResourceWithQueryParam.request("text/plain").get();

         if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
         }

         String output = response.readEntity(String.class);

         System.out.println("Output from Server .... \n");
         System.out.println(output);

} catch (Exception e) {
           e.printStackTrace();
}

 }
项目:jeta    文件:RestClient.java   
private static WebResource getWebResource(String url, ClientConfig config, String content_type) {
    logger.info("WebResource url = " + url + " , content_type = " + content_type);
    Client client;
    if (config != null) {
        client = Client.create(config);
    } else {
        client = Client.create();
    }
    return client.resource(url);
}
项目:Shopping-Cart-using-Web-Services    文件:MyClientRest.java   
public MyClientRest(String myName){

    this.myName=myName;
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    service = client.resource(REST_URI);

}
项目:media_information_service    文件:OAuthController.java   
@RequestMapping(value = "/dropboxcallback", method = {RequestMethod.GET, RequestMethod.POST})
public String dropboxFlow(@RequestParam(value = "code", defaultValue = "") String code, HttpServletRequest request, Model model) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource webResource = client.resource(UriBuilder.fromUri("https://api.dropboxapi.com/oauth2/token").build());
    MultivaluedMap formData = new MultivaluedMapImpl();
    formData.add("code", code);
    formData.add("client_id", MISConfig.getDropbox_id());
    formData.add("redirect_uri", MISConfig.getDropbox_redirect());
    formData.add("client_secret",
            MISConfig.getDropbox_secret());
    formData.add("grant_type", "authorization_code");
    ClientResponse response1 = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); //Exchange code for token
    String json = response1.getEntity(String.class);
    JSONObject jsonObj = new JSONObject(json);
    String token=jsonObj.getString("access_token");
    List<String> names= DbxAPIOp.dropboxGetFiles(token); //Get files name

    List<FilmInfo> films=new LinkedList<FilmInfo>();
    List<BookInfo> books=new LinkedList<BookInfo>();
    List<MusicInfo> songs=new LinkedList<MusicInfo>();
    try {
        MediaOperations.findMediaInfo(names,books,films,songs); //Find info about files
    } catch (Exception e) {
        e.printStackTrace();
    }

    model.addAttribute("films",films);
    model.addAttribute("books",books);
    model.addAttribute("songs",songs);
    if(names!=null) RabbitSend.sendOAuth(MediaOperations.getFilesName(names),"Dropbox", request);
    //Generate HTML result page
    if(books.size()==0 && films.size()==0 && songs.size()==0) return "error_scan";
    else return "result_scan";
    }
项目:media_information_service    文件:UpdateNotifier.java   
private String getJSONData(){
    Client client = Client.create();
    WebResource webResource = client.resource(UriBuilder.fromUri("https://api.github.com/repos/"+username+"/"+repoName+"/releases").build());
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    String output = response.getEntity(String.class);
    //System.out.println(output);
    return output;
}
项目:keybiner    文件:ABFCodeMap.java   
public static ImmutableBiMap<String,String> getABFMapper()    {
    String serviceURL = null;
    ImmutableBiMap<String,String> ABFMAPPER = null;
    try {
        serviceURL = System.getenv("authcode.service.URL");
        if (serviceURL == null)
            serviceURL = System.getProperty("authcode.service.URL","http://localhost:9876/references");
        LOG.info("Initializing ABF Reference with remote service URL: "+ serviceURL);
        Client client = Client.create();
        WebResource webResource = client.resource(serviceURL);
        ClientResponse response = webResource.accept("application/json")
                .get(ClientResponse.class);
        String output = response.getEntity(String.class);
        if (response.getStatus() == 200 && output != null && !output.isEmpty()) {
            Map<String, String> mapResponse = OBJECT_MAPPER.readValue(output, new TypeReference<Map<String, String>>() {});
            ABFMAPPER = ImmutableBiMap.copyOf(Collections.unmodifiableMap(mapResponse));
            LOG.info("Success on getting ABF Reference map from  "+ serviceURL);
        } else {
            ABFMAPPER = ImmutableBiMap.copyOf(Collections.unmodifiableMap(ABFCodeMap.defaultABFMapper()));
        }

    }catch(Exception ex){
        ABFMAPPER = ImmutableBiMap.copyOf(Collections.unmodifiableMap(ABFCodeMap.defaultABFMapper()));
        LOG.warn("ABF Mapper initialization failed");
    }
    return ABFMAPPER;
}
项目:athena    文件:XosManagerRestUtils.java   
/**
 * Gets a client web resource builder for the base XOS REST API
 * with an optional additional URI.
 *
 * @param uri URI suffix to append to base URI
 * @return web resource builder
 */
public WebResource.Builder getClientBuilder(String uri) {
    Client client = Client.create();
    client.addFilter(new HTTPBasicAuthFilter(AUTH_USER, AUTH_PASS));
    WebResource resource = client.resource(baseUrl() + uri);
    log.info("XOS REST CALL>> {}", resource);
    return resource.accept(UTF_8).type(UTF_8);
}
项目:music    文件:MusicHandle.java   
public MusicHandle(String[] musicNodes, int repFactor){
    this.musicNodes = musicNodes;
    this.repFactor=repFactor;

    bmKeySpace = "BmKeySpace";
    bmTable = "BmEmployees";

    clientConfig = new DefaultClientConfig();

    clientConfig.getFeatures().put(
            JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    client = Client.create(clientConfig);
}
项目:emodb    文件:ScanUploadModule.java   
@Inject
public QueueScanWorkflowProvider(@Global CuratorFramework curator, @ServerCluster String cluster,
                                 Client client, @Named ("ScannerAPIKey") String apiKey,
                                 @Named ("pendingScanRangeQueueName") Optional<String> pendingScanRangeQueueName,
                                 @Named ("completeScanRangeQueueName") Optional<String> completeScanRangeQueueName,
                                 Environment environment, MetricRegistry metricRegistry) {
    _curator = curator;
    _cluster = cluster;
    _client = client;
    _apiKey = apiKey;
    _environment = environment;
    _metricRegistry = metricRegistry;
    _pendingScanRangeQueueName = pendingScanRangeQueueName.or("emodb-pending-scan-ranges");
    _completeScanRangeQueueName = completeScanRangeQueueName.or("emodb-complete-scan-ranges");
}
项目:motu    文件:RestUtil.java   
/**
 * Gets the cas restlet url.
 * 
 * @param client the client
 * @param method the method
 * @param serviceURL the service url
 * @param casRestUrlSuffix the cas rest url suffix
 * @return the cas restlet url
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MotuCasBadRequestException the motu cas bad request exception
 */
public static String getCasRestletUrl(Client client, RestUtil.HttpMethod method, String serviceURL, String casRestUrlSuffix)
        throws IOException, MotuCasBadRequestException {

    if (client == null) {
        return null;

    }
    String casServerPrefix = RestUtil.getRedirectUrl(serviceURL, client, method);
    if (AssertionUtils.isNullOrEmpty(casServerPrefix)) {
        return null;
    }

    // StringBuffer stringBuffer = new StringBuffer();
    // stringBuffer.append(casServerPrefix);
    // if ((!casServerPrefix.endsWith("/")) && (!casRestUrlSuffix.startsWith("/"))) {
    // stringBuffer.append("/");
    // }
    //
    // if ((casServerPrefix.endsWith("/")) && (casRestUrlSuffix.startsWith("/"))) {
    // stringBuffer.append(casRestUrlSuffix.substring(1));
    // } else {
    // stringBuffer.append(casRestUrlSuffix);
    // }
    //
    // return stringBuffer.toString();

    return RestUtil.appendPath(casServerPrefix, casRestUrlSuffix);

}
项目:OpenChatAlytics    文件:HipChatApiDAOFactory.java   
public static IChatApiDAO getHipChatApiDao(ChatAlyticsConfig config) {
    if (hipchatDaoImpl == null) {
        DefaultClientConfig clientConfig = new DefaultClientConfig();
        Client client = Client.create(clientConfig);
        hipchatDaoImpl = new JsonHipChatDAO(config, client);
    }
    return hipchatDaoImpl;
}
项目:aiko    文件:RequestDefinition.java   
private Client createClient() {
    Client client = Client.create();
    client.setConnectTimeout(60_000);
    client.setReadTimeout(60_000);

    return client;
}
项目:aiko    文件:RequestDefinition.java   
private WebResource getWebResource(final Client client, final String domain) {
    String path = getUri().replaceAll("/$", "");
    URI uri = URI.create(domain + path);

    System.out.println("\t\t" + method + " " + uri.toASCIIString());

    return client.resource(uri);
}
项目:conductor    文件:ClientBase.java   
protected ClientBase(ClientConfig cc, ClientHandler handler) {
    JacksonJsonProvider provider = new JacksonJsonProvider(objectMapper());
    cc.getSingletons().add(provider);
    if (handler == null) {
        this.client = Client.create(cc);
    } else {
        this.client = new Client(handler, cc);
    }       
}
项目:galaxy-PROV    文件:GHistAPI.java   
public GHistAPI(String gURL, String gApiKey) {
    try {
        this.gURL = gURL;
        this.gApiKey = gApiKey;

        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        this.service = client.resource(new URI(gURL));
    } catch (URISyntaxException ex) {
        logger.error(ex.getMessage());
        ex.printStackTrace();
    }
}
项目:emodb    文件:SecurityModule.java   
@Provides
@Singleton
SubjectUserAccessControl provideSubjectUserAccessControl(LocalSubjectUserAccessControl local,
                                                         DataCenterConfiguration dataCenterConfiguration,
                                                         @ServerCluster String cluster,
                                                         Client jerseyClient, MetricRegistry metricRegistry) {
    // If this is the system data center all user access control can be performed locally
    if (dataCenterConfiguration.isSystemDataCenter()) {
        return local;
    }

    // Create a client for forwarding user access control requests to the system data center
    ServiceFactory<AuthUserAccessControl> clientFactory = UserAccessControlClientFactory
            .forClusterAndHttpClient(cluster, jerseyClient);

    URI uri = dataCenterConfiguration.getSystemDataCenterServiceUri();
    ServiceEndPoint endPoint = new ServiceEndPointBuilder()
            .withServiceName(clientFactory.getServiceName())
            .withId(dataCenterConfiguration.getSystemDataCenter())
            .withPayload(new PayloadBuilder()
                    .withUrl(uri.resolve(DataStoreClient.SERVICE_PATH))
                    .withAdminUrl(uri)
                    .toString())
            .build();

    AuthUserAccessControl uac = ServicePoolBuilder.create(AuthUserAccessControl.class)
            .withMetricRegistry(metricRegistry)
            .withHostDiscovery(new FixedHostDiscovery(endPoint))
            .withServiceFactory(clientFactory)
            .buildProxy(new ExponentialBackoffRetry(30, 1, 10, TimeUnit.SECONDS));

    RemoteSubjectUserAccessControl remote = new RemoteSubjectUserAccessControl(uac);

    // Provide an instance which satisfies read requests locally and forwards write requests to the
    // system data center
    return new ReadWriteDelegatingSubjectUserAccessControl(local, remote);
}