@Test(
      dataProvider =
          com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
              + "buildersClientDataDataProvider")
  public void testCreateId(RestClient restClient, RestliRequestOptions requestOptions)
      throws RemoteInvocationException {
    Greeting greeting = new Greeting();
    greeting.setMessage("Hello there!");
    greeting.setTone(Tone.FRIENDLY);

    final GreetingsRequestBuilders builders = new GreetingsRequestBuilders(requestOptions);

    CreateIdRequest<Long, Greeting> createRequest = builders.create().input(greeting).build();
    Response<IdResponse<Long>> response = restClient.sendRequest(createRequest).getResponse();
    Assert.assertNull(response.getHeader(RestConstants.HEADER_CONTENT_TYPE));
    @SuppressWarnings("unchecked")
    long id = response.getEntity().getId();
    @SuppressWarnings("deprecation")
    String stringId = response.getId();
    Assert.assertEquals(id, Long.parseLong(stringId));

    Request<Greeting> getRequest = builders.get().id(id).build();
    Response<Greeting> getResponse = restClient.sendRequest(getRequest).getResponse();
    Greeting responseGreeting = getResponse.getEntity();

    Assert.assertEquals(responseGreeting.getMessage(), greeting.getMessage());
    Assert.assertEquals(responseGreeting.getTone(), greeting.getTone());
  }
 /** retrieve album */
 private void getAlbumSummary(PrintWriter respWriter, long newAlbumId)
     throws RemoteInvocationException {
   final Request<Album> getReq = _albumBuilders.get().id(newAlbumId).build();
   final ResponseFuture<Album> getFuture = _restClient.sendRequest(getReq);
   final Response<Album> getResp = getFuture.getResponse();
   respWriter.println("Album: " + getResp.getEntity().toString());
 }
 @Test(
     dataProvider =
         com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
             + "clientDataDataProvider")
 public void testGet(RestClient restClient, RootBuilderWrapper<Long, Greeting> builders)
     throws RemoteInvocationException {
   Request<Greeting> request = builders.get().id(1L).build();
   Response<Greeting> response = restClient.sendRequest(request).getResponse();
   Greeting greeting = response.getEntity();
   Assert.assertEquals(greeting.getId(), new Long(1));
 }
  private void testGetMain(
      RootBuilderWrapper.MethodBuilderWrapper<
              ComplexResourceKey<TyperefRecord, TwoPartKey>, TyperefRecord, TyperefRecord>
          requestBuilder)
      throws RemoteInvocationException {
    final ByteString byteData = ByteString.copy(new byte[] {0, 32, -95});
    Request<TyperefRecord> request = requestBuilder.id(getComplexKey(byteData)).build();
    ResponseFuture<TyperefRecord> future = getClient().sendRequest(request);
    Response<TyperefRecord> response = future.getResponse();

    Assert.assertEquals(response.getEntity().getBytes(), byteData);
  }
  private void partialUpdatePhoto(PrintWriter respWriter, long photoId)
      throws RemoteInvocationException {
    final Request<Photo> getReq = _photoBuilders.get().id(photoId).build();
    final ResponseFuture<Photo> getFuture = _restClient.sendRequest(getReq);
    final Response<Photo> getResp = getFuture.getResponse();
    final Photo originalPhoto = getResp.getEntity();

    final Photo updatedPhoto = new Photo().setTitle("Partially Updated Photo");
    final PatchRequest<Photo> patch = PatchGenerator.diff(originalPhoto, updatedPhoto);

    final Request<EmptyRecord> partialUpdateRequest =
        _photoBuilders.partialUpdate().id(photoId).input(patch).build();
    final int status = _restClient.sendRequest(partialUpdateRequest).getResponse().getStatus();
    respWriter.println("Partial update photo is successful: " + (status == 202));
  }
  @Test(
      dataProvider =
          com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
              + "clientDataDataProvider")
  public void testUpdate(RestClient restClient, RootBuilderWrapper<Long, Greeting> builders)
      throws RemoteInvocationException, CloneNotSupportedException {
    // GET
    Request<Greeting> request = builders.get().id(1L).build();
    Response<Greeting> greetingResponse1 = restClient.sendRequest(request).getResponse();

    String response1 = greetingResponse1.getEntity().getMessage();
    Assert.assertNotNull(response1);

    // POST
    Greeting greeting = new Greeting(greetingResponse1.getEntity().data().copy());
    greeting.setMessage(response1 + "Again");

    Request<EmptyRecord> writeRequest = builders.update().id(1L).input(greeting).build();
    Response<EmptyRecord> updateResponse = restClient.sendRequest(writeRequest).getResponse();
    Assert.assertNull(updateResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE));

    // GET again, to verify that our POST worked.
    Request<Greeting> request2 = builders.get().id(1L).build();
    Response<Greeting> greetingResponse2 = restClient.sendRequest(request2).getResponse();

    String response2 = greetingResponse2.getEntity().getMessage();
    Assert.assertEquals(response2, response1 + "Again");
  }
  private long createPhoto(PrintWriter respWriter) throws RemoteInvocationException {
    // make create photo request and send with the rest client synchronously
    // response of create request does not have body, therefore use EmptyRecord as template

    // create an instance of photo pragmatically
    // this resembles to photo-create.json
    final LatLong newLatLong = new LatLong().setLatitude(37.42394f).setLongitude(-122.0708f);
    final EXIF newExif = new EXIF().setLocation(newLatLong);
    final Photo newPhoto =
        new Photo().setTitle("New Photo").setFormat(PhotoFormats.PNG).setExif(newExif);

    final Request<EmptyRecord> createReq1 = _photoBuilders.create().input(newPhoto).build();
    final ResponseFuture<EmptyRecord> createFuture1 = _restClient.sendRequest(createReq1);
    // Future.getResource() blocks until server responds
    final Response<EmptyRecord> createResp1 = createFuture1.getResponse();

    // HTTP header Location also shows the relative URI of the created resource
    final long newPhotoId = Long.parseLong(createResp1.getId());
    respWriter.println("New photo ID: " + newPhotoId);

    return newPhotoId;
  }
  @Test(
      dataProvider =
          com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
              + "clientDataDataProvider")
  public void testAction(RestClient restClient, RootBuilderWrapper<Long, Greeting> builders)
      throws RemoteInvocationException {
    Request<Greeting> request =
        builders
            .<Greeting>action("SomeAction")
            .id(1L)
            .setActionParam("A", 1)
            .setActionParam("B", "")
            .setActionParam("C", new TransferOwnershipRequest())
            .setActionParam("D", new TransferOwnershipRequest())
            .setActionParam("E", 3)
            .build();

    Response<Greeting> response = restClient.sendRequest(request).getResponse();

    Greeting greeting = response.getEntity();
    Assert.assertEquals(greeting.getMessage(), "This is a newly created greeting");
  }
  @Test(
      dataProvider =
          com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
              + "requestBuilderDataProvider")
  public void testPostsWithCharset(RootBuilderWrapper<Long, Greeting> builders)
      throws RemoteInvocationException {
    RestClient restClient = new RestClient(CLIENT, URI_PREFIX);

    Request<Greeting> request =
        builders
            .<Greeting>action("SomeAction")
            .id(1L)
            .setActionParam("A", 1)
            .setActionParam("B", "")
            .setActionParam("C", new TransferOwnershipRequest())
            .setActionParam("D", new TransferOwnershipRequest())
            .setActionParam("E", 3)
            .setHeader("Content-Type", "application/json; charset=UTF-8")
            .build();

    Response<Greeting> response = restClient.sendRequest(request).getResponse();

    Greeting actionGreeting = response.getEntity();
    Assert.assertEquals(actionGreeting.getMessage(), "This is a newly created greeting");

    Greeting createGreeting = new Greeting();
    createGreeting.setMessage("Hello there!");
    createGreeting.setTone(Tone.FRIENDLY);

    Request<EmptyRecord> createRequest =
        builders
            .create()
            .input(createGreeting)
            .setHeader("Content-Type", "application/json; charset=UTF-8")
            .build();
    Response<EmptyRecord> emptyRecordResponse = restClient.sendRequest(createRequest).getResponse();
    Assert.assertNull(emptyRecordResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE));
  }
  /** use Finder to find the photo with some criteria */
  private void findPhoto(PrintWriter respWriter) throws RemoteInvocationException {
    final long newPhotoId = createPhoto(respWriter);
    createPhoto(respWriter);
    createPhoto(respWriter);

    final Request<Photo> getReq = _photoBuilders.get().id(newPhotoId).build();
    final ResponseFuture<Photo> getFuture = _restClient.sendRequest(getReq);
    final Response<Photo> getResp = getFuture.getResponse();
    final Photo photo = getResp.getEntity();

    final FindRequest<Photo> findReq =
        _photoBuilders
            .findByTitleAndOrFormat()
            .titleParam(photo.getTitle())
            .formatParam(photo.getFormat())
            .build();

    final CollectionResponse<Photo> crPhotos =
        _restClient.sendRequest(findReq).getResponse().getEntity();
    final List<Photo> photos = crPhotos.getElements();

    respWriter.println("Found " + photos.size() + " photos with title " + photo.getTitle());
  }
