コード例 #1
0
ファイル: OpenImpl.java プロジェクト: nbj11/DrivlessCar
  public OpenImpl(String name) {
    this.name = name;
    publisherName = name;
    stateEventTypeName = "_" + name + "_state";
    state = s0;

    ClientConfig config = new DefaultClientConfig();
    client = Client.create(config);
    service = client.resource(REST_URI);
    eventTypeService = service.path(EVENTS_PATH);
    publishersService = service.path(PUBLISHERS_PATH);
    myPublisher = service.path(PUBLISHERS_PATH + "/" + publisherName);

    System.out.println("Registering events");
    ClientResponse response =
        eventTypeService
            .type(MediaType.APPLICATION_XML)
            .put(ClientResponse.class, CopalClient.eventType(stateEventTypeName));
    System.out.println(response.toString());
    System.out.println(response.getEntity(String.class).toString());

    System.out.println("Setting ttl");
    WebResource test = service.path(EVENTS_PATH + "/" + stateEventTypeName + "/ttl");
    response = test.type(MediaType.TEXT_PLAIN).put(ClientResponse.class, "" + Integer.MAX_VALUE);
    System.out.println(response.toString());
    System.out.println(response.getEntity(String.class).toString());

    String[] eventNames = {stateEventTypeName};
    System.out.println("Registering publisher");
    System.out.println(CopalClient.publisher(publisherName, eventNames));
    response =
        publishersService
            .type(MediaType.APPLICATION_XML)
            .put(ClientResponse.class, CopalClient.publisher(publisherName, eventNames));
    System.out.println(response.toString());
    System.out.println(response.getEntity(String.class).toString());

    response =
        myPublisher
            .type(MediaType.APPLICATION_XML)
            .post(ClientResponse.class, CopalClient.event(stateEventTypeName, state));
    System.out.println(response.toString());

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                System.out.println("Removing publisher");
                ClientResponse response = myPublisher.delete(ClientResponse.class);
                System.out.println(response.toString());
                System.out.println(response.getEntity(String.class).toString());

                System.out.println("Removing events");
                WebResource wr = service.path(EVENTS_PATH + "/" + stateEventTypeName);
                response = wr.delete(ClientResponse.class);
                System.out.println(response.toString());
                System.out.println(response.getEntity(String.class).toString());
              }
            });
  }
コード例 #2
0
  /** Executes an authentication request via HTTP POST */
  private <T> T executeAuthenticationPost(WebResource webResource, Class<T> returnClass)
      throws CIWiseRESTConnectorTokenExpiredException, CIWiseRESTConnectorException {

    // Map query params for POST operation MultivaluedMap, MultivaluedMapImpl

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("username", getConnector().getConfig().getUsername());
    queryParams.add("password", getConnector().getConfig().getPassword());

    /** Call HTTP POST */
    ClientResponse clientResponse =
        webResource
            .queryParams(queryParams)
            .accept(MediaType.APPLICATION_JSON)
            .post(ClientResponse.class);

    if (clientResponse.getStatus() == 200) {
      return clientResponse.getEntity(returnClass);
    } else if (clientResponse.getStatus() == 401) {
      throw new CIWiseRESTConnectorTokenExpiredException(
          "The access token has expired; " + clientResponse.getEntity(String.class));
    } else {
      throw new CIWiseRESTConnectorException(
          String.format(
              "ERROR - statusCode: %d - message: %s",
              clientResponse.getStatus(), clientResponse.getEntity(String.class)));
    }
  }
