コード例 #1
0
  @Test
  public void testCantAddDuplicatedResearcherUrl()
      throws InterruptedException, JSONException, URISyntaxException {
    String accessToken =
        getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri);
    assertNotNull(accessToken);
    Long now = System.currentTimeMillis();
    ResearcherUrl rUrlToCreate = new ResearcherUrl();
    rUrlToCreate.setUrl(new Url("http://newurl.com/" + now));
    rUrlToCreate.setUrlName("url-name-" + System.currentTimeMillis());
    rUrlToCreate.setVisibility(Visibility.PUBLIC);

    // Create it
    ClientResponse postResponse =
        memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus());

    // Add it again
    postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CONFLICT.getStatusCode(), postResponse.getStatus());

    // Check it can be created by other client
    String otherClientToken =
        getAccessToken(this.client2ClientId, this.client2ClientSecret, this.client2RedirectUri);
    postResponse =
        memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, otherClientToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus());
  }
コード例 #2
0
  static void testUpload(TestParams testParams) throws Exception {

    FormDataMultiPart part = new FormDataMultiPart();

    part.field(RestParams.COMMIT_ID, QUERY_PARAMS.get(RestParams.COMMIT_ID));
    part.field(RestParams.MODULE_GROUPID, QUERY_PARAMS.get(RestParams.MODULE_GROUPID));
    part.field(RestParams.MODULE_ARTIFACTID, QUERY_PARAMS.get(RestParams.MODULE_ARTIFACTID));
    part.field(RestParams.MODULE_VERSION, QUERY_PARAMS.get(RestParams.MODULE_VERSION));
    part.field(RestParams.USERNAME, QUERY_PARAMS.get(RestParams.USERNAME));
    part.field(RestParams.VCS_REPO_URL, "ssh://[email protected]:7999/chop/main.git");
    part.field(RestParams.TEST_PACKAGE, QUERY_PARAMS.get(RestParams.TEST_PACKAGE));
    part.field(RestParams.MD5, "d7d4829506f6cb8c0ab2da9cb1daca02");

    File tmpFile = File.createTempFile("runner", "jar");
    FileInputStream in = new FileInputStream(tmpFile);
    FormDataBodyPart body =
        new FormDataBodyPart(RestParams.CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE);
    part.bodyPart(body);

    ClientResponse response =
        testParams
            .addQueryParameters(QUERY_PARAMS)
            .setEndpoint(UploadResource.ENDPOINT)
            .newWebResource()
            .path("/runner")
            .type(MediaType.MULTIPART_FORM_DATA)
            .accept(MediaType.TEXT_PLAIN)
            .post(ClientResponse.class, part);

    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());

    assertEquals(UploadResource.SUCCESSFUL_TEST_MESSAGE, response.getEntity(String.class));

    tmpFile.delete();
  }
コード例 #3
0
  @Test
  public void testRestoreShouldReturnOkResponse() throws Exception {
    doReturn(new BackupInfo()).when(mockFacade).restore(any(BackupConfig.class));

    Response result = service.restore(ARTIFACT_NAME, "");
    assertEquals(result.getStatus(), Response.Status.CREATED.getStatusCode());
  }
コード例 #4
0
  @Test
  public void testAddNodeShouldReturnOkResponse() throws Exception {
    doReturn(new NodeInfo()).when(mockFacade).addNode("dns");

    Response result = service.addNode("dns");
    assertEquals(result.getStatus(), Response.Status.CREATED.getStatusCode());
  }
コード例 #5
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));
    }
  }
コード例 #6
0
  @Test(dependsOnMethods = "testGetTraitNames")
  public void testAddTrait() throws Exception {
    traitName = "PII_Trait" + randomString();
    HierarchicalTypeDefinition<TraitType> piiTrait =
        TypesUtil.createTraitTypeDef(traitName, ImmutableList.<String>of());
    String traitDefinitionAsJSON = TypesSerialization$.MODULE$.toJson(piiTrait, true);
    LOG.debug("traitDefinitionAsJSON = " + traitDefinitionAsJSON);
    createType(traitDefinitionAsJSON);

    Struct traitInstance = new Struct(traitName);
    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));
  }
コード例 #7
0
  @Test
  public void testUpdateCodenvyProperty() throws Exception {
    Map<String, String> properties = ImmutableMap.of("x", "y");

    Response response = service.updateCodenvyProperties(properties);
    assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
    verify(mockFacade).updateArtifactConfig(any(Artifact.class), anyMap());
  }
