示例#1
0
  @Test
  public void testBuildEncodedQuery() {
    URI u = UriBuilder.fromPath("").queryParam("y", "1 %2B 2").build();
    Assert.assertEquals(URI.create("?y=1+%2B+2"), u);

    // Issue 216
    u =
        UriBuilder.fromPath("http://localhost:8080")
            .path("/{x}/{y}/{z}/{x}")
            .buildFromEncoded("%xy", " ", "=");
    Assert.assertEquals(URI.create("http://localhost:8080/%25xy/%20/=/%25xy"), u);
  }
/**
 * Tests for {@link com.vmware.photon.controller.api.frontend.resources.vm.ProjectVmsResource}. In
 * this test, we only test virtual network related stuff. Other test cases are in {@link
 * com.vmware.photon.controller.api.frontend.resources.ProjectVmsResourceTest}. The reason of
 * putting them in different files is that we cannot dynamically create the ProjectVmsResource in
 * the same file.
 */
public class VmOnVirtualNetworkTest extends ResourceTest {
  private String projectId = "p1";
  private String projectVmsRoutePath =
      UriBuilder.fromPath(ProjectResourceRoutes.PROJECT_VMS_PATH).build(projectId).toString();
  private String taskId = "task1";
  private String taskRoutePath =
      UriBuilder.fromPath(TaskResourceRoutes.TASK_PATH).build(taskId).toString();
  private PaginationConfig paginationConfig = new PaginationConfig();
  private VmCreateSpec spec;

  @Mock private VmFeClient vmFeClient;

  @Override
  protected void setUpResources() throws Exception {
    spec = new VmCreateSpec();
    spec.setName("vm0");
    spec.setSourceImageId("x");

    List<AttachedDiskCreateSpec> disks = new ArrayList<>();
    disks.add(
        new AttachedDiskCreateSpecBuilder().name("name").flavor("flavor").bootDisk(true).build());
    spec.setAttachedDisks(disks);

    addResource(new ProjectVmsResource(vmFeClient, paginationConfig, true));
  }

  @Test
  public void testSuccessfulCreate() throws Exception {
    List<String> networks = ImmutableList.of("network1");
    spec.setSubnets(networks);

    Task task = new Task();
    task.setId(taskId);
    doReturn(task).when(vmFeClient).create(projectId, spec);

    Response response = createVm();
    assertThat(response.getStatus(), is(HttpStatus.SC_CREATED));

    Task responseTask = response.readEntity(Task.class);
    assertThat(responseTask, is(task));
    assertThat(new URI(responseTask.getSelfLink()).isAbsolute(), is(true));
    assertThat(responseTask.getSelfLink().endsWith(taskRoutePath), is(true));
  }

  private Response createVm() {
    return client()
        .target(projectVmsRoutePath)
        .request()
        .post(Entity.entity(spec, MediaType.APPLICATION_JSON_TYPE));
  }
}
public class HalIdentityLink extends HalResource<HalIdentityLink> {

  public static final HalRelation REL_GROUP =
      HalRelation.build(
          "group", GroupRestService.class, UriBuilder.fromPath(GroupRestService.PATH).path("{id}"));
  public static final HalRelation REL_USER =
      HalRelation.build(
          "user", UserRestService.class, UriBuilder.fromPath(UserRestService.PATH).path("{id}"));
  public static final HalRelation REL_TASK =
      HalRelation.build(
          "task", TaskRestService.class, UriBuilder.fromPath(TaskRestService.PATH).path("{id}"));

  protected String type;
  protected String userId;
  protected String groupId;
  protected String taskId;

  public static HalIdentityLink fromIdentityLink(IdentityLink identityLink) {
    HalIdentityLink halIdentityLink = new HalIdentityLink();

    halIdentityLink.type = identityLink.getType();
    halIdentityLink.userId = identityLink.getUserId();
    halIdentityLink.groupId = identityLink.getGroupId();
    halIdentityLink.taskId = identityLink.getTaskId();

    halIdentityLink.linker.createLink(REL_USER, identityLink.getUserId());
    halIdentityLink.linker.createLink(REL_GROUP, identityLink.getGroupId());
    halIdentityLink.linker.createLink(REL_TASK, identityLink.getTaskId());

    return halIdentityLink;
  }

  public String getType() {
    return type;
  }

  public String getUserId() {
    return userId;
  }

  public String getGroupId() {
    return groupId;
  }