コード例 #3
0
  /**
   * Gets token from Keystone. It is a synchronous operation.
   *
   * @param uri String
   * @return token String
   */
  public String getAuthToken(String uri) {

    String token = "";
    String tenantId = "";
    Gson gson = new Gson();

    AuthTokenRequest w = new AuthTokenRequest();
    w.auth.passwordCredentials.username = endPoint.getCinderRESTuserName();
    w.auth.passwordCredentials.password = endPoint.getCinderRESTPassword();
    w.auth.tenantName = endPoint.getCinderTenantName();
    String json = gson.toJson(w);

    try {
      ClientResponse js_response = client.post(URI.create(uri), json);
      String s = js_response.getEntity(String.class);
      AccessWrapper wrapper = gson.fromJson(s, AccessWrapper.class);
      token = wrapper.access.token.id;
      tenantId = wrapper.access.token.tenant.id;
    } catch (Exception e) {
      _log.error("Exception!! \n Now trying String processing....\n");
      ClientResponse js_response = client.post(URI.create(uri), json);
      String s = js_response.getEntity(String.class);

      token = getTokenId(s);
      tenantId = getTenantId(s);
    } /* catch */

    // Update it in endPoint instance for every fetch/re-fetch
    endPoint.setCinderToken(token);
    getClient().setAuthTokenHeader(token);
    endPoint.setCinderTenantId(tenantId);

    return token;
  }
コード例 #4
0
  /** Executes an API request */
  private <T> T execute(WebResource webResource, String method, Class<T> returnClass)
      throws CIWiseRESTConnectorTokenExpiredException, CIWiseRESTConnectorException {

    /** Call HTTP Method */
    if (connector.getToken() == null) {
      Token token = getXAuthToken();
      if (token != null) {
        connector.setToken((String) token.getToken());
      }
    }
    ClientResponse clientResponse =
        webResource
            .accept(MediaType.APPLICATION_JSON)
            .header("X-Auth-Token", connector.getToken())
            .method(method, ClientResponse.class);
    if (clientResponse.getStatus() == 200) {
      return clientResponse.getEntity(returnClass);
    } else if (clientResponse.getStatus() == 401) {
      throw new CIWiseRESTConnectorTokenExpiredException(
          "The access token has expired; " + clientResponse.getEntity(String.class));
    } else {
      throw new CIWiseRESTConnectorException(
          String.format(
              "ERROR - statusCode: %d - message: %s",
              clientResponse.getStatus(), clientResponse.getEntity(String.class)));
    }
  }
コード例 #5
0
ファイル: TestDHCP.java プロジェクト: Ahmed-Azri/midonet
  // @Test
  public void testSubnetCascadingDelete() {
    // Create a subnet with several configuration pieces: option 3,
    // option 121, and a host assignment. Then delete it.
    ClientResponse response;

    DtoDhcpSubnet subnet = new DtoDhcpSubnet();
    subnet.setSubnetPrefix("172.31.0.0");
    subnet.setSubnetLength(24);
    subnet.setServerAddr("172.31.0.118");
    response =
        resource()
            .uri(bridge.getDhcpSubnets())
            .type(APPLICATION_DHCP_SUBNET_JSON)
            .post(ClientResponse.class, subnet);
    assertEquals(201, response.getStatus());
    subnet =
        resource()
            .uri(response.getLocation())
            .accept(APPLICATION_DHCP_SUBNET_JSON)
            .get(DtoDhcpSubnet.class);

    DtoDhcpHost host1 = new DtoDhcpHost();
    host1.setMacAddr("02:33:44:55:00:00");
    host1.setIpAddr("172.31.0.11");
    host1.setName("saturn");
    response =
        resource()
            .uri(subnet.getHosts())
            .type(APPLICATION_DHCP_HOST_JSON)
            .post(ClientResponse.class, host1);
    assertEquals(201, response.getStatus());

    // List the subnets
    response =
        resource()
            .uri(bridge.getDhcpSubnets())
            .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON)
            .get(ClientResponse.class);
    assertEquals(200, response.getStatus());
    DtoDhcpSubnet[] subnets = response.getEntity(DtoDhcpSubnet[].class);
    assertThat("We expect 1 listed subnets.", subnets, arrayWithSize(1));
    assertThat(
        "We expect the listed subnets to match the one we created.",
        subnets,
        arrayContainingInAnyOrder(subnet));

    // Now delete the subnet.
    response = resource().uri(subnet.getUri()).delete(ClientResponse.class);
    assertEquals(204, response.getStatus());
    // Show that the list of DHCP subnet configurations is empty.
    response =
        resource()
            .uri(bridge.getDhcpSubnets())
            .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON)
            .get(ClientResponse.class);
    assertEquals(200, response.getStatus());
    subnets = response.getEntity(DtoDhcpSubnet[].class);
    assertThat("We expect 0 listed subnets.", subnets, arrayWithSize(0));
  }
