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

The following examples show how to use com.sun.jersey.api.client.Client#resource() . 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: Neo4jDBHandler.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * @param requestJson
 * @return ClientResponse
 */
private ClientResponse doCommitCall(JsonObject requestJson) {
	Client client = Client.create();
	if(ApplicationConfigProvider.getInstance().getGraph().getConnectionExpiryTimeOut() != null) 
	{
		client.setConnectTimeout(ApplicationConfigProvider.getInstance().getGraph().getConnectionExpiryTimeOut() * 1000);
	}
	WebResource resource = client
			// .resource("http://localhost:7474/db/data/transaction/commit");
			.resource(ApplicationConfigProvider.getInstance().getGraph().getEndpoint()
					+ "/db/data/transaction/commit");
	ClientResponse response = resource.accept(MediaType.APPLICATION_JSON)
			.header("Authorization", ApplicationConfigProvider.getInstance().getGraph().getAuthToken())
			// ClientResponse response = resource.accept( MediaType.APPLICATION_JSON
			// ).header("Authorization", "Basic bmVvNGo6YWRtaW4=")
			.type(MediaType.APPLICATION_JSON).entity(requestJson.toString()).post(ClientResponse.class);
	return response;
}
 
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: RestApiUtils.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates a GET request using the specified URL.
 *
 * @param url
 *            the URL to send the request to
 * @param authToken
 *            the authentication token to use for this request
 * @return the response from the request
 */
private TsResponse get(String url, String authToken) {
    // Creates the HTTP client object and makes the HTTP request to the
    // specified URL
    Client client = Client.create();
    WebResource webResource = client.resource(url);

    // Sets the header and makes a GET request
    ClientResponse clientResponse = webResource.header(TABLEAU_AUTH_HEADER, authToken).get(ClientResponse.class);

    // Parses the response from the server into an XML string
    String responseXML = clientResponse.getEntity(String.class);

    m_logger.info("Response: \n" + responseXML);

    // Returns the unmarshalled XML response
    return unmarshalResponse(responseXML);
}
 
Example 4
Source File: RestApiUtils.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates a POST request using the specified URL without a payload.
 *
 * @param url
 *            the URL to send the request to
 * @param authToken
 *            the authentication token to use for this request
 * @return the response from the request
 */
private TsResponse post(String url, String authToken) {

    // Creates the HTTP client object and makes the HTTP request to the
    // specified URL
    Client client = Client.create();
    WebResource webResource = client.resource(url);

    // Makes a POST request with the payload and credential
    ClientResponse clientResponse = webResource.header(TABLEAU_AUTH_HEADER, authToken).post(ClientResponse.class);

    // Parses the response from the server into an XML string
    String responseXML = clientResponse.getEntity(String.class);

    m_logger.debug("Response: \n" + responseXML);

    // Returns the unmarshalled XML response
    return unmarshalResponse(responseXML);
}
 
Example 5
Source File: KylinClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
private static ClientResponse getProjectResponse(String url, Client client) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("getProjectResponse():calling " + url);
	}

	WebResource webResource = client.resource(url);

	ClientResponse response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);

	if (response != null) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("getProjectResponse():response.getStatus()= " + response.getStatus());
		}
		if (response.getStatus() != HttpStatus.SC_OK) {
			LOG.warn("getProjectResponse():response.getStatus()= " + response.getStatus() + " for URL " + url
					+ ", failed to get kylin project list.");
			String jsonString = response.getEntity(String.class);
			LOG.warn(jsonString);
		}
	}
	return response;
}
 
Example 6
Source File: NexusConnector.java    From jenkins-deployment-dashboard-plugin with MIT License 6 votes vote down vote up
public List<Artifact> getArtefactList(String groupId, String artifactId) {
    LOGGER.info("Get artifact list for " + groupId + " " + artifactId);
    List<Artifact> list = new ArrayList<Artifact>();

    final Client client = buildClient();
    final WebResource restResource = client.resource(repositoryURI);
    WebResource path = restResource.path("service").path("local").path("lucene").path("search");
    WebResource queryParam = path.queryParam("g", groupId).queryParam("a", artifactId);
    final ClientResponse clientResponse = queryParam.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);

    final SearchResponse response = clientResponse.getEntity(SearchResponse.class);
    List<NexusArtifact> data = response.getData();
    for (NexusArtifact nexusArtifact : data) {
        Artifact a = new Artifact(nexusArtifact.getArtifactId(), nexusArtifact.getVersion(), "");
        list.add(a);
    }

    return list;
}
 