コード例 #8
0
  public void addCatalog() {
    Response response = services.getCatalogService().request().post(Entity.xml(catalogItem));

    Response.StatusType statusInfo = response.getStatusInfo();

    if (statusInfo.getStatusCode() == Response.Status.CREATED.getStatusCode())
      status = "User added successfully";
    else status = statusInfo.getReasonPhrase();
  }
コード例 #9
0
  @Test
  public void testAddTrialSubscriptionShouldReturnOkResponse() throws Exception {
    SaasUserCredentials testUserCredentials =
        new SaasUserCredentials(TEST_ACCESS_TOKEN, TEST_ACCOUNT_ID);
    service.saasUserCredentials = testUserCredentials;

    Response result = service.addTrialSubscription();
    assertEquals(result.getStatus(), Response.Status.CREATED.getStatusCode());
    verify(mockFacade).addTrialSaasSubscription(testUserCredentials);
  }
コード例 #10
0
  @Test
  public void createCollectionObject() {
    long identifier = this.createIdentifier();

    CollectionObject collectionObject = createCollectionObject(identifier);
    ClientResponse<Response> res = collectionObjectClient.createCollectionObject(collectionObject);
    Assert.assertEquals(res.getStatus(), Response.Status.CREATED.getStatusCode());

    // store updateId locally for "update" test
    if (updateId == null) updateId = extractId(res);
    else deleteId = extractId(res);
  }
コード例 #11
0
ファイル: AirplaneIT.java プロジェクト: pflueras/restjug
  private Airplane addAirplane(Airplane airplane) {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(rootURI + "/airplanes");

    Response response = target.request().post(Entity.entity(airplane, MediaType.APPLICATION_JSON));
    Airplane updated = response.readEntity(Airplane.class);

    response.close();

    Assert.assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());

    return updated;
  }
コード例 #12
0
  /* post(null) /wishlists/wishlistId/media */
  @Test
  public void testPostByWishlistIdMedia() throws FileNotFoundException {
    Response response = createWishlistMedia();

    // Verify
    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
    String location =
        response
            .getHeaderString("location")
            .substring(response.getHeaderString("location").lastIndexOf("/") + 1);
    instanceListMedia.add(location);
    assertNotNull(location);
  }
コード例 #13
0
 @Test
 public void testSaveAccount() {
   Account account = new Account();
   account.setUsername("testUser");
   Client client = ClientBuilder.newClient();
   WebTarget target =
       client.target("http://localhost:8080/employee-manager-container/rest/account");
   Response response =
       target
           .request(MediaType.APPLICATION_JSON)
           .post(Entity.entity(account, MediaType.APPLICATION_JSON_TYPE));
   assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
 }
コード例 #14
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");
  }
コード例 #15
0
  @Test
  public void testAddMultipleResearcherUrlAndGetThem()
      throws InterruptedException, JSONException, URISyntaxException {
    String accessToken =
        getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri);
    assertNotNull(accessToken);
    Long now = System.currentTimeMillis();
    ResearcherUrl rUrlToCreate = new ResearcherUrl();
    rUrlToCreate.setVisibility(Visibility.PUBLIC);

    for (int i = 0; i < 3; i++) {
      // Change the name
      rUrlToCreate.setUrlName("url-name-" + now + "-" + i);
      rUrlToCreate.setUrl(new Url("http://newurl.com/" + now + "/" + i));
      // Create it
      ClientResponse postResponse =
          memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
      assertNotNull(postResponse);
      assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus());
    }

    ClientResponse getAllResponse =
        memberV2ApiClient.getResearcherUrls(this.user1OrcidId, accessToken);
    assertNotNull(getAllResponse);
    ResearcherUrls researcherUrls = getAllResponse.getEntity(ResearcherUrls.class);
    assertNotNull(researcherUrls);
    assertNotNull(researcherUrls.getPath());
    assertTrue(researcherUrls.getPath().contains(this.user1OrcidId));
    assertNotNull(researcherUrls.getResearcherUrls());

    boolean found1 = false, found2 = false, found3 = false;

    for (ResearcherUrl rUrl : researcherUrls.getResearcherUrls()) {
      if (rUrl.getUrlName().equals("url-name-" + now + "-0")) {
        found1 = true;
      } else if (rUrl.getUrlName().equals("url-name-" + now + "-1")) {
        found2 = true;
      } else if (rUrl.getUrlName().equals("url-name-" + now + "-2")) {
        found3 = true;
      }
    }

    assertTrue(found1 && found2 && found3);

    // Clean
    for (ResearcherUrl rUrl : researcherUrls.getResearcherUrls()) {
      memberV2ApiClient.deletePeerReviewXml(this.user1OrcidId, rUrl.getPutCode(), accessToken);
    }
  }