コード例 #6
0
ファイル: JiraExporter.java プロジェクト: WtfJoke/rtc2jira
 Issue createIssueInJira(Issue issue) {
   ClientResponse postResponse = restAccess.post("/issue", issue);
   if (postResponse.getStatus() == Status.CREATED.getStatusCode()) {
     return postResponse.getEntity(Issue.class);
   } else {
     System.err.println("Problems while creating issue: " + postResponse.getEntity(String.class));
     return null;
   }
 }
コード例 #7
0
  @Ignore
  public void testGetFileText() throws Exception {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "file.txt", "abcdefg");

    WebResource webResource = resource();

    ClientResponse r1 =
        webResource
            .path("repos/:public:file.txt/content")
            .accept(TEXT_PLAIN)
            .get(ClientResponse.class);
    assertResponse(r1, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r1.getEntity(String.class));

    // check again but with no Accept header
    ClientResponse r2 =
        webResource.path("repos/:public:file.txt/content").get(ClientResponse.class);
    assertResponse(r2, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r2.getEntity(String.class));

    // check again but with */*
    ClientResponse r3 =
        webResource
            .path("repos/:public:file.txt/content")
            .accept(TEXT_PLAIN)
            .accept(MediaType.WILDCARD)
            .get(ClientResponse.class);
    assertResponse(r3, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r3.getEntity(String.class));

    cleanupUserAndRoles(mainTenant_1);
    cleanupUserAndRoles(systemTenant);
  }
コード例 #8
0
  /*
   * Send DELETE request to KittyHawk server, and handle redirect/cookies
   *
   * @param resource webResource
   *
   * @param param parameters for delete
   *
   * @throws VNXeException
   */
  public ClientResponse deleteRequest(Object param) throws VNXeException {
    _logger.debug("delete data: " + _url);
    ClientResponse response = sendDeleteRequest(param);

    Status statusCode = response.getClientResponseStatus();
    if (statusCode == ClientResponse.Status.OK
        || statusCode == ClientResponse.Status.ACCEPTED
        || statusCode == ClientResponse.Status.NO_CONTENT) {
      return response;
    } else if (response.getClientResponseStatus() == ClientResponse.Status.UNAUTHORIZED) {
      authenticate();
      response = sendDeleteRequest(param);
      statusCode = response.getClientResponseStatus();
      if (statusCode == ClientResponse.Status.OK
          || statusCode == ClientResponse.Status.ACCEPTED
          || statusCode == ClientResponse.Status.NO_CONTENT) {
        return response;
      }
    }
    int redirectTimes = 1;
    // handle redirect
    while (response.getClientResponseStatus() == ClientResponse.Status.FOUND
        && redirectTimes < VNXeConstants.REDIRECT_MAX) {

      String code = response.getClientResponseStatus().toString();
      String data = response.getEntity(String.class);
      _logger.debug("Returned code: {} returned data: ", code, data);
      WebResource resource = handelRedirect(response);
      if (resource != null) {
        response =
            buildRequest(resource.getRequestBuilder()).entity(param).delete(ClientResponse.class);
        redirectTimes++;
      } else {
        // could not find the redirect url, return
        _logger.error(
            String.format(
                "The post request to: %s failed with: %s %s",
                _url,
                response.getClientResponseStatus().toString(),
                response.getEntity(String.class)));
        throw VNXeException.exceptions.unexpectedDataError(
            "Got redirect status code, but could not get redirected URL");
      }
    }
    if (redirectTimes >= VNXeConstants.REDIRECT_MAX) {
      _logger.error("redirected too many times for the request {} ", _url);
      throw VNXeException.exceptions.unexpectedDataError(
          "Redirected too many times while sending the request for " + _url);
    }

    checkResponse(response, DELETE_REQUEST);

    return response;
  }