Example 7
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private ClientResponse sendComplexMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  FormDataMultiPart formData = new FormDataMultiPart();
  formData.field("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.field("to", recipient);
  formData.field("subject", "Complex Mailgun Example");
  formData.field("html", "<html>HTML <strong>content</strong></html>");
  ClassLoader classLoader = getClass().getClassLoader();
  File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
  formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
  return webResource
      .type(MediaType.MULTIPART_FORM_DATA_TYPE)
      .post(ClientResponse.class, formData);
}
 
Example 8
Source File: ElasticSearchDBHandler.java    From Insights with Apache License 2.0 6 votes vote down vote up
public String search(String url) {
	ClientResponse response = null;
	String result = "";
	try {
		Client client = Client.create();
		client.setConnectTimeout(5001);
		WebResource resource = client.resource(url);
		response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
				.get(ClientResponse.class);
		result = response.getEntity(String.class);
	} catch (Exception e) {
		log.error("Exception while getting data of url " + url, e);
	} finally {
		if (response != null) {
			response.close();
		}
	}
	return result;
}
 
Example 9
Source File: YarnHttpClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void validateApiEndpoint() throws CloudbreakOrchestratorFailedException, 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 CloudbreakOrchestratorFailedException(msg);
    }
}
 
Example 10
Source File: TestRMHA.java    From hadoop 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 11
Source File: ServicesHealthStatus.java    From Insights with Apache License 2.0 6 votes vote down vote up
private JsonObject getClientResponse(String hostEndPoint, String apiUrl, String type,String version){
	try {
		Client client = Client.create();
		WebResource webResource = client
			   .resource(apiUrl);

			ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON.toString())
	                   .get(ClientResponse.class);

			if (response.getStatus() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
			}
			
			String successResponse = "" ;
			if( response.getStatus() == 200){
				successResponse = "Response successfully recieved from "+apiUrl;
			}
			return buildSuccessResponse(successResponse, hostEndPoint, type,version);

		  } catch (Exception e) {
			  log.error("Error while capturing health check at "+apiUrl,e);
		  }
	String failureResponse = "Error while capturing health check at "+apiUrl;
	return buildFailureResponse(failureResponse, hostEndPoint, type,version);
}
 
Example 12
Source File: NiFiRegistryClient.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 13
Source File: AtlasBaseClient.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
void initializeState(Configuration configuration, String[] baseUrls, UserGroupInformation ugi, String doAsUser) {
    this.configuration = configuration;
    Client client = getClient(configuration, ugi, doAsUser);

    if ((!AuthenticationUtil.isKerberosAuthenticationEnabled()) && basicAuthUser != null && basicAuthPassword != null) {
        final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(basicAuthUser, basicAuthPassword);
        client.addFilter(authFilter);
    }

    String activeServiceUrl = determineActiveServiceURL(baseUrls, client);
    atlasClientContext = new AtlasClientContext(baseUrls, client, ugi, doAsUser);
    service = client.resource(UriBuilder.fromUri(activeServiceUrl).build());
}
 
Example 14
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private ClientResponse sendSimpleMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  MultivaluedMapImpl formData = new MultivaluedMapImpl();
  formData.add("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.add("to", recipient);
  formData.add("subject", "Simple Mailgun Example");
  formData.add("text", "Plaintext content");
  return webResource
      .type(MediaType.APPLICATION_FORM_URLENCODED)
      .post(ClientResponse.class, formData);
}
 