コード例 #16
0
  public static void main(String... args) {
    Client client = createClient();

    Payment payment = new Payment("123", "567", 10005, "Reimbursement for dinner");
    Entity<Payment> entity = Entity.entity(payment, MediaType.APPLICATION_JSON_TYPE);
    Invocation request = client.target(PAYMENTS_URL).request().buildPut(entity);

    Response response = request.invoke();

    int status = response.getStatus();
    if (Response.Status.CREATED.getStatusCode() == status) {
      System.out.println("Payment sent");
    } else {
      System.out.println("Error sending payment: " + status);
    }
  }
コード例 #17
0
  static void testSetup(TestParams testParams) {
    ClientResponse response =
        testParams
            .addQueryParameters(QUERY_PARAMS)
            .setEndpoint(SetupResource.ENDPOINT)
            .newWebResource()
            .queryParam(RestParams.RUNNER_COUNT, "5")
            .path("/stack")
            .type(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .post(ClientResponse.class);

    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());

    assertEquals("\"NotFound\"", response.getEntity(String.class));
  }
コード例 #18
0
  @Test
  public void testTryingToAddInvalidResearcherUrls()
      throws InterruptedException, JSONException, URISyntaxException {
    String accessToken =
        getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri);
    assertNotNull(accessToken);
    ResearcherUrl rUrlToCreate = new ResearcherUrl();
    rUrlToCreate.setUrl(new Url(""));
    rUrlToCreate.setUrlName("");
    // Create
    ClientResponse postResponse =
        memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), postResponse.getStatus());

    String _351Chars = new String();
    for (int i = 0; i < 531; i++) {
      _351Chars += "a";
    }

    rUrlToCreate.setUrl(new Url(_351Chars));
    postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), postResponse.getStatus());

    rUrlToCreate.setUrl(new Url("http://myurl.com"));
    rUrlToCreate.setUrlName(_351Chars);
    postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), postResponse.getStatus());

    rUrlToCreate.setUrlName("The name");
    postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus());

    // Read it to delete it
    ClientResponse getResponse =
        memberV2ApiClient.viewLocationXml(postResponse.getLocation(), accessToken);
    assertEquals(Response.Status.OK.getStatusCode(), getResponse.getStatus());
    ResearcherUrl gotResearcherUrl = getResponse.getEntity(ResearcherUrl.class);
    ClientResponse deleteResponse =
        memberV2ApiClient.deleteResearcherUrl(
            this.user1OrcidId, gotResearcherUrl.getPutCode(), accessToken);
    assertEquals(Response.Status.NO_CONTENT.getStatusCode(), deleteResponse.getStatus());
  }
コード例 #19
0
  @Test
  public void testPostDomainFile() throws URISyntaxException {
    WebResource resource = resource();
    resource.path("testClientId").path("target").path("problem").delete();

    File targetProblemFile = new File(ClassLoader.getSystemResource("pa_target_prob.txt").toURI());
    FormDataMultiPart targetProblemForm = new FormDataMultiPart();
    targetProblemForm.bodyPart(
        new FileDataBodyPart("file", targetProblemFile, MediaType.valueOf(MediaType.TEXT_PLAIN)));
    ClientResponse response =
        resource
            .path("testClientId")
            .path("target")
            .path("problem")
            .type(MediaType.MULTIPART_FORM_DATA_TYPE)
            .post(ClientResponse.class, targetProblemForm);

    assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
  }