コード例 #9
0
  @Test(dependsOnMethods = "testGetTraitNames")
  public void testAddTraitWithAttribute() throws Exception {
    final String traitName = "PII_Trait" + randomString();
    HierarchicalTypeDefinition<TraitType> piiTrait =
        TypesUtil.createTraitTypeDef(
            traitName,
            ImmutableList.<String>of(),
            TypesUtil.createRequiredAttrDef("type", DataTypes.STRING_TYPE));
    String traitDefinitionAsJSON = TypesSerialization$.MODULE$.toJson(piiTrait, true);
    LOG.debug("traitDefinitionAsJSON = " + traitDefinitionAsJSON);
    createType(traitDefinitionAsJSON);

    Struct traitInstance = new Struct(traitName);
    traitInstance.set("type", "SSN");
    String traitInstanceAsJSON = InstanceSerialization.toJson(traitInstance, true);
    LOG.debug("traitInstanceAsJSON = " + traitInstanceAsJSON);

    final String guid = tableId._getId();
    ClientResponse clientResponse =
        service
            .path(ENTITIES)
            .path(guid)
            .path(TRAITS)
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.POST, ClientResponse.class, traitInstanceAsJSON);
    Assert.assertEquals(clientResponse.getStatus(), Response.Status.CREATED.getStatusCode());

    String responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);

    JSONObject response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));
    Assert.assertNotNull(response.get(AtlasClient.GUID));

    // verify the response
    clientResponse = getEntityDefinition(guid);
    Assert.assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());
    responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);
    response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

    final String definition = response.getString(AtlasClient.DEFINITION);
    Assert.assertNotNull(definition);
    Referenceable entityRef = InstanceSerialization.fromJsonReferenceable(definition, true);
    IStruct traitRef = entityRef.getTrait(traitName);
    String type = (String) traitRef.get("type");
    Assert.assertEquals(type, "SSN");
  }
コード例 #10
0
  @Test
  public void testWriteBinaryFile() throws InterruptedException {
    final String str = "some binary text";
    final String fileName = "file.bn";

    // set object in PentahoSystem
    mp.defineInstance(IUnifiedRepository.class, repo);

    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});

    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1,
        "admin",
        "password",
        "",
        new String[] {adminAuthorityName, authenticatedAuthorityName});
    try {
      login(sysAdminUserName, systemTenant, new String[] {adminAuthorityName});
      login("admin", mainTenant_1, new String[] {adminAuthorityName, authenticatedAuthorityName});

      WebResource webResource = resource();
      final byte[] blob = str.getBytes();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFileBinary(publicFolderPath.replaceAll("/", ":") + ":" + fileName, blob);

      // the file might not actually be ready.. wait a second
      Thread.sleep(20000);

      ClientResponse response =
          webResource
              .path("repo/files/:public:file.bn")
              .accept(APPLICATION_OCTET_STREAM)
              .get(ClientResponse.class);
      assertResponse(response, Status.OK, APPLICATION_OCTET_STREAM);

      byte[] data = response.getEntity(byte[].class);
      assertEquals("contents of file incorrect/missing", str, new String(data));
    } catch (Exception ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
コード例 #11
0
ファイル: ALMConnection.java プロジェクト: Jfeurich/almapi
  /**
   * TODO
   *
   * @param serviceName
   * @param pageSize
   * @return
   */
  public List<IEntity> getEntities(final String serviceName, final int pageSize) {

    int startIndex = 1;
    int resultCount = -1;
    final LinkedList<IEntity> result = new LinkedList<IEntity>();

    do {
      final String url =
          ALM_REST_SERVICE_URL
              + serviceName
              + "?page-size="
              + pageSize
              + "&start-index="
              + startIndex;
      final ClientResponse response = request(url);
      if (response == null) {
        // TODO log warn
        return result;
      }
      final Entities entities = response.getEntity(Entities.class);
      resultCount = entities.getTotalResults();
      result.addAll(entities);
      startIndex = startIndex + pageSize;

    } while (resultCount == pageSize);
    return result;
  }
コード例 #12
0
  @Test(dependsOnMethods = "testSubmit")
  public void testGetTypeNames() throws Exception {
    WebResource resource = service.path("api/atlas/types");

    ClientResponse clientResponse =
        resource
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.GET, ClientResponse.class);
    assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());

    String responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);

    JSONObject response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

    final JSONArray list = response.getJSONArray(AtlasClient.RESULTS);
    Assert.assertNotNull(list);

    // Verify that primitive and core types are not returned
    String typesString = list.join(" ");
    Assert.assertFalse(typesString.contains(" \"__IdType\" "));
    Assert.assertFalse(typesString.contains(" \"string\" "));
  }
