public String sendTransactionalCypherQuery(String query) { String result = StringUtils.EMPTY; // query = "match(x:Product // {supcCode:100})-[r:ReviewRatings]-(u:Buyer)-[f:friend]-(us:Buyer {fbid:'3'}) return x,u,r"; // query = "match(x:Product // {supcCode:100})-[r:ReviewRatings]-(u:Buyer)-[f:friend]-(us:Buyer {fbid:'3'}) return distinct // {Product: x, User: u , Review: r}"; final String txUri = SERVER_ROOT_URI + "transaction/commit"; WebResource resource = Client.create().resource(txUri); String payload = "{\"statements\" : [ {\"statement\" : \"" + query + "\"} ]}"; ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity(payload) .post(ClientResponse.class); // System.out.println( String.format( // "POST [%s] to [%s], status code [%d], returned data: " // + System.getProperty( "line.separator" ) + "%s", // payload, txUri, response.getStatus(), // response.getEntity( String.class ) ) ); result = response.getEntity(String.class); response.close(); return result; }
/** * Create a new virtual machine * * @param machine * @param template * @return * @throws EduCloudServerException */ public VirtualMachine createVM(VirtualMachine machine, Template template) throws EduCloudServerException { NewVirtualMachineTO newVirtualMachineTO = new NewVirtualMachineTO(); newVirtualMachineTO.setTemplate(template); newVirtualMachineTO.setVirtualMachine(machine); WebResource service = getWebResouce(); String json = gson.toJson(newVirtualMachineTO); ClientResponse response = service .path("vm") .path("create") .accept(MediaType.APPLICATION_JSON) .put(ClientResponse.class, json); int status = response.getStatus(); String entity = response.getEntity(String.class); handleError(status, entity); response.close(); return gson.fromJson(entity, VirtualMachine.class); }
/** * Return list of virtual machines * * @return * @throws EduCloudServerException */ public List<VirtualMachine> describeInstances() throws EduCloudServerException { WebResource service = getWebResouce(); ClientResponse response = service .path("vm") .path("describeInstances") .accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); int status = response.getStatus(); String entity = response.getEntity(String.class); handleError(status, entity); response.close(); // Recupera o array de retorno. VirtualMachine[] virtualMachines = gson.fromJson(entity, VirtualMachine[].class); // Gera a lista de retorno. List<VirtualMachine> listaVirtualMachines = new ArrayList<VirtualMachine>(); for (VirtualMachine vm : virtualMachines) { listaVirtualMachines.add(vm); } return listaVirtualMachines; }
protected void download(final Location location, final String uri, final OutputStream target) throws IOException { try { final ClientResponse response = getNexusClient().uri(uri).get(ClientResponse.class); if (!ClientResponse.Status.OK.equals(response.getClientResponseStatus())) { throw getNexusClient() .convert( new ContextAwareUniformInterfaceException(response) { @Override public String getMessage(final int status) { if (status == Response.Status.NOT_FOUND.getStatusCode()) { return String.format("Inexistent path: %s", location); } return null; } }); } try { IOUtil.copy(response.getEntityInputStream(), target); } finally { response.close(); } } catch (ClientHandlerException e) { throw getNexusClient().convert(e); } }
public void finish() throws SourceException { if (ios != null) { ios.finish(); } if (response != null) { response.close(); } }
private REST handle(ClientResponse response) { status = response.getStatus(); location = response.getLocation(); readEntityIfPossible(response); response.close(); System.out.printf( "GET from [%s], status code [%d] location: %s, returned data: %n%s", path, status, location, entity); return this; }
public boolean bind(String noid, String target) throws HTTPException { String url = this.uri + "?bind+set+" + naan + "/" + noid + "+location+" + target; bindResource = client.resource(url); ClientResponse bindResponse; bindResponse = bindResource.accept("text/plain").get(ClientResponse.class); int status = bindResponse.getStatus(); bindResponse.close(); if (status != 200) { throw new HTTPException(status); } else return true; }
private static void setPropertyNodeServer(String id, String propertyName, String propertyValue) { String propertyUri = "http://localhost:7474/db/data/node/" + id + "/properties/" + propertyName; WebResource resource = Client.create().resource(propertyUri); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity("\"" + propertyValue + "\"") .put(ClientResponse.class); System.out.println( String.format("PUT to [%s], status code [%d]", propertyUri, response.getStatus())); response.close(); }
public void testPost() { startServer(HttpMethodResource.class); DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig(); config.getClasses().add(HeaderWriter.class); ApacheHttpClient c = ApacheHttpClient.create(config); WebResource r = c.resource(getUri().path("test").build()); ClientResponse cr = r.header("X-CLIENT", "client").post(ClientResponse.class, "POST"); assertEquals(200, cr.getStatus()); assertTrue(cr.hasEntity()); cr.close(); }
public void registerVms(RegisterVirtualMachineTO register) { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource(getBaseURI()); String json = gson.toJson(register); ClientResponse response = service .path("vm") .path("registerVms") .accept(MediaType.APPLICATION_JSON) .put(ClientResponse.class, json); response.close(); }
private static void addMetadataToProperty(URI relationshipUri, String name, String value) throws URISyntaxException { URI propertyUri = new URI(relationshipUri.toString() + "/properties"); String entity = toJsonNameValuePairCollection(name, value); WebResource resource = Client.create().resource(propertyUri); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity(entity) .put(ClientResponse.class); System.out.println( String.format( "PUT [%s] to [%s], status code [%d]", entity, propertyUri, response.getStatus())); response.close(); }
public void testPostChunked() { ResourceConfig rc = new DefaultResourceConfig(HttpMethodResource.class); rc.getProperties() .put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, LoggingFilter.class.getName()); startServer(rc); DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig(); config.getClasses().add(HeaderWriter.class); config.getProperties().put(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE, 1024); ApacheHttpClient c = ApacheHttpClient.create(config); WebResource r = c.resource(getUri().path("test").build()); ClientResponse cr = r.header("X-CLIENT", "client").post(ClientResponse.class, "POST"); assertEquals(200, cr.getStatus()); assertTrue(cr.hasEntity()); cr.close(); }
public String mint() throws HTTPException { if (mintResource == null) { String url = this.uri + "?mint+1"; mintResource = client.resource(url); } String noid; ClientResponse mintResponse; mintResponse = mintResource.accept("text/plain").get(ClientResponse.class); int status = mintResponse.getStatus(); String body = mintResponse.getEntity(String.class); if (status != 200) { throw new HTTPException(status); } noid = body.split("/")[1].trim(); mintResponse.close(); return noid; }
/** * Stop a virtual machine * * @param machine * @throws EduCloudServerException */ public void stopVM(VirtualMachine machine) throws EduCloudServerException { WebResource service = getWebResouce(); String json = gson.toJson(machine); ClientResponse response = service .path("vm") .path("stop") .accept(MediaType.APPLICATION_JSON) .put(ClientResponse.class, json); int status = response.getStatus(); String entity = response.getEntity(String.class); handleError(status, entity); response.close(); }
private static URI sendNodeToServer() { 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); URI location = response.getLocation(); System.out.println( String.format("POST to [%s], status code [%d]", nodeEntryPointUri, response.getStatus())); response.close(); return location; }
/** * Return a virtual machines * * @return * @throws EduCloudServerException */ public VirtualMachine getVirtualMachine(int id) throws EduCloudServerException { WebResource service = getWebResouce(); ClientResponse response = service .path("vm") .path("get") .path(String.valueOf(id)) .accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); int status = response.getStatus(); String entity = response.getEntity(String.class); handleError(status, entity); response.close(); return gson.fromJson(entity, VirtualMachine.class); }
@Override public void waitForAllTasksToStop(final Time timeout, final Time window) { try { Time actualTimeout = timeout; if (actualTimeout == null) { actualTimeout = Time.minutes(1); } Time actualWindow = window; if (actualWindow == null) { actualWindow = Time.seconds(10); } LOG.info( "Waiting for Nexus to not execute any task for {} (timeouts in {})", actualWindow.toString(), actualTimeout.toString()); final MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("timeout", String.valueOf(actualTimeout.toMillis())); params.add("window", String.valueOf(actualWindow.toMillis())); final ClientResponse response = getNexusClient().serviceResource("tasks/waitFor", params).get(ClientResponse.class); response.close(); if (Response.Status.ACCEPTED.getStatusCode() == response.getStatus()) { throw new TasksAreStillRunningException(actualTimeout); } else if (!response .getClientResponseStatus() .getFamily() .equals(Response.Status.Family.SUCCESSFUL)) { throw getNexusClient().convert(new UniformInterfaceException(response)); } } catch (ClientHandlerException e) { throw getNexusClient().convert(e); } catch (UniformInterfaceException e) { throw getNexusClient().convert(e); } }
@Override public HttpResponse get(final URI uri, final Optional<Map<String, String>> additionalHeaders) { ClientResponse clientResponse = null; try { final WebResource webResource = queueProxyClient.resource(uri); WebResource.Builder builder = webResource.getRequestBuilder(); if (additionalHeaders.isPresent()) { for (final Map.Entry<String, String> entry : additionalHeaders.get().entrySet()) { builder = builder.header(entry.getKey(), entry.getValue()); } } clientResponse = builder.get(ClientResponse.class); return new HttpResponse(clientResponse.getStatus(), clientResponse.getEntity(String.class)); } catch (ClientHandlerException ex) { throw new HttpClientException("Jersey client throwing exception.", ex); } finally { if (clientResponse != null) { clientResponse.close(); } } }
private static URI addRelationship( URI startNode, URI endNode, String relationshipType, String jsonAttributes) throws URISyntaxException { URI fromUri = new URI(startNode.toString() + "/relationships"); String relationshipJson = generateJsonRelationship(endNode, relationshipType, jsonAttributes); System.out.println(relationshipJson + "==================================="); WebResource resource = Client.create().resource(fromUri); // POST JSON to the relationships URI ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity(relationshipJson) .post(ClientResponse.class); final URI location = response.getLocation(); System.out.println( String.format( "POST to [%s], status code [%d], location header [%s]", fromUri, response.getStatus(), location.toString())); response.close(); return location; }
private static void setRelationshipServer(String node1, String node2, String type) { URI fromUri = null; try { fromUri = new URI("http://localhost:7474/db/data/node/" + node1 + "/relationships/"); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String endUri = "http://localhost:7474/db/data/node/" + node2; String relationshipJson = generateJsonRelationship(endUri, type, "rel"); WebResource resource = Client.create().resource(fromUri); // POST JSON to the relationships URI ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity(relationshipJson) .post(ClientResponse.class); final URI location = response.getLocation(); System.out.println( String.format("POST to [%s], status code [%d]", fromUri, response.getStatus())); response.close(); }
@Override public ReadResponse readBlock(ReadRequest request) { ReadResponse ret = new ReadResponse(); if (remoteClient == null) { throw new IllegalStateException( String.format( "%s missing %s", getClass().getSimpleName(), RemoteClient.class.getSimpleName())); } ret.setRequest(request); String uri = remoteClient.getURI(String.format("%s/%s", Constants.FILE_PATH, request.getFileName())); WebResource webResource = remoteClient .getClient() .resource(uri) .queryParam(Constants.OFFSET_PARAM, String.valueOf(request.getOffset())) .queryParam(Constants.BLOCK_SIZE_PARAM, String.valueOf(request.getBlockSize())); logger.debug(webResource.toString()); Builder builder = webResource.accept(MediaType.APPLICATION_OCTET_STREAM); if (FileUtils.isCompress()) { builder = builder.header(Constants.CONTENT_ENCODED_HEADER, Constants.DEFLATE); } ClientResponse clientResponse = builder.get(ClientResponse.class); try { remoteClient.checkForException(clientResponse); if (clientResponse.getStatus() != HttpStatus.OK_200) { throw new ErrorReadingBlockException( String.format( "Failed GET %s: HttpStatus: %d/%s", uri, clientResponse.getStatus(), clientResponse.getStatusInfo())); } logger.debug(clientResponse.getHeaders().toString()); ret.setLength( Integer.parseInt(clientResponse.getHeaders().getFirst(Constants.LENGTH_HEADER))); int contentLength = Integer.parseInt(clientResponse.getHeaders().getFirst("Content-Length")); byte[] block = null; int compressed = -1; if (clientResponse.getHeaders().containsKey(Constants.COMPRESSED_HEADER)) { compressed = Integer.parseInt(clientResponse.getHeaders().getFirst(Constants.COMPRESSED_HEADER)); if (contentLength != compressed) { throw new ErrorReadingBlockException( String.format( "Failed GET %s: Compressed Content-Length: %d/%s", uri, contentLength, compressed)); } Inflated inflated = CompressionUtils.inflate(getDataByEntity(clientResponse, compressed), ret.getLength()); if (inflated == null || inflated.getLength() != ret.getLength()) { throw new ErrorInflatingBlockException("Error inflating compressed read response"); } block = inflated.getData(); } else { if (contentLength != ret.getLength()) { throw new ErrorReadingBlockException( String.format( "Failed GET %s: Content-Length: %d/%s", uri, contentLength, ret.getLength())); } block = getDataByEntity(clientResponse, ret.getLength()); } ret.setCrc32(Long.parseLong(clientResponse.getHeaders().getFirst(Constants.CRC_HEADER))); ret.setEof(Boolean.parseBoolean(clientResponse.getHeaders().getFirst(Constants.EOF_HEADER))); ret.setSuccess( Boolean.parseBoolean(clientResponse.getHeaders().getFirst(Constants.SUCCESS_HEADER))); ret.setData(block); } finally { clientResponse.close(); } return ret; }
/** * Get storage pools. * * @return storage pools * @throws ECSException */ public List<ECSStoragePool> getStoragePools() throws ECSException { _log.info("ECSApi:getStoragePools enter"); ClientResponse clientResp = null; clientResp = _client.get_json(_baseUrl.resolve(URI_STORAGE_POOL), authToken); if (clientResp.getStatus() != 200) { if (clientResp.getStatus() == 401 || clientResp.getStatus() == 302) { getAuthToken(); clientResp = _client.get_json(_baseUrl.resolve(URI_STORAGE_POOL), authToken); } if (clientResp.getStatus() != 200) { throw ECSException.exceptions.storageAccessFailed( _baseUrl.resolve(URI_STORAGE_POOL), clientResp.getStatus(), "getStoragePools"); } } JSONObject objectRepGroup = null; JSONArray arrayRepGroup = null; List<ECSStoragePool> ecsPools = new ArrayList<ECSStoragePool>(); JSONObject objRG = null; JSONArray aryVarray = null; Long storagepoolTotalCapacity = 0L, storagepoolFreeCapacity = 0L; ClientResponse clientRespVarray = null; try { objectRepGroup = clientResp.getEntity(JSONObject.class); arrayRepGroup = objectRepGroup.getJSONArray("data_service_vpool"); // run thru every replication group for (int i = 0; i < arrayRepGroup.length(); i++) { ECSStoragePool pool = new ECSStoragePool(); objRG = arrayRepGroup.getJSONObject(i); JSONObject objVarray = null; String vArrayId = null; URI uriEcsVarray = null; JSONObject objVarrayCap = null; String ecsVarray = null; // Get ECS vArray ID(=ECS StoragePool/cluster) and its capacity aryVarray = objRG.getJSONArray("varrayMappings"); for (int j = 0; j < aryVarray.length(); j++) { objVarray = aryVarray.getJSONObject(j); vArrayId = objVarray.getString("value"); // get total and free capacity for this ECS vArray ecsVarray = ECS_VARRAY_BASE + vArrayId + ".json"; uriEcsVarray = URI.create(ecsVarray); clientRespVarray = _client.get_json(_baseUrl.resolve(uriEcsVarray), authToken); if (clientRespVarray.getStatus() != 200) { if (clientRespVarray.getStatus() == 401 || clientRespVarray.getStatus() == 302) { getAuthToken(); clientRespVarray = _client.get_json(_baseUrl.resolve(uriEcsVarray), authToken); } if (clientRespVarray.getStatus() != 200) { throw ECSException.exceptions.storageAccessFailed( _baseUrl.resolve(uriEcsVarray), clientRespVarray.getStatus(), "get ECS vArray"); } } objVarrayCap = clientRespVarray.getEntity(JSONObject.class); storagepoolTotalCapacity += Integer.parseInt(objVarrayCap.getString("totalProvisioned_gb")); storagepoolFreeCapacity += Integer.parseInt(objVarrayCap.getString("totalFree_gb")); } // for each ECS varray pool.setName(objRG.getString("name")); pool.setId(objRG.getString("id")); pool.setTotalCapacity(storagepoolTotalCapacity); pool.setFreeCapacity(storagepoolFreeCapacity); ecsPools.add(pool); if (clientRespVarray != null) { clientRespVarray.close(); } } } catch (Exception e) { _log.error("discovery of Pools failed"); String response = String.format("%1$s", (clientResp == null) ? "" : clientResp); String response2 = String.format("%1$s", (clientRespVarray == null) ? "" : clientRespVarray); response = response + response2; throw ECSException.exceptions.getStoragePoolsFailed(response, e); } finally { _log.info("discovery of Pools finished"); if (clientResp != null) { clientResp.close(); } if (clientRespVarray != null) { clientRespVarray.close(); } } _log.info("ECSApi:getStoragePools leave"); return ecsPools; }
// Dans cette fonction nous allons récupérer des identifiants d'utilisateurs @Test public void testGetUsers() throws Exception { Form f = new Form(); WebResource webResource; ClientResponse result; System.out.println("****************** Recupereration des utilisateurs ! ******************"); // tente de récupérer un utilisateur sans être connecté: échec attendu webResource = client.resource(new URL(this.baseUrl + "/users/getuserid/1").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.USER_OFFLINE, result.getStatus()); System.out.println( "Un utilisateur non connecte tente, sans succes, de recuperer les informations de l'utilisateur 1 par id"); result.close(); webResource = client.resource(new URL(this.baseUrl + "/users/getuseremail/[email protected]").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.USER_OFFLINE, result.getStatus()); System.out.println( "Un utilisateur non connecte tente, sans succes, de recuperer les informations de l'utilisateur 1 par email"); result.close(); webResource = client.resource(new URL(this.baseUrl + "/users/search/jul").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.USER_OFFLINE, result.getStatus()); System.out.println( "Un utilisateur non connecte tente, sans succes, de rechercher des utilisateurs par nom"); result.close(); // Connexion de l'utilisateur 1: succès attendu f.add("email", "*****@*****.**"); f.add("password", "password"); webResource = client.resource(new URL(this.baseUrl + "/connection").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, f); Assert.assertEquals(Status.OK, result.getStatus()); System.out.println("L'utilisateur 1 se connecte"); result.close(); // tente de récupérer un utilisateur inexistant par id: échec attendu webResource = client.resource(new URL(this.baseUrl + "/users/getuserid/132324").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.USER_NO_ACCOUNT, result.getStatus()); System.out.println( "L'utilisateur 1 n'arrive pas a recuperer les informations d'un utilisateur inexistant"); result.close(); // récupère l'utilisateur ayant l'id 1 : succès attendu webResource = client.resource(new URL(this.baseUrl + "/users/getuserid/1").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.OK, result.getStatus()); System.out.println( "L'utilisateur 1 recupere les informations de l'utilisateur 1 par identifiant technique"); result.close(); // tente de récupérer un utilisateur inexistant par email: échec attendu webResource = client.resource( new URL(this.baseUrl + "/users/getuseremail/[email protected]").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.USER_NO_ACCOUNT, result.getStatus()); System.out.println( "L'utilisateur 1 tente de recuperer, sans succes, les informations d'un utilisateur inexistant par email"); result.close(); // récupère l'utilisateur 5 ayant l'email [email protected] : succès attendu webResource = client.resource(new URL(this.baseUrl + "/users/getuseremail/[email protected]").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.OK, result.getStatus()); System.out.println("L'utilisateur 1 recupere les informations de l'utilisateur 5 par email"); result.close(); // récupère la liste des utilisateurs dont une partie du nom est 'n': succès attendu webResource = client.resource(new URL(this.baseUrl + "/users/search/n").toURI()); result = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); Assert.assertEquals(Status.OK, result.getStatus()); List<LinkedHashMap<String, ?>> listUser = result.getEntity(List.class); String res = "L'utilisateur 1 recherche les utilisateurs possedants 'n' dans leur nom: "; for (LinkedHashMap<String, ?> u : listUser) { res += u.get("email") + " "; } System.out.println(res); result.close(); }
private void closeResponse(ClientResponse clientResp) { if (null != clientResp) { clientResp.close(); } }