com.sun.jersey.api.client.WebResource Java Examples

The following examples show how to use com.sun.jersey.api.client.WebResource. 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: NeoGraphDatabase.java    From navex with GNU General Public License v3.0 6 votes vote down vote up
private static URI createNode()
{
	// START SNIPPET: createNode
	final String nodeEntryPointUri = SERVER_ROOT_URI + "node";
	// http://localhost:7474/db/data/node

	WebResource resource = Client.create()
			.resource( nodeEntryPointUri );
	// POST {} to the node entry point URI
	ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
			.type( MediaType.APPLICATION_JSON )
			.entity( "{}" )
			.post( ClientResponse.class );

	final URI location = response.getLocation();
	System.out.println( String.format(
			"POST to [%s], status code [%d], location header [%s]",
			nodeEntryPointUri, response.getStatus(), location.toString() ) );
	response.close();

	return location;
	// END SNIPPET: createNode
}
 
Example #2
Source File: TestRMWebServicesApps.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppsQueryStatesNone() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  rm.submitApp(CONTAINER_MB);
  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps")
      .queryParam("states", YarnApplicationState.RUNNING.toString())
      .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());
  assertEquals("apps is not null", JSONObject.NULL, json.get("apps"));
  rm.stop();
}
 
Example #3
Source File: TestHsWebServicesAttempts.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testTaskAttemptsSlash() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    for (Task task : jobsMap.get(id).getTasks().values()) {

      String tid = MRApps.toString(task.getID());
      ClientResponse response = r.path("ws").path("v1").path("history")
          .path("mapreduce").path("jobs").path(jobId).path("tasks").path(tid)
          .path("attempts/").accept(MediaType.APPLICATION_JSON)
          .get(ClientResponse.class);
      assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
      JSONObject json = response.getEntity(JSONObject.class);
      verifyHsTaskAttempts(json, task);
    }
  }
}
 
Example #4
Source File: EagleServiceClientImpl.java    From Eagle with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public GenericServiceAPIResponseEntity<String> delete(EagleServiceSingleEntityQueryRequest request) throws IOException,EagleServiceClientException {
    String queryString = request.getQueryParameterString();
    StringBuilder sb = new StringBuilder();
    sb.append(GENERIC_ENTITY_PATH);
    sb.append("?");
    sb.append(queryString);
    final String urlString =  sb.toString();

    if(!this.silence) LOG.info("Going to delete by querying service: " + getWholePath(urlString));
    WebResource r = getWebResource(urlString);
    return putAuthHeaderIfNeeded(r.accept(DEFAULT_MEDIA_TYPE)
                                  .header(CONTENT_TYPE, DEFAULT_HTTP_HEADER_CONTENT_TYPE))
                                  .delete(GenericServiceAPIResponseEntity.class);
}
 
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: AtlasClient.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Get an entity given the entity id
 * @param entityType entity type name
 * @param attribute qualified name of the entity
 * @param value
 * @return result object
 * @throws AtlasServiceException
 */
public Referenceable getEntity(final String entityType, final String attribute, final String value)
        throws AtlasServiceException {
    JSONObject jsonResponse = callAPIWithRetries(API.GET_ENTITY, null, new ResourceCreator() {
        @Override
        public WebResource createResource() {
            WebResource resource = getResource(API.GET_ENTITY);
            resource = resource.queryParam(TYPE, entityType);
            resource = resource.queryParam(ATTRIBUTE_NAME, attribute);
            resource = resource.queryParam(ATTRIBUTE_VALUE, value);
            return resource;
        }
    });
    try {
        String entityInstanceDefinition = jsonResponse.getString(AtlasClient.DEFINITION);
        return InstanceSerialization.fromJsonReferenceable(entityInstanceDefinition, true);
    } catch (JSONException e) {
        throw new AtlasServiceException(API.GET_ENTITY, e);
    }
}
 
Example #7
Source File: TestHsWebServicesTasks.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testTasks() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("tasks")
        .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 tasks = json.getJSONObject("tasks");
    JSONArray arr = tasks.getJSONArray("task");
    assertEquals("incorrect number of elements", 2, arr.length());

    verifyHsTask(arr, jobsMap.get(id), null);
  }
}
 