コード例 #13
0
ファイル: Bootstrap.java プロジェクト: jwl2006/273-IoT-client
  public void bootFromServer(String clientName, Database db1)
      throws JSONException, ClassNotFoundException {

    Client client = Client.create();

    WebResource webResource =
        client.resource("http://localhost:8080/com.youtube.rest/api/bootstrap/get/" + clientName);
    ;

    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

    if (response.getStatus() != 200 && response.getStatus() != 204) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    String output = response.getEntity(String.class);
    System.out.println("Server Bootstrap information: ");
    System.out.println(output);
    String query = db1.parseData(output);
    System.out.println("QUERY");
    System.out.println(query);
    db1.delete("client1");
    //	db1.insert(query);
    System.out.println("Information saved in Mysql!");
    System.out.println("Server boot done!");
  }
コード例 #14
0
ファイル: MP.java プロジェクト: mercadopago/sdk-java
    private static JSONObject exec(String method, String uri, Object data, String contentType)
        throws JSONException {
      ClientResponse apiResult;
      JSONObject response = new JSONObject();

      try {
        apiResult =
            buildRequest(API_BASE_URL + uri, contentType)
                .method(method, ClientResponse.class, data);
        int apiHttpCode = apiResult.getStatus();

        response.put("status", apiHttpCode);

        String responseBody = apiResult.getEntity(String.class);

        response.put(
            "response",
            responseBody.indexOf("[") == 0
                ? new JSONArray(responseBody)
                : new JSONObject(responseBody));
      } catch (Exception e) {
        response.put("status", 500);
        response.put("error", e.getMessage());
      }

      return response;
    }