Example 15
Source File: RestApiUtils.java    From db with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a POST request using the specified URL with the specified payload.
 *
 * @param url
 *            the URL to send the request to
 * @param authToken
 *            the authentication token to use for this request
 * @param requestPayload
 *            the payload to send with the request
 * @return the response from the request
 */
private TsResponse post(String url, String authToken, TsRequest requestPayload) {
    // Creates an instance of StringWriter to hold the XML for the request
    StringWriter writer = new StringWriter();

    // Marshals the TsRequest object into XML format if it is not null
    if (requestPayload != null) {
        try {
            s_jaxbMarshaller.marshal(requestPayload, writer);
        } catch (JAXBException ex) {
            m_logger.error("There was a problem marshalling the payload");
        }
    }

    // Converts the XML into a string
    String payload = writer.toString();

    m_logger.debug("Input payload: \n" + payload);

    // Creates the HTTP client object and makes the HTTP request to the
    // specified URL
    Client client = Client.create();
    WebResource webResource = client.resource(url);

    // Makes a POST request with the payload and credential
    ClientResponse clientResponse = webResource.header(TABLEAU_AUTH_HEADER, authToken)
            .type(MediaType.TEXT_XML_TYPE).post(ClientResponse.class, payload);

    // Parses the response from the server into an XML string
    String responseXML = clientResponse.getEntity(String.class);

    m_logger.debug("Response: \n" + responseXML);

    // Returns the unmarshalled XML response
    return unmarshalResponse(responseXML);
}
 
Example 16
Source File: ApiClient.java    From docusign-java-client with MIT License 5 votes vote down vote up
/**
 *
 * @param accessToken the bearer token to use to authenticate for this call.
 * @return OAuth UserInfo model
 * @throws ApiException if the HTTP call status is different than 2xx.
 * @see OAuth.UserInfo
 */
public OAuth.UserInfo getUserInfo(String accessToken) throws IllegalArgumentException, ApiException {
  try {
    if (accessToken == null || "".equals(accessToken)) {
      throw new IllegalArgumentException("Cannot find a valid access token. Make sure OAuth is configured before you try again.");
    }

    Client client = buildHttpClient(debugging);
    WebResource webResource = client.resource("https://" + getOAuthBasePath() + "/oauth/userinfo");
    ClientResponse response = webResource
        .header("Authorization", "Bearer " + accessToken)
        .header("Cache-Control", "no-store")
        .header("Pragma", "no-cache")
        .get(ClientResponse.class);
    if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
      String respBody = response.getEntity(String.class);
      throw new ApiException(
        response.getStatusInfo().getStatusCode(),
        "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'",
        response.getHeaders(),
        respBody);
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    OAuth.UserInfo userInfo = mapper.readValue(response.getEntityInputStream(), OAuth.UserInfo.class);

    // TODO "auto-assign base uri of the default account" is coming in next versions
    /*for (OAuth.UserInfo.Account account: userInfo.getAccounts()) {
        if ("true".equals(account.getIsDefault())) {
            setBasePath(account.getBaseUri() + "/restapi");
            Configuration.setDefaultApiClient(this);
            return userInfo;
        }
    }*/
    return userInfo;
  } catch (Exception e) {
    throw new ApiException("Error while fetching user info: " + e.getMessage());
  }
}
 
Example 17
Source File: SecureEmbeddedServerTestBase.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void setup() throws Exception {
    jksPath = new Path(Files.createTempDirectory("tempproviders").toString(), "test.jks");
    providerUrl = JavaKeyStoreProvider.SCHEME_NAME + "://file/" + jksPath.toUri();

    String baseUrl = String.format("https://localhost:%d/", securePort);

    DefaultClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    client.resource(UriBuilder.fromUri(baseUrl).build());

    service = client.resource(UriBuilder.fromUri(baseUrl).build());
}
 
Example 18
Source File: ClientProvider.java    From angulardemorestful with MIT License 4 votes vote down vote up
public WebResource getWebResource() {
    Client client = Client.create(new DefaultClientConfig());
    return client.resource(serverProvider.getBaseURI());
}
 