Example #8
Source File: TestAHSWebServices.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleAttempts() throws Exception {
  ApplicationId appId = ApplicationId.newInstance(0, 1);
  WebResource r = resource();
  ClientResponse response =
      r.path("ws").path("v1").path("applicationhistory").path("apps")
        .path(appId.toString()).path("appattempts")
        .queryParam("user.name", USERS[round])
        .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  if (round == 1) {
    assertEquals(
        Status.FORBIDDEN, response.getClientResponseStatus());
    return;
  }
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject json = response.getEntity(JSONObject.class);
  assertEquals("incorrect number of elements", 1, json.length());
  JSONObject appAttempts = json.getJSONObject("appAttempts");
  assertEquals("incorrect number of elements", 1, appAttempts.length());
  JSONArray array = appAttempts.getJSONArray("appAttempt");
  assertEquals("incorrect number of elements", 5, array.length());
}
 
Example #9
Source File: TestHsWebServicesJobs.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobIdDefault() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).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 info = json.getJSONObject("job");
    VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id));
  }

}
 
Example #10
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 #11
Source File: TestRMWebServicesApps.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppsQueryFinalStatus() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  RMApp app1 = rm.submitApp(CONTAINER_MB);
  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();

  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps").queryParam("finalStatus", FinalApplicationStatus.UNDEFINED.toString())
      .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());
  System.out.println(json.toString());
  JSONObject apps = json.getJSONObject("apps");
  assertEquals("incorrect number of elements", 1, apps.length());
  JSONArray array = apps.getJSONArray("app");
  assertEquals("incorrect number of elements", 1, array.length());
  verifyAppInfo(array.getJSONObject(0), app1);
  rm.stop();
}
 
Example #12
Source File: RunManagerImpl.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public void store( final Project project, final Summary summary, final File resultsFile,
                   final Class<?> testClass ) throws FileNotFoundException, MalformedURLException {
    Preconditions.checkNotNull( summary, "The summary argument cannot be null." );

    // upload the results file
    InputStream in = new FileInputStream( resultsFile );
    FormDataMultiPart part = new FormDataMultiPart();
    part.field( FILENAME, resultsFile.getName() );

    FormDataBodyPart body = new FormDataBodyPart( CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
    part.bodyPart( body );

    WebResource resource = Client.create().resource( coordinatorFig.getEndpoint() );
    resource = addQueryParameters( resource, project, me );
    String result = resource.path( coordinatorFig.getStoreResultsPath() )
                     .queryParam( RUN_ID, summary.getRunId() )
                     .queryParam( RUN_NUMBER, "" + summary.getRunNumber() )
                     .type( MediaType.MULTIPART_FORM_DATA_TYPE )
                     .post( String.class, part );

    LOG.debug( "Got back result from results file store = {}", result );
}
 
Example #13
Source File: TestAHSWebServices.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidAccept() throws JSONException, Exception {
  WebResource r = resource();
  String responseStr = "";
  try {
    responseStr =
        r.path("ws").path("v1").path("applicationhistory")
          .queryParam("user.name", USERS[round])
          .accept(MediaType.TEXT_PLAIN).get(String.class);
    fail("should have thrown exception on invalid uri");
  } catch (UniformInterfaceException ue) {
    ClientResponse response = ue.getResponse();
    assertEquals(Status.INTERNAL_SERVER_ERROR,
      response.getClientResponseStatus());
    WebServicesTestUtils.checkStringMatch(
      "error string exists and shouldn't", "", responseStr);
  }
}
 
Example #14
Source File: TestAMWebServicesJobConf.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobConfDefault() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).path("conf").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 info = json.getJSONObject("conf");
    verifyAMJobConf(info, jobsMap.get(id));
  }
}
 