  public String getTaskId() {
    return taskId;
  }
}
  @Test
  public void succeedsToListByName() throws Throwable {
    VirtualSubnet expectedVirtualSubnet = new VirtualSubnet();
    expectedVirtualSubnet.setId(UUID.randomUUID().toString());
    expectedVirtualSubnet.setName("virtualNetwork");

    when(frontendClient.list(
            projectId, Project.KIND, Optional.of("virtualNetwork"), Optional.of(1)))
        .thenReturn(new ResourceList<>(ImmutableList.of(expectedVirtualSubnet)));

    Response response =
        listNetworks(Optional.of("virtualNetwork"), Optional.of(1), Optional.absent());
    assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));

    ResourceList<VirtualSubnet> virtualNetworks =
        response.readEntity(new GenericType<ResourceList<VirtualSubnet>>() {});
    assertThat(virtualNetworks.getItems().size(), is(1));

    VirtualSubnet actualVirtualSubnet = virtualNetworks.getItems().get(0);
    assertThat(actualVirtualSubnet, is(expectedVirtualSubnet));

    String apiRoutePath =
        UriBuilder.fromPath(SubnetResourceRoutes.SUBNET_PATH)
            .build(expectedVirtualSubnet.getId())
            .toString();
    assertThat(actualVirtualSubnet.getSelfLink().endsWith(apiRoutePath), is(true));
    assertThat(new URI(actualVirtualSubnet.getSelfLink()).isAbsolute(), is(true));
  }
示例#5
0
  @Test
  public void testAppendQueryParams() throws URISyntaxException {
    URI uri =
        UriBuilder.fromUri("http://localhost:8080/a/b/c?a=x&b=y").queryParam("c", "z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c?a=x&b=y&c=z"), uri);

    uri =
        UriBuilder.fromUri("http://localhost:8080/a/b/c?a=x&b=y").queryParam("c= ", "z= ").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c?a=x&b=y&c%3D+=z%3D+"), uri);

    uri = UriBuilder.fromUri(new URI("http://localhost:8080/")).queryParam("c", "z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/?c=z"), uri);

    uri = UriBuilder.fromUri(new URI("http://localhost:8080")).queryParam("c", "z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/?c=z"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/").queryParam("c", "z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/?c=z"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080").queryParam("c", "z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/?c=z"), uri);

    try {
      uri = UriBuilder.fromPath("http://localhost:8080").queryParam("name", "x", null).build();
    } catch (IllegalArgumentException e) {
      Assert.assertTrue(true);
    } catch (NullPointerException e) {
      Assert.assertTrue(false);
    }
  }
 @Test
 public void testBadURIResource() throws ExecutionException, InterruptedException {
   initiateWebApplication(BadURIResource.class, URIStringReaderProvider.class);
   final ContainerResponse responseContext =
       getResponseContext(UriBuilder.fromPath("/").queryParam("d", "::::123").build().toString());
   assertEquals(404, responseContext.getStatus());
 }
  @GET
  @Path("/{imageStream}/tag/{imageStreamTag}")
  @Produces(MediaType.APPLICATION_JSON)
  public ImageStreamTag getImageStreamTag(
      @PathParam("namespace") String namespace,
      @PathParam("imageStream") String imageStream,
      @PathParam("imageStreamTag") String imageStreamTag)
      throws UnauthorizedException, ServerException {
    URL url;
    try {
      url =
          UriBuilder.fromPath(getTagUrlTemplate)
              .buildFromMap(
                  ImmutableMap.of(
                      "namespace", namespace,
                      "imageStream", imageStream,
                      "tag", imageStreamTag))
              .toURL();
    } catch (MalformedURLException e) {
      throw new ServerException("Unable to get image stream tag. " + e.getMessage(), e);
    }

    try {
      final String response =
          clientFactory.getHttpClient().get(url, IHttpClient.DEFAULT_READ_TIMEOUT);
      return DtoFactory.getInstance().createDtoFromJson(response, ImageStreamTag.class);
    } catch (SocketTimeoutException e) {
      throw new ServerException("Unable to get image stream tag. " + e.getMessage(), e);
    }
  }
示例#8
0
  @Test
  public void testHostValue() {
    boolean caught = false;
    try {
      UriBuilder.fromPath("http://localhost").host("");
    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);

    URI uri = UriBuilder.fromPath("").host("abc").build();
    Assert.assertEquals(URI.create("//abc"), uri);

    uri = UriBuilder.fromPath("").host("abc").host(null).build();
    Assert.assertEquals(URI.create(""), uri);
  }
/** Tests {@link com.vmware.photon.controller.api.frontend.resources.auth.AuthResource}. */
public class AuthResourceTest extends ResourceTest {

  private static final boolean ENABLE_AUTH = true;
  private static final String AUTH_AUTH_SERVER_ADDRESS = "10.1.1.0";
  private static final int AUTH_AUTH_SERVER_PORT = 443;

  @Mock private DeploymentFeClient deploymentFeClient;

  private String authRoute = UriBuilder.fromPath(AuthRoutes.API).build().toString();