Exemple #11
0
  @Test(
      dataProvider =
          com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
              + "requestMembershipsBuilderDataProvider")
  public void testAssociationCreateGetDelete(
      ProtocolVersion version, RootBuilderWrapper<CompoundKey, GroupMembership> membershipBuilders)
      throws RemoteInvocationException {
    // Setup - create group memberships
    CompoundKey key1 = buildCompoundKey(1, 1);
    GroupMembership groupMembership1 =
        buildGroupMembership(null, "*****@*****.**", "Alfred", "Hitchcock");

    Response<EmptyRecord> response =
        getClient()
            .sendRequest(membershipBuilders.update().id(key1).input(groupMembership1).build())
            .getResponse();
    Assert.assertEquals(response.getStatus(), 204);

    // Get membership
    Request<GroupMembership> getRequest =
        membershipBuilders.get().id(key1).fields(GroupMembership.fields().contactEmail()).build();
    GroupMembership groupMembership = getClient().sendRequest(getRequest).getResponse().getEntity();
    Assert.assertEquals(groupMembership.getContactEmail(), "*****@*****.**");

    // Delete the newly created group membership
    Response<EmptyRecord> deleteResponse =
        getClient().sendRequest(membershipBuilders.delete().id(key1).build()).getResponse();
    Assert.assertEquals(deleteResponse.getStatus(), 204);

    // Make sure it is gone
    try {
      getClient().sendRequest(getRequest).getResponse();
    } catch (RestLiResponseException e) {
      Assert.assertEquals(e.getStatus(), 404);
    }
  }
 /** call action purge to delete all photos on server */
 private void purgeAllPhotos(PrintWriter respWriter) throws RemoteInvocationException {
   final Request<Integer> purgeReq = _photoBuilders.actionPurge().build();
   final ResponseFuture<Integer> purgeFuture = _restClient.sendRequest(purgeReq);
   final Response<Integer> purgeResp = purgeFuture.getResponse();
   respWriter.println("Purged " + purgeResp.getEntity() + " photos");
 }
 /** send request to retrieve created photo */
 private void getPhoto(PrintWriter respWriter, long newPhotoId) throws RemoteInvocationException {
   final Request<Photo> getReq = _photoBuilders.get().id(newPhotoId).build();
   final ResponseFuture<Photo> getFuture = _restClient.sendRequest(getReq);
   final Response<Photo> getResp = getFuture.getResponse();
   respWriter.println("Photo: " + getResp.getEntity().toString());
 }
  /**
   * Retrieve the album information and each photo in the album. The photos are retrieved in
   * parallel.
   */
  private void getAlbum(PrintWriter respWriter, long albumId) throws RemoteInvocationException {
    // get the specific album
    final Request<Album> getAlbumReq = _albumBuilders.get().id(albumId).build();
    final ResponseFuture<Album> getAlbumFuture = _restClient.sendRequest(getAlbumReq);
    final Response<Album> getResp = getAlbumFuture.getResponse();
    final Album album = getResp.getEntity();

    respWriter.println(album.getTitle());
    respWriter.println("Created on " + new Date(album.getCreationTime()));

    // get the album's entries
    final FindRequest<AlbumEntry> searchReq =
        _albumEntryBuilders.findBySearch().albumIdParam(albumId).build();
    final ResponseFuture<CollectionResponse<AlbumEntry>> responseFuture =
        _restClient.sendRequest(searchReq);
    final Response<CollectionResponse<AlbumEntry>> response = responseFuture.getResponse();
    final List<AlbumEntry> entries = new ArrayList<AlbumEntry>(response.getEntity().getElements());

    entries.add(new AlbumEntry().setAlbumId(-1).setPhotoId(9999));

    // don't return until all photo requests done
    final CountDownLatch latch = new CountDownLatch(entries.size());

    // fetch every photo asynchronously
    // store either a photo or an exception
    final Object[] photos = new Object[entries.size()];
    for (int i = 0; i < entries.size(); i++) {
      final int finalI = i; // need final version for callback
      final AlbumEntry entry = entries.get(i);
      final long photoId = entry.getPhotoId();
      final Request<Photo> getPhotoReq = _photoBuilders.get().id(photoId).build();
      _restClient.sendRequest(
          getPhotoReq,
          new Callback<Response<Photo>>() {
            @Override
            public void onSuccess(Response<Photo> result) {
              photos[finalI] = result.getEntity();
              latch.countDown();
            }

            @Override
            public void onError(Throwable e) {
              photos[finalI] = e;
            }
          });
    }

    try {
      // wait for all requests to finish
      latch.await(2, TimeUnit.SECONDS);
      if (latch.getCount() > 0) {
        respWriter.println("Failed to retrieve some photo(s)");
      }
    } catch (InterruptedException e) {
      e.printStackTrace(respWriter);
    }

    // print photo data
    for (int i = 0; i < entries.size(); i++) {
      final Object val = photos[i];
      final AlbumEntry entry = entries.get(i);
      if (val instanceof Throwable) {
        respWriter.println("Failed to load photo " + entry.getPhotoId());
        respWriter.println("Stack trace:");
        ((Throwable) val).printStackTrace(respWriter);
        respWriter.println();
      } else if (val instanceof Photo) {
        final Photo photo = (Photo) val;
        respWriter.println("Photo " + photo.getTitle() + ":");
        respWriter.println(photo);
        respWriter.println("Added on " + new Date(entry.getAddTime()));
      } else {
        throw new AssertionError("expected photo or exception");
      }
    }
  }