Example 19
Source File: RestApiUtils.java    From db with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Creates a multipart POST request using the specified URL with the specified payload.
 *
 * @param url
 *            the URL to send the request to
 * @param authToken
 *            the authentication token to use for this request
 * @param requestPayload
 *            the payload to send with the request
 * @param file
 *            the file to send with the request
 * @return the response from the request
 */
private TsResponse postMultipart(String url, String authToken, TsRequest requestPayload, BodyPart filePart) {
    // Creates an instance of StringWriter to hold the XML for the request
    StringWriter writer = new StringWriter();

    // Marshals the TsRequest object into XML format if it is not null
    if (requestPayload != null) {
        try {
            s_jaxbMarshaller.marshal(requestPayload, writer);
        } catch (JAXBException ex) {
            m_logger.error("There was a problem marshalling the payload");
        }
    }

    // Converts the XML into a string
    String payload = writer.toString();

    m_logger.debug("Input payload: \n" + payload);

    // Creates the XML request payload portion of the multipart request
    BodyPart payloadPart = new FormDataBodyPart(TABLEAU_PAYLOAD_NAME, payload);

    // Creates the multipart object and adds the file portion of the
    // multipart request to it
    MultiPart multipart = new MultiPart();
    multipart.bodyPart(payloadPart);

    if(filePart != null) {
        multipart.bodyPart(filePart);
    }

    // Creates the HTTP client object and makes the HTTP request to the
    // specified URL
    Client client = Client.create();
    WebResource webResource = client.resource(url);

    // Makes a multipart POST request with the multipart payload and
    // authenticity token
    ClientResponse clientResponse = webResource.header(TABLEAU_AUTH_HEADER, authToken)
            .type(MultiPartMediaTypes.createMixed()).post(ClientResponse.class, multipart);

    // Parses the response from the server into an XML string
    String responseXML = clientResponse.getEntity(String.class);

    m_logger.debug("Response: \n" + responseXML);

    // Returns the unmarshalled XML response
    return unmarshalResponse(responseXML);
}
 
Example 20
Source File: TestRMWebServicesAppsModification.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 120000)
public void testSingleAppKill() throws Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
      amNodeManager.nodeHeartbeat(true);

      AppState targetState =
          new AppState(YarnApplicationState.KILLED.toString());

      Object entity;
      if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        entity = appStateToJSON(targetState);
      } else {
        entity = targetState;
      }
      ClientResponse response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "state").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);

      if (!isAuthenticationEnabled()) {
        assertEquals(Status.UNAUTHORIZED, response.getClientResponseStatus());
        continue;
      }
      assertEquals(Status.ACCEPTED, response.getClientResponseStatus());
      if (mediaType.equals(MediaType.APPLICATION_JSON)) {
        verifyAppStateJson(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      } else {
        verifyAppStateXML(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      }

      String locationHeaderValue =
          response.getHeaders().getFirst(HttpHeaders.LOCATION);
      Client c = Client.create();
      WebResource tmp = c.resource(locationHeaderValue);
      if (isAuthenticationEnabled()) {
        tmp = tmp.queryParam("user.name", webserviceUserName);
      }
      response = tmp.get(ClientResponse.class);
      assertEquals(Status.OK, response.getClientResponseStatus());
      assertTrue(locationHeaderValue.endsWith("/ws/v1/cluster/apps/"
          + app.getApplicationId().toString() + "/state"));

      while (true) {
        Thread.sleep(100);
        response =
            this
              .constructWebResource("apps",
                app.getApplicationId().toString(), "state").accept(mediaType)
              .entity(entity, contentType).put(ClientResponse.class);
        assertTrue((response.getClientResponseStatus() == Status.ACCEPTED)
            || (response.getClientResponseStatus() == Status.OK));
        if (response.getClientResponseStatus() == Status.OK) {
          assertEquals(RMAppState.KILLED, app.getState());
          if (mediaType.equals(MediaType.APPLICATION_JSON)) {
            verifyAppStateJson(response, RMAppState.KILLED);
          } else {
            verifyAppStateXML(response, RMAppState.KILLED);
          }
          break;
        }
      }
    }
  }

  rm.stop();
}