/** 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); } } }
@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); } }
/** * 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); } }
public GetStreamKeyStreamServer getGetStreamKeyStreamServer( String songID, GetCountry country, String sesionID) { GetStreamKeyStreamServer res = null; String post = "{\"method\":\"getStreamKeyStreamServer\",\"header\":{\"wsKey\":\"" + KEY + "\",\"sessionID\":\"" + sesionID + "\"},\"parameters\":{\"songID\":\"" + songID + "\",\"country\":" + country.getResult() + ",\"lowBitrate\":\"\"}}"; ClientResource cr = new ClientResource(uri + getSignatures(post)); try { res = gson.fromJson(cr.post(post).getText(), GetStreamKeyStreamServer.class); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; }
protected ClientResource getAuthenticatedClient(String uri) { ClientResource client = new ClientResource(getBaseURI() + uri); client.getCookies().add("ES_DMS_TICKET", adminToken); // client.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "kermit", // "kermit"); return client; }
/** 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); } } }
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 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); }
@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(); } }
/** * 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); }
/** * Invoke PUT * * @param uri String * @param params String * @param object Representation * @param parameters Map<String, String> * @param uriTemplate String */ public void putDocAPI( String uri, String params, Representation object, Map<String, String> parameters, String uriTemplate) { ClientResource cr = new ClientResource(uri); System.out.println("URI: " + uriTemplate); docAPI.appendSection("Format"); // url type // request ClientResource crLocal = new ClientResource(uriTemplate); docAPI.appendRequest(Method.PUT, crLocal); // parameters docAPI.appendParameters(parameters); docAPI.appendSection("Example"); docAPI.appendRequest(Method.PUT, cr, object); // response Representation result = cr.put(object, docAPI.getMediaTest()); docAPI.appendResponse(result); RIAPUtils.exhaust(result); }
public static void main(String[] args) throws Exception { // Create and configure HTTPS client Client client = new Client(new Context(), Protocol.HTTPS); Series<Parameter> parameters = client.getContext().getParameters(); parameters.add("truststorePath", "certs/client-truststore.jks"); parameters.add("truststorePassword", "password"); parameters.add("truststoreType", "JKS"); // Create and configure client resource ClientResource clientResource = new ClientResource("https://localhost:8183/accounts/chunkylover53/mails/123"); clientResource.setNext(client); // Preemptively configure the authentication credentials ChallengeResponse authentication = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, "chunkylover53", "pwd"); clientResource.setChallengeResponse(authentication); // Communicate with remote resource MailResource mailClient = clientResource.wrap(MailResource.class); Mail m = mailClient.retrieve(); System.out.println("Subject: " + m.getSubject()); System.out.println("Content: " + m.getContent()); // Store HTTPS client client.stop(); }
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(); } }
/** * Wraps the parent client resource to proxy calls to the given Java interface into Restlet method * calls. The parent resource is defined in the sense of hierarchical URIs. If the resource URI is * not hierarchical, then an exception is thrown. * * @param <T> * @param resourceInterface The annotated resource interface class to proxy. * @return The proxy instance. */ public <T> T getParent(Class<? extends T> resourceInterface) throws ResourceException { T result = null; ClientResource parentResource = getParent(); if (parentResource != null) { result = parentResource.wrap(resourceInterface); } return result; }
/** * Example * http://api.smmry.com/&SM_API_KEY=792375072138384&SM_LENGTH=5&SM_URL=http://en.wikipedia.org/wiki/The_A-Team * * <p>Possible parameters placed in the request URL are: * * <p>&SM_API_KEY=N // Mandatory, N represents your registered API key. &SM_URL=X // Optional, X * represents the web page to summarize. &SM_LENGTH=N // Optional, N represents the number of * sentences returned, default is 6 &SM_KEYWORD_COUNT=N // Optional, N represents how many of the * top keywords to return &SM_QUOTE_AVOID // Optional, summary will not include quotations * &SM_WITH_BREAK // Optional, summary will contain string [BREAK] between each sentence */ public static ClientResource buildQueryToSummarizeArticle(String url, String length) { ClientResource resource = new ClientResource(SMMRY_URL); resource.getReference().addQueryParameter("SM_API_KEY", SM_API_KEY); resource.getReference().addQueryParameter("SM_KEYWORD_COUNT", "6"); // TODO fix hard code resource.getReference().addQueryParameter("SM_LENGTH", length); resource.getReference().addQueryParameter("SM_URL", url); resource.getReference().addSegment("&SM_QUOTE_AVOID"); // TODO fix hard code resource.getReference().addSegment("&SM_WITH_BREAK"); // TODO fix hard code return resource; }
public void postContent(String content) { ClientResource cr = null; try { cr = new ClientResource(uriShare + "?access_token=" + access_token + "&message=" + content); cr.post(content); } catch (ResourceException re) { System.err.println("Error when retrieving friends: " + cr.getResponse().getStatus()); System.err.println(uri + "?access_token" + access_token); } }
public void testPost() throws IOException, ResourceException { Representation result = clientResource.post("[\"root\"]", MediaType.APPLICATION_JSON); assertNotNull(result); assertEquals("[\"root\"]2", result.getText()); assertEquals(MediaType.APPLICATION_JSON, result.getMediaType()); result = clientResource.post("<root/>", MediaType.APPLICATION_XML); assertNotNull(result); assertEquals("<root/>1", result.getText()); assertEquals(MediaType.APPLICATION_XML, result.getMediaType()); }
/** * Wraps the child client resource to proxy calls to the given Java interface into Restlet method * calls. The child resource is defined in the sense of hierarchical URIs. If the resource URI is * not hierarchical, then an exception is thrown. * * @param <T> * @param relativeRef The URI reference of the child resource relatively to the current resource * seen as the parent resource. * @param resourceInterface The annotated resource interface class to proxy. * @return The proxy instance. */ public <T> T getChild(Reference relativeRef, Class<? extends T> resourceInterface) throws ResourceException { T result = null; ClientResource childResource = getChild(relativeRef); if (childResource != null) { result = childResource.wrap(resourceInterface); } return result; }
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(); }
/** * Test updating a single task variable using a binary stream. PUT * runtime/tasks/{taskId}/variables/{variableName} */ public void testUpdateBinaryTaskVariable() throws Exception { try { Task task = taskService.newTask(); taskService.saveTask(task); taskService.setVariable(task.getId(), "binaryVariable", "Original value".getBytes()); InputStream binaryContent = new ByteArrayInputStream("This is binary content".getBytes()); // Add name, type and scope Map<String, String> additionalFields = new HashMap<String, String>(); additionalFields.put("name", "binaryVariable"); additionalFields.put("type", "binary"); additionalFields.put("scope", "local"); // Upload a valid BPMN-file using multipart-data Representation uploadRepresentation = new HttpMultipartRepresentation("value", binaryContent, additionalFields); ClientResource client = getAuthenticatedClient( RestUrls.createRelativeResourceUrl( RestUrls.URL_TASK_VARIABLE, task.getId(), "binaryVariable")); Representation response = client.put(uploadRepresentation); assertEquals(Status.SUCCESS_OK, client.getResponse().getStatus()); JsonNode responseNode = objectMapper.readTree(response.getStream()); assertNotNull(responseNode); assertEquals("binaryVariable", responseNode.get("name").asText()); assertTrue(responseNode.get("value").isNull()); assertEquals("local", responseNode.get("scope").asText()); assertEquals("binary", responseNode.get("type").asText()); assertNotNull(responseNode.get("valueUrl").isNull()); assertTrue( responseNode .get("valueUrl") .asText() .endsWith( RestUrls.createRelativeResourceUrl( RestUrls.URL_TASK_VARIABLE_DATA, task.getId(), "binaryVariable"))); // Check actual value of variable in engine Object variableValue = taskService.getVariableLocal(task.getId(), "binaryVariable"); assertNotNull(variableValue); assertTrue(variableValue instanceof byte[]); assertEquals("This is binary content", new String((byte[]) variableValue)); } finally { // Clean adhoc-tasks even if test fails List<Task> tasks = taskService.createTaskQuery().list(); for (Task task : tasks) { taskService.deleteTask(task.getId(), true); } } }
private void resetGame() { final Reference reference = new Reference("http://localhost/clue/game"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); resource.delete(); resource.release(); assertEquals(324, getRemainingCount()); }
@Override public String call() throws Exception { String url = buildUrl(); System.out.println("Sending ==>" + url); ClientResource client = new ClientResource(url); StringWriter writer = new StringWriter(); client.post(javascript, MediaType.APPLICATION_JSON).write(writer); return writer.toString(); }
/** * Returns the parent resource. The parent resource is defined in the sense of hierarchical URIs. * If the resource URI is not hierarchical, then an exception is thrown. * * @return The parent resource. */ public ClientResource getParent() throws ResourceException { ClientResource result = null; if (getReference().isHierarchical()) { result = new ClientResource(this); result.setReference(getReference().getParentRef()); } else { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "The resource URI is not hierarchical."); } return result; }
/** * Returns the child resource defined by its URI relatively to the current resource. The child * resource is defined in the sense of hierarchical URIs. If the resource URI is not hierarchical, * then an exception is thrown. * * @param relativeRef The URI reference of the child resource relatively to the current resource * seen as the parent resource. * @return The child resource. * @throws ResourceException */ public ClientResource getChild(Reference relativeRef) throws ResourceException { ClientResource result = null; if ((relativeRef != null) && relativeRef.isRelative()) { result = new ClientResource(this); result.setReference(new Reference(getReference().getTargetRef(), relativeRef).getTargetRef()); } else { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "The child URI is not relative."); } return result; }
/** * Create WADL documentation * * @param url application url * @param docPath repository name */ protected void createWadl(String url, String docPath) { ClientResource cr = new ClientResource(url); DocWadl dw = new DocWadl(docPath); try { cr.options().write(dw.getWadlPrintStream()); cr.options(MediaType.TEXT_HTML).write(dw.getHtmlPrintStream()); } catch (ResourceException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@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--------------------------------"); }
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(); } }