Exemple #15
0
  @Test(
      dataProvider =
          com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
              + "requestComplexBuilderDataProvider")
  public void testComplexKeyCreateGetUpdateDelete(
      ProtocolVersion version,
      RootBuilderWrapper<
              ComplexResourceKey<GroupMembershipKey, GroupMembershipParam>,
              ComplexKeyGroupMembership>
          builders)
      throws RemoteInvocationException {
    // Create a new complex key resource
    ComplexResourceKey<GroupMembershipKey, GroupMembershipParam> complexKey =
        buildComplexKey(1, 1, 10, "String1");
    ComplexKeyGroupMembership groupMembership =
        buildComplexKeyGroupMembership(
            complexKey.getKey(), "*****@*****.**", "alfred", "hitchcock");

    Request<EmptyRecord> createRequest = builders.create().input(groupMembership).build();
    Response<EmptyRecord> createResponse = getClient().sendRequest(createRequest).getResponse();
    Assert.assertEquals(createResponse.getStatus(), 201);

    GroupMembershipParam param = new GroupMembershipParam();
    param.setIntParameter(1);
    param.setStringParameter("1");

    GroupMembershipQueryParam groupMembershipQueryParam1 = new GroupMembershipQueryParam();
    groupMembershipQueryParam1.setIntParameter(1);
    groupMembershipQueryParam1.setStringParameter("1");
    GroupMembershipQueryParam groupMembershipQueryParam2 = new GroupMembershipQueryParam();
    groupMembershipQueryParam2.setIntParameter(2);
    groupMembershipQueryParam2.setStringParameter("2");
    GroupMembershipQueryParamArray queryParamArray =
        new GroupMembershipQueryParamArray(
            Arrays.asList(groupMembershipQueryParam1, groupMembershipQueryParam2));
    // Get the resource back and check state
    Request<ComplexKeyGroupMembership> request =
        builders
            .get()
            .id(complexKey)
            .fields(GroupMembership.fields().contactEmail())
            .setQueryParam("testParam", param)
            .setQueryParam("testParamArray", queryParamArray)
            .build();
    ComplexKeyGroupMembership groupMembership1 =
        getClient().sendRequest(request).getResponse().getEntity();
    Assert.assertNotNull(groupMembership1);
    Assert.assertEquals(groupMembership1.getContactEmail(), "*****@*****.**");

    // Test the same with optional complex parameters
    request = builders.get().id(complexKey).fields(GroupMembership.fields().contactEmail()).build();
    groupMembership1 = getClient().sendRequest(request).getResponse().getEntity();
    Assert.assertNotNull(groupMembership1);
    Assert.assertEquals(groupMembership1.getContactEmail(), "*****@*****.**");

    // Update contact email and verify
    groupMembership.setContactEmail("*****@*****.**");
    Request<EmptyRecord> updateRequest =
        builders.update().id(complexKey).input(groupMembership).build();
    Response<EmptyRecord> updateResponse = getClient().sendRequest(updateRequest).getResponse();
    Assert.assertEquals(updateResponse.getStatus(), 204);

    groupMembership1 = getClient().sendRequest(request).getResponse().getEntity();
    Assert.assertEquals(groupMembership1.getContactEmail(), "*****@*****.**");

    // Delete and verify
    Request<EmptyRecord> deleteRequest = builders.delete().id(complexKey).build();
    Response<EmptyRecord> deleteResponse = getClient().sendRequest(deleteRequest).getResponse();
    Assert.assertEquals(deleteResponse.getStatus(), 204);
    try {
      getClient().sendRequest(request).getResponse().getEntity();
    } catch (RestLiResponseException e) {
      Assert.assertEquals(e.getStatus(), 404);
    }
  }