コード例 #20
0
  @Test
  public void testCreateReport() {
    // Setup
    Integer jobId = 1;
    CommandRegistry mockCommandRegistry = createMockCommandRegistry();
    ReportCommand reportCommand = createReportCommand();
    expect(mockCommandRegistry.<ReportCommandOptions>newCommand(reportCommand.getName()))
        .andReturn(reportCommand)
        .atLeastOnce();

    CommandJobService mockCommandJobService = createMockCommandJobService();
    expect(
            mockCommandJobService.launchCommand(
                eqCommandJob(createCommandJob(jobId, reportCommand, null))))
        .andReturn(jobId)
        .atLeastOnce();

    WebShellResource sut = new WebShellResource();
    sut.setCommandJobService(mockCommandJobService);
    sut.setCommandRegistry(mockCommandRegistry);

    replay(mockCommandRegistry, mockCommandJobService);

    // Exercise
    ReportCommandOptionsDto optionsDto = createReportCommandOptionsDto("test report", "project1");
    Response response = sut.createReport(optionsDto);

    // Verify mocks
    verify(mockCommandRegistry, mockCommandJobService);

    // Verify that the options in the dto were applied to the launched command
    ReportCommandOptions importOptions = reportCommand.getOptions();
    assertThat(optionsDto.getName()).isEqualTo(importOptions.getName());

    // Verify that the HTTP response code was CREATED (201) and that the "Location"
    // header was set to '/shell/command/{jobId}'.
    assertThat(response.getStatus()).isEqualTo(Response.Status.CREATED.getStatusCode());
    assertThat(response.getMetadata().getFirst("Location").toString())
        .isEqualTo("/shell/command/" + jobId);
  }
コード例 #21
0
  @Test
  public void testSubmitSingleEntity() throws Exception {
    Referenceable databaseInstance = new Referenceable(DATABASE_TYPE);
    databaseInstance.set("name", randomString());
    databaseInstance.set("description", randomString());

    ClientResponse clientResponse =
        service
            .path(ENTITIES)
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(
                HttpMethod.POST,
                ClientResponse.class,
                InstanceSerialization.toJson(databaseInstance, true));
    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));
  }
コード例 #22
0
ファイル: RestSBControllerImpl.java プロジェクト: gunine/onos
/** The implementation of RestSBController. */
@Component(immediate = true)
@Service
public class RestSBControllerImpl implements RestSBController {

  private static final Logger log = LoggerFactory.getLogger(RestSBControllerImpl.class);
  private static final String APPLICATION = "application/";
  private static final String XML = "xml";
  private static final String JSON = "json";
  private static final String DOUBLESLASH = "//";
  private static final String COLON = ":";
  private static final int STATUS_OK = Response.Status.OK.getStatusCode();
  private static final int STATUS_CREATED = Response.Status.CREATED.getStatusCode();
  private static final int STATUS_ACCEPTED = Response.Status.ACCEPTED.getStatusCode();
  private static final String SLASH = "/";

  private final Map<DeviceId, RestSBDevice> deviceMap = new ConcurrentHashMap<>();
  Client client;

  @Activate
  public void activate(ComponentContext context) {
    client = Client.create();
    log.info("Started");
  }

  @Deactivate
  public void deactivate() {
    deviceMap.clear();
    log.info("Stopped");
  }

  @Override
  public Map<DeviceId, RestSBDevice> getDevices() {
    return deviceMap;
  }

  @Override
  public RestSBDevice getDevice(DeviceId deviceInfo) {
    return deviceMap.get(deviceInfo);
  }

  @Override
  public RestSBDevice getDevice(IpAddress ip, int port) {
    for (DeviceId info : deviceMap.keySet()) {
      if (IpAddress.valueOf(info.uri().getHost()).equals(ip) && info.uri().getPort() == port) {
        return deviceMap.get(info);
      }
    }
    return null;
  }

  @Override
  public void addDevice(RestSBDevice device) {
    deviceMap.put(device.deviceId(), device);
  }

  @Override
  public void removeDevice(RestSBDevice device) {
    deviceMap.remove(device.deviceId());
  }

  @Override
  public boolean post(DeviceId device, String request, InputStream payload, String mediaType) {
    WebResource webResource = getWebResource(device, request);

    ClientResponse response = null;
    if (payload != null) {
      try {
        response =
            webResource
                .accept(mediaType)
                .post(ClientResponse.class, IOUtils.toString(payload, StandardCharsets.UTF_8));
      } catch (IOException e) {
        log.error(
            "Cannot do POST {} request on device {} because can't read payload", request, device);
      }
    } else {
      response = webResource.accept(mediaType).post(ClientResponse.class);
    }
    return checkReply(response);
  }

  @Override
  public boolean put(DeviceId device, String request, InputStream payload, String mediaType) {

    WebResource webResource = getWebResource(device, request);
    ClientResponse response = null;
    if (payload != null) {
      try {
        response =
            webResource
                .accept(mediaType)
                .put(ClientResponse.class, IOUtils.toString(payload, StandardCharsets.UTF_8));
      } catch (IOException e) {
        log.error(
            "Cannot do PUT {} request on device {} because can't read payload", request, device);
      }
    } else {
      response = webResource.accept(mediaType).put(ClientResponse.class);
    }
    return checkReply(response);
  }