コード例 #15
0
  protected AccessTokenResponse getAccessToken(
      Client client, PartnerConfiguration partnerConfiguration)
      throws UnsupportedEncodingException {
    String tokenParams =
        String.format(
            "grant_type=client_credentials&scope=all&client_id=%s&client_secret=%s",
            partnerConfiguration.userName, partnerConfiguration.password);

    ClientResponse postResponse =
        client
            .resource(TOKEN_URL)
            .entity(tokenParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .header(
                "Authorization",
                basic(partnerConfiguration.userName, partnerConfiguration.password))
            .post(ClientResponse.class);

    String json = postResponse.getEntity(String.class);
    JSONObject accessToken = (JSONObject) JSONSerializer.toJSON(json);

    AccessTokenResponse response = new AccessTokenResponse();
    response.setAccessToken(accessToken.getString("access_token"));
    response.setExpiresIn(accessToken.getLong("expires_in"));
    response.setRefreshToken(accessToken.getString("refresh_token"));
    response.setTokenType(accessToken.getString("token_type"));

    return response;
  }
コード例 #16
0
ファイル: WebServiceHelper.java プロジェクト: kvr2277/vinbass
  public String contactNumberClient(Business input) {

    String contactNumber = "";

    try {

      Client client = Client.create();
      WebResource webResource = client.resource("http://localhost:9280/NICUtil/rest/contact/post");

      ObjectMapper mapper = new ObjectMapper();
      ClientResponse response =
          webResource
              .type("application/json")
              .post(ClientResponse.class, mapper.writeValueAsString(input));

      if (response.getStatus() != 201) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
      }

      System.out.println("**Web Service Successful in helper**\n\n");
      contactNumber = response.getEntity(String.class);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return contactNumber;
  }
コード例 #17
0
ファイル: WebServiceHelper.java プロジェクト: kvr2277/vinbass
  public String fileUploadClient(MultipartFile mpf) {

    String filePath = "";
    Client client = Client.create();
    WebResource webResource = client.resource("http://localhost:9280/NICUtil/rest/contact/upload");
    byte[] logo = null;

    try {
      // logo = FileUtils.readFileToByteArray(file);
      logo = mpf.getBytes();
    } catch (IOException e1) {

      e1.printStackTrace();
    }

    // Construct a MultiPart with two body parts
    MultiPart multiPart =
        new MultiPart().bodyPart(new BodyPart(logo, MediaType.APPLICATION_OCTET_STREAM_TYPE));

    // POST the request
    try {
      ClientResponse response =
          webResource.type("multipart/mixed").post(ClientResponse.class, multiPart);
      filePath = response.getEntity(String.class);

      System.out.println("id is " + filePath);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return filePath;
  }
コード例 #18
0
  @Test
  public void testMember() throws InterruptedException, JSONException {
    // The member must be unlocked to begin the test
    String accessToken =
        getAccessTokenWithScopePath(
            ScopePathType.READ_LIMITED,
            lockedClientId,
            lockedClientSecret,
            lockedClientRedirectUri);
    ClientResponse getAllResponse = memberV2ApiClient.getEmails(user1OrcidId, accessToken);
    assertNotNull(getAllResponse);
    Emails emails = getAllResponse.getEntity(Emails.class);
    assertNotNull(emails);
    assertNotNull(emails.getEmails());
    assertFalse(emails.getEmails().isEmpty());

    // Lock and try to get authorization code
    adminLockAccount(adminUserName, adminPassword, memberId);
    lookForErrorsOnAuthorizationCodePage(
        lockedClientId, ScopePathType.READ_LIMITED.value(), lockedClientRedirectUri);

    // Try to use access token while the client is locked
    getAllResponse = memberV2ApiClient.getEmails(user1OrcidId, accessToken);
    assertNotNull(getAllResponse);

    // unlock to finish
    adminUnlockAccount(adminUserName, adminPassword, memberId);
  }
コード例 #19
0
  private FileMetaData getFileContentInfo(File file) {
    try {
      MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
      queryParams.add("redirect", "meta");
      ClientResponse resp =
          getRootApiWebResource()
              .path("files")
              .path(String.valueOf(file.getId()))
              .path("content")
              .queryParams(queryParams)
              .accept(MediaType.APPLICATION_OCTET_STREAM)
              .accept(MediaType.TEXT_HTML)
              .accept(MediaType.APPLICATION_XHTML_XML)
              .get(ClientResponse.class);

      String sResp = resp.getEntity(String.class);
      FileMetaData fileInfo =
          mapper.readValue(
              mapper.readValue(sResp, JsonNode.class).findPath(RESPONSE).toString(),
              FileMetaData.class);
      logger.info(fileInfo.toString());
      return fileInfo;
    } catch (BaseSpaceException bs) {
      throw bs;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
コード例 #20
0
  @Test
  public void testProcessEndtimeUpdate() throws Exception {
    scheduleProcess();
    waitForBundleStart(Job.Status.RUNNING);

    ClientResponse response =
        this.service
            .path("api/entities/definition/process/" + processName)
            .header("Remote-User", REMOTE_USER)
            .accept(MediaType.TEXT_XML)
            .get(ClientResponse.class);
    Process process =
        (Process)
            EntityType.PROCESS
                .getUnmarshaller()
                .unmarshal(new StringReader(response.getEntity(String.class)));

    Validity processValidity = process.getClusters().getClusters().get(0).getValidity();
    processValidity.setEnd(new Date(new Date().getTime() + 60 * 60 * 1000));
    File tmpFile = getTempFile();
    EntityType.PROCESS.getMarshaller().marshal(process, tmpFile);
    response =
        this.service
            .path("api/entities/update/process/" + processName)
            .header("Remote-User", REMOTE_USER)
            .accept(MediaType.TEXT_XML)
            .post(ClientResponse.class, getServletInputStream(tmpFile.getAbsolutePath()));
    assertSuccessful(response);

    // Assert that update does not create new bundle
    List<BundleJob> bundles = getBundles();
    Assert.assertEquals(bundles.size(), 1);
  }
コード例 #21
0
  public void testNodeHelper(String path, String media) throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    HashMap<String, String> hash = addAppContainers(app);
    Application app2 = new MockApp(2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);

    ClientResponse response =
        r.path("ws").path("v1").path("node").path(path).accept(media).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 2, appInfo.length());
    String id = appInfo.getJSONObject(0).getString("id");
    if (id.matches(app.getAppId().toString())) {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app, hash);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app2, hash2);
    } else {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app, hash);
    }
  }