Example #15
Source File: TestHsWebServicesJobsQuery.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryLimitInvalid() throws JSONException, Exception {
  WebResource r = resource();

  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs").queryParam("limit", "-1")
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

  assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject msg = response.getEntity(JSONObject.class);
  JSONObject exception = msg.getJSONObject("RemoteException");
  assertEquals("incorrect number of elements", 3, exception.length());
  String message = exception.getString("message");
  String type = exception.getString("exception");
  String classname = exception.getString("javaClassName");
  WebServicesTestUtils.checkStringMatch("exception message",
      "java.lang.Exception: limit value must be greater then 0", message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example #16
Source File: TestHsWebServicesJobsQuery.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobsQueryFinishTimeBeginNegative() throws JSONException,
    Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("finishedTimeBegin", String.valueOf(-1000))
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject msg = response.getEntity(JSONObject.class);
  JSONObject exception = msg.getJSONObject("RemoteException");
  assertEquals("incorrect number of elements", 3, exception.length());
  String message = exception.getString("message");
  String type = exception.getString("exception");
  String classname = exception.getString("javaClassName");
  WebServicesTestUtils.checkStringMatch("exception message",
      "java.lang.Exception: finishedTimeBegin must be greater than 0",
      message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example #17
Source File: TestHsWebServicesJobs.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobCountersDefault() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("counters/")
        .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 info = json.getJSONObject("jobCounters");
    verifyHsJobCounters(info, appContext.getJob(id));
  }
}
 
Example #18
Source File: TestHsWebServicesJobs.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobId() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId)
        .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 info = json.getJSONObject("job");
    VerifyJobsUtils.verifyHsJob(info, appContext.getJob(id));
  }

}
 
Example #19
Source File: ImplicitGrantTest.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Test
public void testAccessToken()
{
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	ResourceClient client = new ResourceClient(clientEntity.getClientId(), GrantType.AUTHORIZATION_REQUEST, ResponseType.TOKEN);
	String authUrl = client.getAuthUrl(null);
	
	WebResource webResource = restClient.resource(authUrl);
	ClientResponse clientResponse = webResource.get(ClientResponse.class);
	assertEquals(302, clientResponse.getStatus());
	String fragment = clientResponse.getLocation().getFragment();
	assertNotNull(fragment);
}
 
Example #20
Source File: TestHsWebServicesJobConf.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobConfDefault() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history").path("mapreduce")
        .path("jobs").path(jobId).path("conf").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 info = json.getJSONObject("conf");
    verifyHsJobConf(info, jobsMap.get(id));
  }
}
 
Example #21
Source File: TestHsWebServicesTasks.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testTasksQueryReduce() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    String type = "r";
    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("tasks")
        .queryParam("type", type).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 tasks = json.getJSONObject("tasks");
    JSONArray arr = tasks.getJSONArray("task");
    assertEquals("incorrect number of elements", 1, arr.length());
    verifyHsTask(arr, jobsMap.get(id), type);
  }
}
 
Example #22
Source File: TestAMWebServicesJobs.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobCountersXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).path("counters")
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList info = dom.getElementsByTagName("jobCounters");
    verifyAMJobCountersXML(info, jobsMap.get(id));
  }
}
 
Example #23
Source File: RestApiUtils.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Invokes an HTTP request to sign out of the Server.
 *
 * @param credential
 *            the credential containing the authentication token to use for
 *            this request
 */
public void invokeSignOut(TableauCredentialsType credential) {

    m_logger.info("Signing out of Tableau Server");

    String url = Operation.SIGN_OUT.getUrl();

    // 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, credential.getToken()).post(
            ClientResponse.class);

    if (clientResponse.getStatus() == Status.NO_CONTENT.getStatusCode()) {
        m_logger.info("Successfully signed out of Tableau Server");
    } else {
        m_logger.error("Failed to sign out of Tableau Server");
    }
}
 
Example #24
Source File: TestHsWebServicesJobs.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobAttempts() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("jobattempts")
        .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 info = json.getJSONObject("jobAttempts");
    verifyHsJobAttempts(info, appContext.getJob(id));
  }
}
 