  @Override
  public InputStream get(DeviceId device, String request, String mediaType) {
    WebResource webResource = getWebResource(device, request);
    String type;
    switch (mediaType) {
      case XML:
        type = MediaType.APPLICATION_XML;
        break;
      case JSON:
        type = MediaType.APPLICATION_JSON;
        break;
      default:
        throw new IllegalArgumentException("Unsupported media type " + mediaType);
    }
    return new ByteArrayInputStream(
        webResource
            .accept(type)
            .get(ClientResponse.class)
            .getEntity(String.class)
            .getBytes(StandardCharsets.UTF_8));
  }

  @Override
  public boolean delete(DeviceId device, String request, InputStream payload, String mediaType) {
    WebResource webResource = getWebResource(device, request);
    ClientResponse response = null;
    if (payload != null) {
      try {
        response =
            webResource
                .accept(mediaType)
                .delete(ClientResponse.class, IOUtils.toString(payload, StandardCharsets.UTF_8));
      } catch (IOException e) {
        log.error(
            "Cannot do PUT {} request on device {} because can't read payload", request, device);
      }
    } else {
      response = webResource.accept(mediaType).delete(ClientResponse.class);
    }
    return checkReply(response);
  }

  private WebResource getWebResource(DeviceId device, String request) {
    return Client.create()
        .resource(
            deviceMap.get(device).protocol()
                + COLON
                + DOUBLESLASH
                + deviceMap.get(device).ip().toString()
                + COLON
                + deviceMap.get(device).port()
                + SLASH
                + request);
  }

  private boolean checkReply(ClientResponse response) {
    if (response != null) {
      if (response.getStatus() == STATUS_OK
          || response.getStatus() == STATUS_CREATED
          || response.getStatus() == STATUS_ACCEPTED) {
        return true;
      } else {
        log.error("Failed request: HTTP error code : " + response.getStatus());
        return false;
      }
    }
    log.error("Null reply from device");
    return false;
  }
}
コード例 #23
0
  /**
   * Write the specified document to the DDS using RESTful API.
   *
   * @param document The DDS meta-data wrapped document to write to DDS.
   * @throws UnsupportedEncodingException If the name of the document (nsaId, type, documentId)
   *     cannot be URL encoded.
   * @throws IOException If the document cannot be written to the DDS.
   */
  private void writeDocument(DocumentType document)
      throws UnsupportedEncodingException, IOException {
    // Wrap the provided DDS document in a JAXB element for sending.
    JAXBElement<DocumentType> request = ddsFactory.createDocument(document);

    // Build the full document path based on identifiers.
    WebTarget path;
    try {
      path =
          dds.path(URLEncoder.encode(document.getNsa().trim(), "UTF-8"))
              .path(URLEncoder.encode(document.getType().trim(), "UTF-8"))
              .path(URLEncoder.encode(document.getId().trim(), "UTF-8"));
    } catch (UnsupportedEncodingException ex) {
      log.error(
          "Could not format URL "
              + document.getNsa()
              + "/"
              + document.getType()
              + "/"
              + document.getId(),
          ex);
      throw ex;
    }

    // Determine of the NSA document already exists.
    Response response = path.request(NsiConstants.NSI_DDS_V1_XML).get();
    int status = response.getStatus();
    response.close();

    // If the document exists we modify it through PUT, otherwise we use POST.
    if (Response.Status.OK.getStatusCode() == status) {
      // Document already exists so we will need to modify it.
      Response result =
          path.request(NsiConstants.NSI_DDS_V1_XML)
              .put(
                  Entity.entity(
                      new GenericEntity<JAXBElement<DocumentType>>(request) {},
                      NsiConstants.NSI_DDS_V1_XML));
      status = result.getStatus();
      result.close();
      if (Response.Status.OK.getStatusCode() != status) {
        throw new IOException(error("PUT", status, path.getUri().toASCIIString()));
      }
    } else if (Response.Status.NOT_FOUND.getStatusCode() == response.getStatus()) {
      // Document does not exist so we will need to add it.  We POST the
      // new document under "/documents" and not the full path of the
      // document.
      Response result =
          dds.request(NsiConstants.NSI_DDS_V1_XML)
              .post(
                  Entity.entity(
                      new GenericEntity<JAXBElement<DocumentType>>(request) {},
                      NsiConstants.NSI_DDS_V1_XML));
      status = result.getStatus();
      result.close();
      if (Response.Status.CREATED.getStatusCode() != status) {
        throw new IOException(error("POST", status, path.getUri().toASCIIString()));
      }
    } else {
      throw new IOException(error("GET", status, path.getUri().toASCIIString()));
    }
  }