コード例 #22
0
 public static void main(String[] args) {
   Client c = Client.create();
   String v1 = "http://www.diachron-fp7.eu/resource/recordset/efo/2.34";
   String v2 = "http://www.diachron-fp7.eu/resource/recordset/efo/2.35";
   boolean ingest = true;
   String ip = "139.91.183.48";
   ip = "localhost";
   WebResource r = c.resource("http://" + ip + ":8181/ForthMaven-1.0/diachron/change_detection");
   String input =
       "{ \"Old_Version\" : \""
           + v1
           + "\", "
           + "\"New_Version\" : \""
           + v2
           + "\", "
           + "\"Ingest\" : "
           + ingest
           + ", "
           + "\"Complex_Changes\" : [ ] }";
   ClientResponse response =
       r.type(MediaType.APPLICATION_JSON)
           .accept(MediaType.APPLICATION_JSON)
           .post(ClientResponse.class, input);
   System.out.println(response.getEntity(String.class));
   System.out.println(response.getStatus());
 }
コード例 #23
0
  @Test
  public void testGetEntityDefinition() throws Exception {
    ClientResponse response;
    Map<String, String> overlay = getUniqueOverlay();

    response = submitToIvory(CLUSTER_FILE_TEMPLATE, overlay, EntityType.CLUSTER);
    assertSuccessful(response);

    response = submitToIvory(FEED_TEMPLATE1, overlay, EntityType.FEED);
    assertSuccessful(response);

    response =
        this.service
            .path("api/entities/definition/feed/" + overlay.get("inputFeedName"))
            .header("Remote-User", REMOTE_USER)
            .accept(MediaType.TEXT_XML)
            .get(ClientResponse.class);

    String feedXML = response.getEntity(String.class);
    try {
      Feed result = (Feed) unmarshaller.unmarshal(new StringReader(feedXML));
      Assert.assertEquals(result.getName(), overlay.get("inputFeedName"));
    } catch (JAXBException e) {
      Assert.fail("Reponse " + feedXML + " is not valid", e);
    }
  }
コード例 #24
0
  @Test
  public void testNodeAppsState() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    addAppContainers(app);
    MockApp app2 = new MockApp("foo", 1234, 2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);
    app2.setState(ApplicationState.RUNNING);

    ClientResponse response =
        r.path("ws")
            .path("v1")
            .path("node")
            .path("apps")
            .queryParam("state", ApplicationState.RUNNING.toString())
            .accept(MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);

    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 1, appInfo.length());
    verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
  }
コード例 #25
0
  @Test(
      dependsOnMethods = {
        "testListEffectors",
        "testFetchApplicationsAndEntity",
        "testTriggerSampleEffector",
        "testListApplications",
        "testReadEachSensor",
        "testPolicyWhichCapitalizes",
        "testLocatedLocation"
      })
  public void testDeleteApplication() throws TimeoutException, InterruptedException {
    waitForPageFoundResponse("/v1/applications/simple-app", ApplicationSummary.class);
    Collection<Application> apps = getManagementContext().getApplications();
    log.info("Deleting simple-app from " + apps);
    int size = apps.size();

    ClientResponse response =
        client().resource("/v1/applications/simple-app").delete(ClientResponse.class);

    assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode());
    TaskSummary task = response.getEntity(TaskSummary.class);
    assertTrue(task.getDescription().toLowerCase().contains("destroy"), task.getDescription());
    assertTrue(task.getDescription().toLowerCase().contains("simple-app"), task.getDescription());

    waitForPageNotFoundResponse("/v1/applications/simple-app", ApplicationSummary.class);

    log.info("App appears gone, apps are: " + getManagementContext().getApplications());
    // more logging above, for failure in the check below

    Asserts.eventually(
        EntityFunctions.applications(getManagementContext()),
        Predicates.compose(Predicates.equalTo(size - 1), CollectionFunctionals.sizeFunction()));
  }