  @Override
  protected void setUpResources() throws Exception {
    addResource(new AuthResource(deploymentFeClient));
  }

  @Test
  public void dummy() {}

  /** Contains tests for HTTP GET Method on AuthResource. */
  @Test
  public void testGetAuthInfo() throws Exception {
    Auth auth = new Auth();
    auth.setEnabled(AuthResourceTest.ENABLE_AUTH);
    auth.setEndpoint(AuthResourceTest.AUTH_AUTH_SERVER_ADDRESS);
    auth.setPort(AuthResourceTest.AUTH_AUTH_SERVER_PORT);

    when(deploymentFeClient.getAuth()).thenReturn(auth);

    Auth authInfo = client().target(authRoute).request().get(Auth.class);

    assertThat(authInfo.getEnabled(), is(AuthResourceTest.ENABLE_AUTH));
    assertThat(authInfo.getEndpoint(), is(AuthResourceTest.AUTH_AUTH_SERVER_ADDRESS));
    assertThat(authInfo.getPort(), is(AuthResourceTest.AUTH_AUTH_SERVER_PORT));
  }
}
  public Result makeRequest(
      RemoteInstanceRequestClient client, String methodName, Object... values) {
    String remoteResponse;
    String errorMessage;
    {
      try {
        URI remoteUri =
            UriBuilder.fromPath(getPath())
                .scheme(exhibitor.getRestScheme())
                .host(hostname)
                .port(exhibitor.getRestPort())
                .path(ClusterResource.class, methodName)
                .build(values);

        remoteResponse =
            client.getWebResource(remoteUri, MediaType.APPLICATION_JSON_TYPE, String.class);
        errorMessage = "";
      } catch (Exception e) {
        remoteResponse = "{}";
        errorMessage = e.getMessage();
        if (errorMessage == null) {
          errorMessage = "Unknown";
        }
      }
    }

    return new Result(remoteResponse, errorMessage);
  }