コード例 #24
0
  @Test
  public void testResearcherUrl() throws InterruptedException, JSONException, URISyntaxException {
    String accessToken =
        getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri);
    assertNotNull(accessToken);
    ResearcherUrl rUrlToCreate =
        (ResearcherUrl)
            unmarshallFromPath(
                "/record_2.0_rc2/samples/researcher-url-2.0_rc2.xml", ResearcherUrl.class);
    assertNotNull(rUrlToCreate);
    Long time = System.currentTimeMillis();
    rUrlToCreate.setCreatedDate(null);
    rUrlToCreate.setLastModifiedDate(null);
    rUrlToCreate.setPath(null);
    rUrlToCreate.setPutCode(null);
    rUrlToCreate.setSource(null);
    rUrlToCreate.setUrl(new Url(rUrlToCreate.getUrl().getValue() + time));
    rUrlToCreate.setUrlName(String.valueOf(time));

    // Create
    ClientResponse postResponse =
        memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken);
    assertNotNull(postResponse);
    assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus());
    String locationPath = postResponse.getLocation().getPath();
    assertTrue(
        "Location header path should match pattern, but was " + locationPath,
        locationPath.matches(".*/v2.0_rc2/" + user1OrcidId + "/researcher-urls/\\d+"));

    // Read
    ClientResponse getResponse =
        memberV2ApiClient.viewLocationXml(postResponse.getLocation(), accessToken);
    assertEquals(Response.Status.OK.getStatusCode(), getResponse.getStatus());
    ResearcherUrl gotResearcherUrl = getResponse.getEntity(ResearcherUrl.class);
    assertNotNull(gotResearcherUrl);
    assertNotNull(gotResearcherUrl.getPutCode());
    assertNotNull(gotResearcherUrl.getSource());
    assertNotNull(gotResearcherUrl.getCreatedDate());
    assertNotNull(gotResearcherUrl.getLastModifiedDate());
    assertEquals(this.client1ClientId, gotResearcherUrl.getSource().retrieveSourcePath());
    assertEquals("http://site1.com/" + time, gotResearcherUrl.getUrl().getValue());
    assertEquals(String.valueOf(time), gotResearcherUrl.getUrlName());
    assertEquals("public", gotResearcherUrl.getVisibility().value());

    // Update
    LastModifiedDate initialLastModified = gotResearcherUrl.getLastModifiedDate();
    Long currentTime = System.currentTimeMillis();
    gotResearcherUrl.setUrlName(gotResearcherUrl.getUrlName() + " - " + currentTime);
    gotResearcherUrl.getUrl().setValue(gotResearcherUrl.getUrl().getValue() + currentTime);
    gotResearcherUrl.setVisibility(Visibility.LIMITED);
    ClientResponse updatedResearcherUrlResponse =
        memberV2ApiClient.updateResearcherUrls(this.user1OrcidId, gotResearcherUrl, accessToken);
    assertNotNull(updatedResearcherUrlResponse);
    assertEquals(Response.Status.OK.getStatusCode(), updatedResearcherUrlResponse.getStatus());
    ResearcherUrl updatedResearcherUrl =
        updatedResearcherUrlResponse.getEntity(ResearcherUrl.class);
    assertNotNull(updatedResearcherUrl);
    assertEquals(
        "http://site1.com/" + time + currentTime, updatedResearcherUrl.getUrl().getValue());
    assertEquals(String.valueOf(time) + " - " + currentTime, updatedResearcherUrl.getUrlName());
    // Keep it public, since it is more restrictive than the user visibility
    // default
    assertEquals("public", updatedResearcherUrl.getVisibility().value());
    assertFalse(initialLastModified.equals(updatedResearcherUrl.getLastModifiedDate()));

    // Delete
    ClientResponse deleteResponse =
        memberV2ApiClient.deleteResearcherUrl(
            this.user1OrcidId, gotResearcherUrl.getPutCode(), accessToken);
    assertEquals(Response.Status.NO_CONTENT.getStatusCode(), deleteResponse.getStatus());
  }