下面列出了org.apache.http.auth.InvalidCredentialsException#com.sun.jersey.api.client.WebResource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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();
}
@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);
}
}
/**
* 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);
}
}
@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);
}
}
}
@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();
}
@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);
}
}
@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);
}
@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);
}
@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));
}
}
@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));
}
}
@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);
}
}
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
}
@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));
}
}
@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);
}
}
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;
}
@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));
}
}
/**
* @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());
}
}
@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());
}
}
@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);
}
@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);
}
/**
* 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);
}
/**
* 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");
}
}
@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));
}
}
@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));
}
}
@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());
}
@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));
}
}
@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 );
}
@Test
public void testPrimaryFilterNumericStringWithQuotes() {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("timeline")
.path("type_1").queryParam("primaryFilter", "other:\"123abc\"")
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
verifyEntities(response.getEntity(TimelineEntities.class));
}
private WebResource.Builder applyHeaders(WebResource.Builder builder,
MultivaluedMap<String, String> headers) {
for (String key : headers.keySet()) {
for (String value : headers.get(key)) {
builder = builder.header(key, value);
}
}
return builder;
}
@Test
public void testPrimaryFilterNumericString() {
// without quotes, 123abc is interpreted as the number 123,
// which finds no entities
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("timeline")
.path("type_1").queryParam("primaryFilter", "other:123abc")
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
assertEquals(0, response.getEntity(TimelineEntities.class).getEntities()
.size());
}