示例#11
0
  @Test
  public void testIllegalArgumentException() {
    boolean caught = false;
    try {
      UriBuilder.fromPath(null);
    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);

    caught = false;
    try {
      UriBuilder.fromUri((URI) null);
    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);

    caught = false;
    try {
      UriBuilder.fromUri((String) null);
    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }
    public HttpResponse clientToProxyRequest(HttpObject httpObject) {
      if (httpObject instanceof DefaultHttpRequest) {

        DefaultHttpRequest fullreq = (DefaultHttpRequest) httpObject;
        Content c = null;
        // only return if content exist & at least one quality is
        // available
        if ((c = content.get(fullreq.getUri())) != null && c.getQualities().size() > 0) {

          LOGGER.debug("Cached resource found {}", c.getUri());

          HttpResponse response =
              new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
          Collections.shuffle(c.getQualities());

          String redirectUri =
              UriBuilder.fromPath(
                      "http://" + config.getFrontalHostName() + ":" + config.getFrontalPort())
                  .path("api")
                  .path("content")
                  .path(c.getId())
                  .path(c.getQualities().get(0))
                  .build()
                  .toString();
          response.headers().add("Location", redirectUri);
          LOGGER.debug("Redirecting it to ", redirectUri);
          return response;
        }
      }
      return null;
    }
示例#13
0
 public SourceConfig getSourceConfig(String sourceConfigId) throws ClientException {
   String path =
       UriBuilder.fromPath("/api/protected/sourceconfig/")
           .segment(sourceConfigId)
           .build()
           .toString();
   return doGet(path, SourceConfig.class);
 }
示例#14
0
 public ThresholdsOperator getThresholdsOperatorByName(String inName) throws ClientException {
   final String path =
       UriBuilder.fromPath("/api/protected/thresholdsop/byname/")
           .segment(inName)
           .build()
           .toString();
   return doGet(path, ThresholdsOperator.class);
 }
示例#15
0
 public OAuthProvider getOAuthProviderByName(String inName) throws ClientException {
   final String path =
       UriBuilder.fromPath("/api/protected/oauthproviders/byname/")
           .segment(inName)
           .build()
           .toString();
   return doGet(path, OAuthProvider.class);
 }
示例#16
0
 public RelationOperator getRelationOperatorByName(String inName) throws ClientException {
   final String path =
       UriBuilder.fromPath("/api/protected/relationops/byname/")
           .segment(inName)
           .build()
           .toString();
   return doGet(path, RelationOperator.class);
 }
 private String createHttpUrl(String host, String port, String path) {
   UriBuilder ub = UriBuilder.fromPath(path);
   ub.scheme("http").host(host);
   if (port != null && port.isEmpty()) {
     ub.port(Integer.parseInt(port));
   }
   return ub.build().toString();
 }
 public ClientResponse updateExternalIdentifier(
     String orcid, PersonExternalIdentifier externalIdentifier, String accessToken) {
   URI uri =
       UriBuilder.fromPath(EXTERNAL_IDENTIFIERS + PUTCODE)
           .build(orcid, externalIdentifier.getPutCode());
   return orcidClientHelper.putClientResponseWithToken(
       uri, VND_ORCID_XML, externalIdentifier, accessToken);
 }
示例#19
0
 // Search Functionality
 public List<String> getSystemElementSearchResults(String searchKey) throws ClientException {
   final String path =
       UriBuilder.fromPath("/api/protected/systemelement/search/")
           .segment(searchKey)
           .build()
           .toString();
   return doGet(path, SystemElementSearchResultsList);
 }
示例#20
0
 public Destination getDestination(String destinationId) throws ClientException {
   String path =
       UriBuilder.fromPath("/api/protected/destinations/")
           .segment(destinationId)
           .build()
           .toString();
   return doGet(path, Destination.class);
 }
示例#21
0
 public void deleteDestination(Long id, String destinationId) throws ClientException {
   String path =
       UriBuilder.fromPath("/api/protected/destinations/")
           .segment(destinationId)
           .build()
           .toString();
   doDelete(path);
 }
 public ClientResponse getGroupIdRecords(int pageSize, int page, String accessToken) {
   URI uri =
       UriBuilder.fromPath(GROUP_ID_RECORD)
           .queryParam("page-size", pageSize)
           .queryParam("page", page)
           .build();
   return orcidClientHelper.getClientResponseWithToken(uri, VND_ORCID_XML, accessToken);
 }
示例#23
0
 private URI getQueryStringSeqCluster40OfChain(String pdbid, String chain) {
   UriBuilder builder =
       UriBuilder.fromPath(restHost)
           .queryParam("cluster", 40)
           .queryParam("structureId", pdbid + "." + chain);
   URI uri = builder.build();
   return uri;
 }
  private void addLinks(UriInfo uriInfo) {
    action.setHref(UriBuilder.fromPath(getPath(uriInfo)).path(action.getId()).build().toString());

    String parentHref = LinkHelper.addLinks(uriInfo, parent).getHref();
    if (parentHref != null) {
      addLink("parent", parentHref);
    }
    addLink("replay", getPath(uriInfo));
  }
 public CrateHttpService(PersistentStateStore crateState, Configuration conf) {
   ResourceConfig httpConf =
       new ResourceConfig()
           .register(new CrateRestResource(crateState, conf))
           .packages(PACKAGE_NAMESPACE);
   URI httpUri =
       UriBuilder.fromPath("/").scheme("http").host("0.0.0.0").port(conf.apiPort).build();
   server = GrizzlyHttpServerFactory.createHttpServer(httpUri, httpConf);
   server.getServerConfiguration().addHttpHandler(new StaticHttpHandler(getRoot()), "/static");
 }
示例#26
0
 @Test
 public void testPortValue() {
   boolean caught = false;
   try {
     UriBuilder.fromPath("http://localhost").port(-2);
   } catch (IllegalArgumentException e) {
     caught = true;
   }
   Assert.assertTrue(caught);
 }
示例#27
0
 public void upload(String fileName, String sourceId, String fileTypeId, InputStream inputStream)
     throws ClientException {
   String path =
       UriBuilder.fromPath("/api/protected/file/upload/")
           .segment(sourceId)
           .segment(fileTypeId)
           .build()
           .toString();
   doPostMultipart(path, fileName, inputStream);
 }
示例#28
0
  public Statistics getJobStats(Long jobId, String propId) throws ClientException {
    if (jobId == null) {
      throw new IllegalArgumentException("jobId cannot be null");
    }
    UriBuilder uriBuilder = UriBuilder.fromPath("/api/protected/jobs/{arg1}/stats/");
    if (propId != null) {
      uriBuilder = uriBuilder.segment(propId);
    }

    return doGet(uriBuilder.build(jobId).toString(), Statistics.class);
  }
  @Test
  public void testListOfStringReaderProvider() throws ExecutionException, InterruptedException {
    initiateWebApplication(ListOfStringResource.class, ListOfStringReaderProvider.class);
    final ContainerResponse responseContext =
        getResponseContext(
            UriBuilder.fromPath("/").queryParam("l", "1,2," + "3").build().toString());

    final String s = (String) responseContext.getEntity();

    assertEquals(Collections.singletonList(Arrays.asList("1", "2", "3")).toString(), s);
  }
示例#30
0
  @Test
  public void testVariableWithoutValue() {
    boolean caught = false;
    try {
      UriBuilder.fromPath("http://localhost:8080").path("/{a}/{b}").buildFromEncoded("aVal");

    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }