public static void main(String[] args) throws Exception { ClientResource resource = new ClientResource("http://localhost:8111/"); // Get a representation Representation rep = resource.get(); System.out.println(resource.getStatus()); // Get an updated representation, if modified resource.getConditions().setModifiedSince(rep.getModificationDate()); rep = resource.get(); System.out.println(resource.getStatus()); // Get an updated representation, if tag changed resource.getConditions().setModifiedSince(null); resource.getConditions().getNoneMatch().add(new Tag("xyz123")); rep = resource.get(); System.out.println(resource.getStatus()); // Put a new representation if tag has not changed resource.getConditions().getNoneMatch().clear(); resource.getConditions().getMatch().add(rep.getTag()); resource.put(rep); System.out.println(resource.getStatus()); // Put a new representation when a different tag resource.getConditions().getMatch().clear(); resource.getConditions().getMatch().add(new Tag("abcd7890")); resource.put(rep); System.out.println(resource.getStatus()); }
/** * Assert if the FileOrdered have been copied It gets the list of files from the order, and gets * the file described in the list of files * * @param order the order to assert * @param nbFileCopied the expected number of files to be copied */ private void assertFileOrderedExists(Order order, int nbFileCopied) { assertNotNull(order); assertNotNull(order.getResourceCollection()); assertEquals(1, order.getResourceCollection().size()); Representation result = null; try { String res = order.getResourceCollection().get(0); ClientResource cr = new ClientResource(res); ChallengeResponse chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(chal); result = cr.get(getMediaTest()); assertNotNull(result); assertTrue(cr.getStatus().isSuccess()); try { // get the list of files String text = result.getText(); String[] contents = text.split("\r\n"); assertNotNull(contents); assertEquals(nbFileCopied, contents.length); Reference content = new Reference(contents[0]); // asserts assertNotNull(content); assertNotSame("", content.toString()); // get the file corresponding to the first url, check that this file // exists cr = new ClientResource(content); chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(chal); result = cr.get(getMediaTest()); assertNotNull(result); assertTrue(cr.getStatus().isSuccess()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { RIAPUtils.exhaust(result); } } finally { RIAPUtils.exhaust(result); } }
@Test public void testGetProbabilities() throws ResourceException, IOException { final Reference reference = new Reference("http://localhost/clue/probability.json"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); System.out.println(resource.get().getText()); final ProbabilityReport report = resource.get(ProbabilityReport.class); System.out.println(report.getMostLikelyRoom().getCardProbability()); resource.release(); }
/** * Invoke GET * * @param uri String * @param params String * @param parameters Map<String, String> * @param uriTemplate String */ public void retrieveDocAPI( String uri, String params, Map<String, String> parameters, String uriTemplate, ChallengeResponse challengeResponse) { ClientResource cr = new ClientResource(uri); cr.setChallengeResponse(challengeResponse); System.out.println("URI: " + uriTemplate); Representation result = cr.get(docAPI.getMediaTest()); docAPI.appendSection("Format"); // url type // request ClientResource crLocal = new ClientResource(uri); docAPI.appendRequest(Method.GET, crLocal); // parameters docAPI.appendParameters(parameters); docAPI.appendSection("Example"); docAPI.appendRequest(Method.GET, cr); // response docAPI.appendResponse(result); RIAPUtils.exhaust(result); }
@Test public void testErrorSearchRdfWithoutSearchTerm() throws Exception { // prepare: final InferredOWLOntologyID testArtifact = this.loadTestArtifact( TestConstants.TEST_ARTIFACT_20130206, MediaType.APPLICATION_RDF_TURTLE); final ClientResource searchClientResource = new ClientResource(this.getUrl(PoddWebConstants.PATH_SEARCH)); // there is no need to authenticate or have a test artifact as the // search term is checked // for first try { // no search term! searchClientResource.addQueryParameter( PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, testArtifact.getOntologyIRI().toString()); searchClientResource.addQueryParameter( PoddWebConstants.KEY_SEARCH_TYPES, "http://purl.org/podd/ns/poddScience#Platform"); searchClientResource.get(MediaType.APPLICATION_RDF_XML); Assert.fail("Should have thrown a ResourceException"); } catch (final ResourceException e) { Assert.assertEquals(Status.CLIENT_ERROR_BAD_REQUEST, e.getStatus()); } finally { this.releaseClient(searchClientResource); } }
/** Test getting a task variable. GET runtime/tasks/{taskId}/variables/{variableName}/data */ public void testGetTaskVariableDataSerializable() throws Exception { try { TestSerializableVariable originalSerializable = new TestSerializableVariable(); originalSerializable.setSomeField("This is some field"); // Test variable behaviour on standalone tasks Task task = taskService.newTask(); taskService.saveTask(task); taskService.setVariableLocal(task.getId(), "localTaskVariable", originalSerializable); ClientResource client = getAuthenticatedClient( RestUrls.createRelativeResourceUrl( RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "localTaskVariable")); client.get(); assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus()); // Read the serializable from the stream ObjectInputStream stream = new ObjectInputStream(client.getResponse().getEntity().getStream()); Object readSerializable = stream.readObject(); assertNotNull(readSerializable); assertTrue(readSerializable instanceof TestSerializableVariable); assertEquals( "This is some field", ((TestSerializableVariable) readSerializable).getSomeField()); assertEquals(MediaType.APPLICATION_JAVA_OBJECT.getName(), getMediaType(client)); } finally { // Clean adhoc-tasks even if test fails List<Task> tasks = taskService.createTaskQuery().list(); for (Task task : tasks) { taskService.deleteTask(task.getId(), true); } } }
@Override public Representation put(Representation entity) throws ResourceException { this.userId = UmlgURLDecoder.decode((String) getRequestAttributes().get("userId")); User c = UMLG.get().getEntity(this.userId); try { String entityText = entity.getText(); c.fromJson(entityText); String lookupUri = UmlgURLDecoder.decode(getReference().getQueryAsForm(false).getFirstValue("lookupUri")); lookupUri = "riap://host" + lookupUri; int fakeIdIndex = lookupUri.indexOf("fake"); if (fakeIdIndex != -1) { int indexOfForwardSlash = lookupUri.indexOf("/", fakeIdIndex); String fakeId = lookupUri.substring(fakeIdIndex, indexOfForwardSlash); Object id = UmlgTmpIdManager.INSTANCE.get(fakeId); lookupUri = lookupUri.replace(fakeId, UmlgURLDecoder.encode(id.toString())); } ClientResource cr = new ClientResource(lookupUri); Representation result = cr.get(); return result; } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } finally { UmlgTmpIdManager.INSTANCE.remove(); UMLG.get().rollback(); } }
/** Test getting a task variable. GET runtime/tasks/{taskId}/variables/{variableName}/data */ public void testGetTaskVariableData() throws Exception { try { // Test variable behaviour on standalone tasks Task task = taskService.newTask(); taskService.saveTask(task); taskService.setVariableLocal( task.getId(), "localTaskVariable", "This is a binary piece of text".getBytes()); // Force content-type to TEXT_PLAIN to make sure this is ignored and application-octect-stream // is always returned ClientResource client = getAuthenticatedClient( RestUrls.createRelativeResourceUrl( RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "localTaskVariable")); client.get(MediaType.TEXT_PLAIN); assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus()); String actualResponseBytesAsText = client.getResponse().getEntityAsText(); assertEquals("This is a binary piece of text", actualResponseBytesAsText); assertEquals(MediaType.APPLICATION_OCTET_STREAM.getName(), getMediaType(client)); } finally { // Clean adhoc-tasks even if test fails List<Task> tasks = taskService.createTaskQuery().list(); for (Task task : tasks) { taskService.deleteTask(task.getId(), true); } } }
@Test public void shouldGetWithSSL() throws ResourceException { // Given setSslConfiguration(); final String uri = "URI"; final Map<String, String> queryParameters = new HashMap<String, String>(); final Map<String, String> headers = new HashMap<String, String>(); final Context context = mock(Context.class); final ConcurrentHashMap<String, Object> requestAttributes = new ConcurrentHashMap<String, Object>(); final JSONObject restResponse = mock(JSONObject.class); given(resource.getContext()).willReturn(context); given(context.getAttributes()).willReturn(requestAttributes); given(resource.get(JSONObject.class)).willReturn(restResponse); given(restResponse.toString()).willReturn("{}"); // When final JsonValue response = restClient.get(uri, queryParameters, headers); // Then verify(resource, never()).addQueryParameter(anyString(), anyString()); verify(requestHeaders, never()).set(anyString(), anyString()); verify(resource).getContext(); assertTrue(requestAttributes.containsKey("sslContextFactory")); assertEquals(response.size(), 0); }
/** * Tests that we can GET a value from the system and verify that it is within acceptable range. * * @throws Exception if GET fails */ @Test public void testGet() throws Exception { PhotovoltaicsData.modifySystemState(); // Set up the GET client // String getUrl = "http://localhost:7001/photovoltaic/state"; String getUrl = "http://localhost:7001/cgi-bin/egauge?tot"; ClientResource getClient = new ClientResource(getUrl); // Get the XML representation. DomRepresentation domRep = new DomRepresentation(getClient.get()); Document domDoc = domRep.getDocument(); // Grabs tags from XML. NodeList meterList = domDoc.getElementsByTagName("meter"); NodeList energyList = domDoc.getElementsByTagName("energy"); NodeList powerList = domDoc.getElementsByTagName("power"); // Grabs attributes from tags. String title = ((Element) meterList.item(1)).getAttribute("title"); // Grabs value from tags. String energy = ((Element) energyList.item(1)).getTextContent(); String power = ((Element) powerList.item(1)).getTextContent(); // Check that we are returning the correct title. assertEquals("Checking that title is \"Solar\"", title, "Solar"); // Check that the returned value is within a delta of our value. assertEquals(1500, Double.parseDouble(energy), 1750); assertEquals(700, Double.parseDouble(power), 700); }
public void testRepresentationTemplate() throws Exception { // Create a temporary directory for the tests File testDir = new File(System.getProperty("java.io.tmpdir"), "VelocityTestCase"); testDir.mkdir(); // Create a temporary template file File testFile = File.createTempFile("test", ".vm", testDir); FileWriter fw = new FileWriter(testFile); fw.write("Value=$value"); fw.close(); Map<String, Object> map = new TreeMap<String, Object>(); map.put("value", "myValue"); // Representation approach Reference ref = LocalReference.createFileReference(testFile); ClientResource r = new ClientResource(ref); Representation templateFile = r.get(); TemplateRepresentation tr = new TemplateRepresentation(templateFile, map, MediaType.TEXT_PLAIN); final String result = tr.getText(); assertEquals("Value=myValue", result); // Clean-up BioUtils.delete(testFile); BioUtils.delete(testDir, true); }
@Test public void testErrorSearchRdfWithoutAuthentication() throws Exception { // prepare: final InferredOWLOntologyID testArtifact = this.loadTestArtifact( TestConstants.TEST_ARTIFACT_20130206, MediaType.APPLICATION_RDF_TURTLE); final ClientResource searchClientResource = new ClientResource(this.getUrl(PoddWebConstants.PATH_SEARCH)); // request without authentication try { searchClientResource.addQueryParameter(PoddWebConstants.KEY_SEARCHTERM, "Scan"); searchClientResource.addQueryParameter( PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, testArtifact.getOntologyIRI().toString()); searchClientResource.addQueryParameter( PoddWebConstants.KEY_SEARCH_TYPES, "http://purl.org/podd/ns/poddScience#Platform"); searchClientResource.get(MediaType.APPLICATION_RDF_XML); Assert.fail("Should have thrown a ResourceException"); } catch (final ResourceException e) { Assert.assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, e.getStatus()); } finally { this.releaseClient(searchClientResource); } }
/** Test getting a task variable. GET runtime/tasks/{taskId}/variables/{variableName}/data */ public void testGetTaskVariableDataForIllegalVariables() throws Exception { try { // Test variable behaviour on standalone tasks Task task = taskService.newTask(); taskService.saveTask(task); taskService.setVariableLocal( task.getId(), "localTaskVariable", "this is a plain string variable"); // Try getting data for non-binary variable ClientResource client = getAuthenticatedClient( RestUrls.createRelativeResourceUrl( RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "localTaskVariable")); try { client.get(); fail("Exception expected"); } catch (ResourceException expected) { assertEquals(Status.CLIENT_ERROR_NOT_FOUND, expected.getStatus()); assertEquals( "The variable does not have a binary data stream.", expected.getStatus().getDescription()); } // Try getting data for unexisting property client = getAuthenticatedClient( RestUrls.createRelativeResourceUrl( RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "unexistingVariable")); try { client.get(); fail("Exception expected"); } catch (ResourceException expected) { assertEquals(Status.CLIENT_ERROR_NOT_FOUND, expected.getStatus()); assertEquals( "Task '" + task.getId() + "' doesn't have a variable with name: 'unexistingVariable'.", expected.getStatus().getDescription()); } } finally { // Clean adhoc-tasks even if test fails List<Task> tasks = taskService.createTaskQuery().list(); for (Task task : tasks) { taskService.deleteTask(task.getId(), true); } } }
public void testGetUsers() throws Exception { ClientResource client = getAuthenticatedClient("users?searchText=erm"); Representation response = client.get(); JsonNode responseNode = objectMapper.readTree(response.getStream()); assertNotNull(responseNode); assertEquals(1, responseNode.get("total").asInt()); JsonNode userNode = responseNode.get("data").get(0); assertEquals("Kermit", userNode.get("firstName").asText()); }
public void testGetAllUsers() throws Exception { ClientResource client = getAuthenticatedClient("users"); try { client.get(); fail(); } catch (Exception e) { // not allowed, should provide search text } }
public void doGet(String path) { ClientResource cr = new ClientResource(testContext, BASE_URI + path); try { cr.get(); } catch (ResourceException e) { e.printStackTrace(); Assert.fail(); } }
private int getRemainingCount() { final Reference reference = new Reference("http://localhost/clue/game.json"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); final ClueServerStatus response = resource.get(ClueServerStatus.class); resource.release(); return response.getRemainingTriples().size(); }
public FacebookPhoto getPhotos() { ClientResource cr = null; FacebookPhoto photos = null; try { cr = new ClientResource(uriPhoto + "&access_token=" + access_token); photos = cr.get(FacebookPhoto.class); } catch (ResourceException re) { System.err.println("Error when retrieving photos: " + cr.getResponse().getStatus()); System.err.println(uri + "?access_token" + access_token); } return photos; }
public void doPut(String path, String fileToPut) { ClientResource cr = new ClientResource(testContext, BASE_URI + path); LocalReference ref = new LocalReference(fileToPut); ref.setProtocol(Protocol.CLAP); ClientResource local = new ClientResource(ref); Representation rep = local.get(); if (fileToPut.endsWith(".csv")) rep.setMediaType(MediaType.TEXT_CSV); try { cr.put(rep); } catch (ResourceException e) { e.printStackTrace(); Assert.fail(); } }
@Test public void testServerGetStatus() throws Exception { final Reference reference = new Reference("http://localhost/clue/game.xml"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); final ClueServerStatus response = resource.get(ClueServerStatus.class); resource.release(); assertNotNull(response); }
@Test public void testGetCompute() { Compute compute = null; try { compute = new Compute(Architecture.x64, 2, "TestCase", 200, 20, State.active, null); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } // test if compute ist not null Assert.assertNotNull(compute); // connect to api clientResource.setReference( OcciConfig.getInstance().config.getString("occi.server.location") + "compute/" + compute.getId()); clientResource.setHostRef( OcciConfig.getInstance().config.getString("occi.server.location") + "compute/" + compute.getId()); // create new representation Representation representation = null; try { // send post request representation = clientResource.get(); } catch (Exception ex) { System.out.println("Failed to execute GET request: " + ex.getMessage()); } Assert.assertNotNull(representation); // get request and print it in debugger Request request = Request.getCurrent(); System.out.println(request.toString() + "\n\n"); System.out.println("--------------------------------"); // get current response Response response = Response.getCurrent(); Assert.assertNotNull(response); System.out.println("Response: " + response.toString()); try { representation.write(System.out); } catch (IOException e) { System.out.println(e.getMessage()); } System.out.println("\n--------------------------------"); }
@Test public void testRemainingTriples() { final Reference reference = new Reference("http://localhost/clue/triples/remaining.json"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); final TripleList response = resource.get(TripleList.class); resource.release(); assertNotNull(response); assertEquals(324, response.size()); }
/** Assert if there are no Orders */ protected void assertNoneOrder() { ClientResource cr = new ClientResource(getOrderUrl()); ChallengeResponse chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(chal); Representation result = cr.get(getMediaTest()); assertNotNull(result); assertTrue(cr.getStatus().isSuccess()); Response response = getResponseOrderandUserstorage(getMediaTest(), result, Order.class, true); assertTrue(response.getSuccess()); assertEquals(0, response.getTotal().intValue()); }
/** * Get the Order at the given url * * @param url the url where to find the Order * @return the Order found */ protected Order getOrder(String url) { ClientResource cr = new ClientResource(url); ChallengeResponse chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(chal); Representation result = cr.get(getMediaTest()); assertNotNull(result); assertTrue(cr.getStatus().isSuccess()); Response response = getResponseOrderandUserstorage(getMediaTest(), result, Order.class); assertTrue(response.getSuccess()); result.release(); return (Order) response.getItem(); }
public void doDelete(String path) { ClientResource cr = new ClientResource(testContext, BASE_URI + path); try { cr.delete(); } catch (ResourceException e) { e.printStackTrace(); Assert.fail(); } try { cr.get(); Assert.fail("resource still exists after delete"); } catch (ResourceException e) { } }
public static void main(String[] args) { try { // Create the client resource ClientResource resource = new ClientResource("http://www.restlet.org"); // Customize the referrer property resource.setReferrerRef("http://www.mysite.org"); // Write the response entity on the console Representation tmp = resource.get(MediaType.TEXT_HTML); System.out.println(tmp.getMediaType()); tmp.write(System.out); } catch (Exception e) { e.printStackTrace(); } }
/** * Performs a test by sending HTTP Gets to the URL, and records the number of bytes returned. Each * test results are documented and displayed in standard out with the following information: * * <p>URL - The source URL of the test REQ CNT - How many times this test has run START - The * start time of the last test run STOP - The stop time of the last test run THREAD - The thread * id handling this test case RESULT - The result of the test. Either the number of bytes returned * or an error message. */ private void doTest() { String result = ""; this.reqCount++; // Connect and run test steps Date startTime = new Date(); try { ClientResource client = new ClientResource(this.myURL); // place order JSONObject json = new JSONObject(); json.put("payment", "quarter"); json.put("action", "place-order"); client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON); // Get Gumball Count Representation result_string = client.get(); JSONObject json_count = new JSONObject(result_string.getText()); result = Integer.toString((int) json_count.get("count")); } catch (Exception e) { result = e.toString(); } finally { Date stopTime = new Date(); // Print Report of Result: System.out.println( "======================================\n" + "URL => " + this.myURL + "\n" + "REQ CNT => " + this.reqCount + "\n" + "START => " + startTime + "\n" + "STOP => " + stopTime + "\n" + "THREAD => " + Thread.currentThread().getName() + "\n" + "RESULT => " + result + "\n"); } }
/** * The constructor is {@code private} to have strict control what instances exist at any time. * Instead of the constructor the {@code public} <i>static factory method</i> {@link * #getInstance(JavaClient)} returns the instances of the class. * * @param javaClient The corresponding {@code JavaClient} */ private CoreServiceImpl(JavaClient javaClient) { super(CoreServiceID.INSTANCE, javaClient.getAPIBaseURL(), javaClient); this.javaClient = javaClient; restletClient = ((JavaClientImpl) javaClient).getRestletClient(); ClientResource clientResource = new ClientResource(serviceURL.toExternalForm()); clientResource.setNext(restletClient); CoreServiceInstanceDataResource coreServiceInstanceDataResource = clientResource.get(CoreServiceInstanceDataResource.class); System.out.println("[CoreService CoreServiceImpl] " + serviceURL.toExternalForm()); maxEntityRequestSize = coreServiceInstanceDataResource.getParameters().getBatchLimit(); paginationSize = coreServiceInstanceDataResource.getParameters().getPaginationSize(); }
public static void main(String[] args) throws ResourceException, IOException { if (args.length != 1) { System.err.println("Please specify name of file that includes the request."); } else { Properties properties = new Properties(); properties.load(new FileInputStream(args[0])); ClientResource comparisonsResource = new ClientResource(properties.getProperty("endpoint")); try { comparisonsResource.get().write(System.out); System.out.println("\n"); } catch (ResourceException e) { System.out.println(e); } try { // first comparison String firstComparisonId = UUID.randomUUID().toString(); Comparison comparison = new Comparison( firstComparisonId, properties.getProperty("dataset1"), properties.getProperty("dataset2"), properties.getProperty("adapter"), properties.getProperty("extractor"), properties.getProperty("measure")); Representation post = comparisonsResource.post(getComparisonRepresentation(comparison)); post.write(System.out); System.out.println("\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ResourceException e) { logger.log(Level.SEVERE, "Error connecting to server", e); } } }
public static void main(String[] args) throws Exception { String uri = "http://*****:*****@aaa.com"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); emailList.add("*****@*****.**"); account.setEmailList(emailList); String json = JSON.intoText(account); log.debug("account : {}", account); Representation entity = new StringRepresentation(json); entity.setMediaType(MediaType.APPLICATION_JSON); client.put(entity); // entity = client.get(MediaType.APPLICATION_JSON); json = entity.getText(); account = JSON.fromText(json, Account.class); log.debug("account : {}", account); }