Java Code Examples for com.sun.jersey.api.client.Client#create()

The following examples show how to use com.sun.jersey.api.client.Client#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RunnerCoordinator.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * Stop the tests on given runners and puts them into STOPPED state, if indeed they were RUNNING.
 *
 * @param runners    Runners that are running the tests
 * @return           Map of resulting states of <code>runners</code>, after the operation
 */
public Map<Runner, State> stop( Collection<Runner> runners ) {
    Map<Runner, State> states = new HashMap<Runner, State>( runners.size() );
    for( Runner runner: runners ) {
        trustRunner( runner.getUrl() );
        DefaultClientConfig clientConfig = new DefaultClientConfig();
        Client client = Client.create( clientConfig );
        WebResource resource = client.resource( runner.getUrl() ).path( Runner.STOP_POST );
        BaseResult response = resource.type( MediaType.APPLICATION_JSON ).post( BaseResult.class );
        if( ! response.getStatus() ) {
            LOG.warn( "Tests at runner {} could not be stopped.", runner.getUrl() );
            LOG.warn( response.getMessage() );
            states.put( runner, null );
        }
        else {
            states.put( runner, response.getState() );
        }
    }
    return states;
}
 
Example 2
Source File: TestRMHA.java    From big-c with Apache License 2.0 6 votes vote down vote up
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
  }
 
Example 3
Source File: EagleServiceBaseClient.java    From Eagle with Apache License 2.0 6 votes vote down vote up
public EagleServiceBaseClient(String host, int port, String basePath, String username, String password) {
    this.host = host;
    this.port = port;
    this.basePath = basePath;
    this.baseEndpoint = buildBathPath().toString();
    this.username = username;
    this.password = password;

    ClientConfig cc = new DefaultClientConfig();
    cc.getProperties().put(DefaultClientConfig.PROPERTY_CONNECT_TIMEOUT, 60 * 1000);
    cc.getProperties().put(DefaultClientConfig.PROPERTY_READ_TIMEOUT, 60 * 1000);
    cc.getClasses().add(JacksonJsonProvider.class);
    cc.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);
    this.client = Client.create(cc);
    client.addFilter(new com.sun.jersey.api.client.filter.GZIPContentEncodingFilter());
    //        Runtime.getRuntime().addShutdownHook(new EagleServiceClientShutdownHook(this));
}
 
Example 4
Source File: YarnHttpClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void validateApiEndpoint() throws YarnClientException, MalformedURLException {
    YarnEndpoint dashEndpoint = new YarnEndpoint(apiEndpoint, YarnResourceConstants.APPLICATIONS_PATH);

    ClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create(clientConfig);

    WebResource webResource = client.resource(dashEndpoint.getFullEndpointUrl().toString());
    ClientResponse response = webResource.accept("application/json").type("application/json").get(ClientResponse.class);

    // Validate HTTP 200 status code
    if (response.getStatus() != YarnResourceConstants.HTTP_SUCCESS) {
        String msg = String.format("Received %d status code from url %s, reason: %s",
                response.getStatus(),
                dashEndpoint.getFullEndpointUrl().toString(),
                response.getEntity(String.class));
        LOGGER.debug(msg);
        throw new YarnClientException(msg);
    }
}
 
Example 5
Source File: EmpClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
    String uri = "http://localhost:8080/rest/emp/getEmp";
    EmpRequest request = new EmpRequest();
    request.setId(2);
    request.setName("PK");
    try{
    Client client = Client.create();
    WebResource r=client.resource(uri);
    ClientResponse response = r.type(MediaType.APPLICATION_XML).post(ClientResponse.class,request );
    System.out.println(response.getStatus());
    if(response.getStatus() == 200){
        EmpResponse empResponse = response.getEntity(EmpResponse.class);
        System.out.println(empResponse.getId() + "::"+empResponse.getName());
    }else{
        ErrorResponse exc = response.getEntity(ErrorResponse.class);
        System.out.println(exc.getErrorCode());
        System.out.println(exc.getErrorId());
    }
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
}
 
Example 6
Source File: MailgunService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
@Override
public EmailSendingStatus sendEmail(EmailWrapper wrapper) {
    try (FormDataMultiPart email = parseToEmail(wrapper)) {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("api", Config.MAILGUN_APIKEY));
        WebResource webResource =
                client.resource("https://api.mailgun.net/v3/" + Config.MAILGUN_DOMAINNAME + "/messages");

        ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
                .post(ClientResponse.class, email);

        return new EmailSendingStatus(response.getStatus(), response.getStatusInfo().getReasonPhrase());
    } catch (IOException e) {
        log.warning("Could not clean up resources after sending email: " + TeammatesException.toStringWithStackTrace(e));
        return new EmailSendingStatus(HttpStatus.SC_OK, e.getMessage());
    }
}
 
Example 7
Source File: JCRSolutionFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public JCRSolutionFileModel( final String url,
                             final String username,
                             final String password,
                             final int timeout ) {
  if ( url == null ) {
    throw new NullPointerException();
  }
  this.url = url;
  descriptionEntries = new HashMap<FileName, String>();

  final ClientConfig config = new DefaultClientConfig();
  config.getProperties().put( ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true );
  config.getProperties().put( ClientConfig.PROPERTY_READ_TIMEOUT, timeout );
  this.client = Client.create( config );
  this.client.addFilter( new CookiesHandlerFilter() ); // must be inserted before HTTPBasicAuthFilter
  this.client.addFilter( new HTTPBasicAuthFilter( username, password ) );
  this.majorVersion = "999";
  this.minorVersion = "999";
  this.releaseVersion = "999";
  this.buildVersion = "999";
  this.milestoneVersion = "999";
  this.loadTreePartially = Boolean.parseBoolean( PARTIAL_LOADING_ENABLED );
}
 
Example 8
Source File: RunnerCoordinator.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the run State of all given runners as a map.
 * <p>
 * <ul>
 *     <li>Key of map is the runner</li>
 *     <li>Value field is the state of a runner, or null if state could not be retrieved</li>
 * </ul>
 *
 * @param runners    Runners to get states
 * @return           Map of all Runner, State pairs
 */
public Map<Runner, State> getStates( Collection<Runner> runners ) {
    Map<Runner, State> states = new HashMap<Runner, State>( runners.size() );
    for( Runner runner: runners ) {
        trustRunner( runner.getUrl() );
        DefaultClientConfig clientConfig = new DefaultClientConfig();
        Client client = Client.create( clientConfig );
        LOG.info( "Runner to get state: {}", runner.getUrl() );
        WebResource resource = client.resource( runner.getUrl() ).path( Runner.STATUS_GET );
        BaseResult response = resource.type( MediaType.APPLICATION_JSON ).get( BaseResult.class );
        if( ! response.getStatus() ) {
            LOG.warn( "Could not get the state of Runner at {}", runner.getUrl() );
            LOG.warn( response.getMessage() );
            states.put( runner, null );
        }
        else {
            states.put( runner, response.getState() );
        }
    }
    return states;
}
 
Example 9
Source File: NiFiClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
protected WebResource getWebResource() {
    final ClientConfig config = new DefaultClientConfig();
    if (sslContext != null) {
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(hostnameVerifier, sslContext));
    }

    final Client client = Client.create(config);
    return client.resource(url);
}
 
Example 10
Source File: SystemStatus.java    From Insights with Apache License 2.0 5 votes vote down vote up
public static String jerseyPostClientWithAuthentication(String url, String name, String password,
		String authtoken, String data) {
	String output;
	String authStringEnc;
	ClientResponse response = null;
	try {
		if (authtoken == null) {
			String authString = name + ":" + password;
			authStringEnc = new BASE64Encoder().encode(authString.getBytes());
		} else {
			authStringEnc = authtoken;
		}
		JsonParser parser = new JsonParser();
		JsonElement dataJson = parser.parse(data);//new Gson().fromJson(data, JsonElement.class)
		Client restClient = Client.create();
		restClient.setConnectTimeout(5001);
		WebResource webResource = restClient.resource(url);
		response = webResource.accept("application/json")
				//.header("Authorization", "Basic " + authStringEnc)
				.post(ClientResponse.class, dataJson.toString());//"{aa}"
		if (response.getStatus() != 200) {
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
		} else {
			output = response.getEntity(String.class);
		}
		System.out.print(" response code " + response.getStatus() + "  output  " + output);
	} catch (Exception e) {
		System.out.println(" error while getGetting  jerseyPostClientWithAuthentication " + e.getMessage());
		throw new RuntimeException(
				"Failed : error while getGetting jerseyPostClientWithAuthentication : " + e.getMessage());
	} finally {
		if (response != null) {
			response.close();
		}
	}
	return output;
}
 
Example 11
Source File: EcsSyncCtl.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
public EcsSyncCtl(String endpoint) {
    this.endpoint = endpoint;
    this.pluginResolver = new PluginResolver();

    // initialize REST client
    ClientConfig cc = new DefaultClientConfig();
    cc.getSingletons().add(pluginResolver);
    this.client = Client.create(cc);
}
 
Example 12
Source File: TeamctiyRest.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Trigger a build on the Teamcity instance using vcs root
 *
 * @param repository - {@link Repository}
 * @param url - url to TeamCity server
 * @param username - TeamCity user name
 * @param password - TeamCity user password
 * @return "OK" if it worked. Otherwise, an error message.
 */
@GET
@Path(value = "testconnection")
@Produces("text/plain; charset=UTF-8")
public Response testconnection(
        @Context final Repository repository,
        @QueryParam("url") final String url,
        @QueryParam("username") final String username,
        @QueryParam("password") final String password,
        @QueryParam("debugon") final String isDebugOn) {

  String realPasswordValue = password;
  if (Constant.TEAMCITY_PASSWORD_SAVED_VALUE.equals(realPasswordValue)) {
    realPasswordValue = this.connectionSettings.getPassword(repository);
  }

  final Client restClient = Client.create(Constant.REST_CLIENT_CONFIG);
  restClient.addFilter(new HTTPBasicAuthFilter(username, realPasswordValue));

  try {
    final ClientResponse response = restClient.resource(url + "/app/rest/builds?locator=lookupLimit:0").accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    if (ClientResponse.Status.OK == response.getClientResponseStatus()) {
      this.connectionSettings.savePassword(realPasswordValue, repository);
      return Response.ok(Constant.TEAMCITY_PASSWORD_SAVED_VALUE).build();
    } else {
      return Response.status(response.getClientResponseStatus()).entity(response.getEntity(String.class)).build();
    }
  } catch (final UniformInterfaceException | ClientHandlerException e) {
    return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
  } finally {
    restClient.destroy();
  }
}
 
Example 13
Source File: RegionClient.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
public RegionClient() {
    com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    client = Client.create(config);
    webResource = client.resource(DataApplication.SERVER_URI).path("com.javafx.experiments.dataapp.model.region");
}
 