Example #25
Source File: TestRMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidAccept() throws JSONException, Exception {
  WebResource r = resource();
  String responseStr = "";
  try {
    responseStr = r.path("ws").path("v1").path("cluster")
        .accept(MediaType.TEXT_PLAIN).get(String.class);
    fail("should have thrown exception on invalid uri");
  } catch (UniformInterfaceException ue) {
    ClientResponse response = ue.getResponse();
    assertEquals(Status.INTERNAL_SERVER_ERROR,
        response.getClientResponseStatus());
    WebServicesTestUtils.checkStringMatch(
        "error string exists and shouldn't", "", responseStr);
  }
}
 
Example #26
Source File: NiFiTestUser.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a PUT using the specified url and entity body.
 *
 * @param url url
 * @param entity entity
 * @param headers http headers
 * @return response
 * @throws java.lang.Exception ex
 */
public ClientResponse testPutWithHeaders(String url, Object entity, Map<String, String> headers) throws Exception {
    // get the resource
    WebResource.Builder resourceBuilder = addProxiedEntities(client.resource(url).type(MediaType.APPLICATION_JSON));

    // include the request entity
    if (entity != null) {
        resourceBuilder = resourceBuilder.entity(entity);
    }

    // append any headers
    if (headers != null && !headers.isEmpty()) {
        for (String key : headers.keySet()) {
            resourceBuilder = resourceBuilder.header(key, headers.get(key));
        }
    }

    // perform the request
    return resourceBuilder.put(ClientResponse.class);
}
 
Example #27
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 #28
Source File: JCRSolutionFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void setData( final FileName file, final byte[] data ) throws FileSystemException {
  final String[] fileName = computeFileNames( file );
  final StringBuilder b = new StringBuilder();
  for ( int i = 0; i < fileName.length; i++ ) {
    if ( i != 0 ) {
      b.append( SLASH );
    }
    b.append( fileName[ i ] );
  }

  String service = MessageFormat.format( UPLOAD_SERVICE,
    URLEncoder.encodeUTF8( normalizePath( b.toString() ).replaceAll( "\\!", "%21" ).replaceAll( "\\+", "%2B" ) ) );
  final WebResource resource = client.resource( url + service );
  final ByteArrayInputStream stream = new ByteArrayInputStream( data );
  final ClientResponse response = resource.put( ClientResponse.class, stream );
  final int status = response.getStatus();

  if ( status != HttpStatus.SC_OK ) {
    if ( status == HttpStatus.SC_MOVED_TEMPORARILY
      || status == HttpStatus.SC_FORBIDDEN
      || status == HttpStatus.SC_UNAUTHORIZED ) {
      throw new FileSystemException( "ERROR_INVALID_USERNAME_OR_PASSWORD" );
    } else {
      throw new FileSystemException( "ERROR_FAILED", status );
    }
  }

  try {
    // Perhaps a New file was created. Refresh local tree model.
    this.refresh();
  } catch ( IOException e ) {
    // Ignore if unable to refresh
  }
}
 
Example #29
Source File: PublicRestApiTest.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
@Test
public void createPolicyTest() throws Exception{
	WebResource webResource = resource();
	String policyStr = getPolicyContent();
	ClientResponse response = webResource.path("/apps/" + TESTAPPID + "/policy").type(MediaType.APPLICATION_JSON).put(ClientResponse.class,policyStr);
       assertEquals(response.getStatus(), STATUS200);
}
 
Example #30
Source File: AtlasClientTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
private WebResource.Builder getBuilder(WebResource resourceObject) {
    when(resourceObject.getRequestBuilder()).thenReturn(resourceBuilderMock);
    when(resourceObject.path(anyString())).thenReturn(resourceObject);
    when(resourceBuilderMock.accept(AtlasBaseClient.JSON_MEDIA_TYPE)).thenReturn(resourceBuilderMock);
    when(resourceBuilderMock.accept(MediaType.APPLICATION_JSON)).thenReturn(resourceBuilderMock);
    when(resourceBuilderMock.type(AtlasBaseClient.JSON_MEDIA_TYPE)).thenReturn(resourceBuilderMock);
    when(resourceBuilderMock.type(MediaType.MULTIPART_FORM_DATA)).thenReturn(resourceBuilderMock);
    return resourceBuilderMock;
}