コード例 #26
0
  // verify the exception object default format is JSON
  @Test
  public void testNodeAppsStateInvalidDefault() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    addAppContainers(app);
    Application app2 = new MockApp("foo", 1234, 2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    addAppContainers(app2);

    try {
      r.path("ws")
          .path("v1")
          .path("node")
          .path("apps")
          .queryParam("state", "FOO_STATE")
          .get(JSONObject.class);
      fail("should have thrown exception on invalid user query");
    } catch (UniformInterfaceException ue) {
      ClientResponse response = ue.getResponse();

      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");
      verifyStateInvalidException(message, type, classname);
    }
  }
コード例 #27
0
  @Test(dependsOnMethods = "testSubmit")
  public void testGetDefinition() throws Exception {
    for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) {
      System.out.println("typeName = " + typeDefinition.typeName);

      WebResource resource = service.path("api/atlas/types").path(typeDefinition.typeName);

      ClientResponse clientResponse =
          resource
              .accept(Servlets.JSON_MEDIA_TYPE)
              .type(Servlets.JSON_MEDIA_TYPE)
              .method(HttpMethod.GET, ClientResponse.class);
      assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());

      String responseAsString = clientResponse.getEntity(String.class);
      Assert.assertNotNull(responseAsString);
      JSONObject response = new JSONObject(responseAsString);
      Assert.assertNotNull(response.get(AtlasClient.DEFINITION));
      Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

      String typesJson = response.getString(AtlasClient.DEFINITION);
      final TypesDef typesDef = TypesSerialization.fromJson(typesJson);
      List<HierarchicalTypeDefinition<ClassType>> hierarchicalTypeDefinitions =
          typesDef.classTypesAsJavaList();
      for (HierarchicalTypeDefinition<ClassType> classType : hierarchicalTypeDefinitions) {
        for (AttributeDefinition attrDef : classType.attributeDefinitions) {
          if ("name".equals(attrDef.name)) {
            assertEquals(attrDef.isIndexable, true);
            assertEquals(attrDef.isUnique, true);
          }
        }
      }
    }
  }
コード例 #28
0
  @Test
  public void testNodeSingleAppsXML() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    HashMap<String, String> hash = addAppContainers(app);
    Application app2 = new MockApp(2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    addAppContainers(app2);

    ClientResponse response =
        r.path("ws")
            .path("v1")
            .path("node")
            .path("apps")
            .path(app.getAppId().toString() + "/")
            .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 nodes = dom.getElementsByTagName("app");
    assertEquals("incorrect number of elements", 1, nodes.getLength());
    verifyNodeAppInfoXML(nodes, app, hash);
  }
コード例 #29
0
  @Test
  public void testSubmit() throws Exception {
    for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) {
      String typesAsJSON = TypesSerialization.toJson(typeDefinition);
      System.out.println("typesAsJSON = " + typesAsJSON);

      WebResource resource = service.path("api/atlas/types");

      ClientResponse clientResponse =
          resource
              .accept(Servlets.JSON_MEDIA_TYPE)
              .type(Servlets.JSON_MEDIA_TYPE)
              .method(HttpMethod.POST, ClientResponse.class, typesAsJSON);
      assertEquals(clientResponse.getStatus(), Response.Status.CREATED.getStatusCode());

      String responseAsString = clientResponse.getEntity(String.class);
      Assert.assertNotNull(responseAsString);

      JSONObject response = new JSONObject(responseAsString);
      JSONArray typesAdded = response.getJSONArray(AtlasClient.TYPES);
      assertEquals(typesAdded.length(), 1);
      assertEquals(typesAdded.getJSONObject(0).getString("name"), typeDefinition.typeName);
      Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));
    }
  }
コード例 #30
0
  /**
   * @param path
   * @param expectedValue
   */
  private void shouldRetrieveResourceWithValue(final String path, final String expectedValue) {
    final ClientResponse res =
        root().path(path).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);

    assertEquals(ClientResponse.Status.OK, res.getClientResponseStatus());
    assertEquals(expectedValue, res.getEntity(String.class));
  }