Example 14
Source File: DyCrokageApp.java    From CROKAGE-replication-package with MIT License 4 votes vote down vote up
@PostConstruct
public void init() throws Exception {
	System.out.println("Initializing app...");
	
	client = Client.create();
	
	gson = new GsonBuilder()
			  .excludeFieldsWithoutExposeAnnotation()
			  .create();
	
	jsonInput = "{\"numberOfComposedAnswers\":"+numberOfComposedAnswers+",\"reduceSentences\":false,\"queryText\":\"___queryText___\",\"ipAddress\":\"__ipAddress__\"}";
	jsonInput = jsonInput.replace("__ipAddress__", InetAddress.getLocalHost().toString());
	
	webResourceGetCandidadeBuckets = client.resource(stackOverflowSolutionsURL);
	
	String queries[] = {
			"how to add an element in an array in a specific position",
			"Convert between a file path and url",
			"convert string to number",
			"How to build rest service in java",
			"how do iterate and filter to a stream",
			"parse html with regex",
			"how to deserialize json string to object",			
			"how to remove characters from a string",
			"how to print to screen",
			
	};
	
	
	for(String query: queries) {
		processedQuery = CrokageUtils.processQuery(query,true);
		
		processedInput = jsonInput.replace("___queryText___", processedQuery);
		System.out.println("\n\nGetting solutions for: "+processedQuery);
		ClientResponse response = webResourceGetCandidadeBuckets.type("application/json").post(ClientResponse.class, processedInput);
		String output = response.getEntity(String.class);
		PostRestTransfer postRestTransfer = gson.fromJson(output, PostRestTransfer.class);
		
		List<Post> posts = postRestTransfer.getPosts();
		int pos=1;
		logger.info("Solutions for: "+query);
		for(Post answer: posts) {
			//via link
			logger.info("https://stackoverflow.com/questions/"+answer.getId());
			
			//or directly 
			//logger.info("Answer: "+pos+" -id:"+answer.getId()+ " -body: "+answer.getBody());
			
			pos++;
		}
		
		
	}
	
}
 
Example 15
Source File: YarnHttpClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public WebResource getNewWebResourceWithClientConfig(ClientConfig clientConfig, String url) {
    Client client = Client.create(clientConfig);
    return client.resource(url);
}
 
Example 16
Source File: PizzaClient.java    From jersey-hmac-auth with Apache License 2.0 4 votes vote down vote up
private static Client createClient(String apiKey, String secretKey) {
    Client client = Client.create();
    client.addFilter(new HmacClientFilter(apiKey, secretKey, client.getMessageBodyWorkers()));
    return client;
}
 
Example 17
Source File: BrooklynMetricsRetrieverV1.java    From SeaCloudsPlatform with Apache License 2.0 4 votes vote down vote up
private static Client buildJerseyClient() {
    ClientConfig config = new DefaultClientConfig();
    Client jerseyClient = Client.create(config);
    return jerseyClient;
}
 
Example 18
Source File: RegionClient.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
public RegionClient() {
    com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig();
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    client = Client.create(config);
    webResource = client.resource(DataApplication.SERVER_URI).path("com.javafx.experiments.dataapp.model.region");
}
 
Example 19
Source File: RDFServerExtensionTest.java    From neo4j-sparql-extension with GNU General Public License v3.0 4 votes vote down vote up
protected Client request() {
	DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
	defaultClientConfig.getClasses().add(JacksonJsonProvider.class);
	return Client.create(defaultClientConfig);
}
 
Example 20
Source File: SourceForgeDownloadCounterMetricProvider.java    From scava with Eclipse Public License 2.0 3 votes vote down vote up
@Override
public void measure(Project project, ProjectDelta delta, DownloadCounter db) {
	
	
	String deltaDate = toString(delta.getDate());
	String previousDeltaDate = toString(delta.getDate().addDays(-1));
		
	try {
		Client client = Client.create(); 
		
		String restRequest = "http://sourceforge.net/projects/" +  project.getName() + "/files/stats/json?start_date=" + previousDeltaDate + "&end_date=" + deltaDate;
		
		WebResource webResource = client.resource(restRequest);
		ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
		String output = response.getEntity(String.class);
		
		int counter = JsonPath.read(output, "$.summaries.time.downloads");

		Download download = new Download();
		download.setCounter(counter);
		download.setDate(deltaDate);
		
		db.getDownloads().add(download);
		
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}

	db.sync();
	
}