org.restlet.data.Reference Java Examples

The following examples show how to use org.restlet.data.Reference. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AdminTestHelper.java    From helix with Apache License 2.0 7 votes vote down vote up
public static ZNRecord post(Client client, String url, String body)
    throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.POST, resourceRef);

  request.setEntity(body, MediaType.APPLICATION_ALL);

  Response response = client.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();

  if (result != null) {
    result.write(sw);
  }
  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);

  ObjectMapper mapper = new ObjectMapper();
  ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
  return record;
}
 
Example #2
Source File: RestApiServer.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@Override
public Restlet createInboundRoot() {
    Router baseRouter = new Router(context);
    baseRouter.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
    for (RestletRoutable rr : restlets) {
        baseRouter.attach(rr.basePath(), rr.getRestlet(context));
    }

    Filter slashFilter = new Filter() {            
        @Override
        protected int beforeHandle(Request request, Response response) {
            Reference ref = request.getResourceRef();
            String originalPath = ref.getPath();
            if (originalPath.contains("//"))
            {
                String newPath = originalPath.replaceAll("/+", "/");
                ref.setPath(newPath);
            }
            return Filter.CONTINUE;
        }

    };
    slashFilter.setNext(baseRouter);
    
    return slashFilter;
}
 
Example #3
Source File: ContextResourceClient.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
HandlerCommand command( Link link, Object commandRequest, ResponseHandler handler, ResponseHandler processingErrorHandler )
{
    if (handler == null)
        handler = commandHandlers.get( link.rel().get() );

    if (processingErrorHandler == null)
        processingErrorHandler = processingErrorHandlers.get( link.rel().get() );

    // Check if we should do POST or PUT
    Method method;
    if( LinksUtil.withClass( "idempotent" ).test( link ) )
    {
        method = Method.PUT;
    }
    else
    {
        method = Method.POST;
    }

    Reference ref = new Reference( reference.toUri().toString() + link.href().get() );
    return invokeCommand( ref, method, commandRequest, handler, processingErrorHandler );
}
 
Example #4
Source File: AdminTestHelper.java    From helix with Apache License 2.0 6 votes vote down vote up
public static ZNRecord get(Client client, String url) throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.GET, resourceRef);
  Response response = client.handle(request);
  Assert.assertEquals(response.getStatus(), Status.SUCCESS_OK);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);

  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);
  ObjectMapper mapper = new ObjectMapper();
  ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
  return record;
}
 
Example #5
Source File: ContextResourceClient.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public synchronized ContextResourceClient newClient( String relativePath )
{
    if( relativePath.startsWith( "http://" ) )
    {
        return contextResourceFactory.newClient( new Reference( relativePath ) );
    }

    Reference reference = this.reference.clone();
    if( relativePath.startsWith( "/" ) )
    {
        reference.setPath( relativePath );
    }
    else
    {
        reference.setPath( reference.getPath() + relativePath );
        reference = reference.normalize();
    }

    return contextResourceFactory.newClient( reference );
}
 
Example #6
Source File: TestClusterManagementWebapp.java    From helix with Apache License 2.0 6 votes vote down vote up
private void postConfig(Client client, String url, ObjectMapper mapper, String command,
    String configs) throws Exception {
  Map<String, String> params = new HashMap<String, String>();

  params.put(JsonParameters.MANAGEMENT_COMMAND, command);
  params.put(JsonParameters.CONFIGS, configs);

  Request request = new Request(Method.POST, new Reference(url));
  request.setEntity(
      JsonParameters.JSON_PARAMETERS + "=" + ClusterRepresentationUtil.ObjectToJson(params),
      MediaType.APPLICATION_ALL);

  Response response = client.handle(request);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);
  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);
}
 
Example #7
Source File: ResourceBuilder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public RestForm createNameForm( Reference base )
{
    ValueBuilder<RestForm> builder = vbf.newValueBuilder( RestForm.class );
    builder.prototype().link().set( createRestLink( "form", base, Method.POST ) );
    builder.prototype().fields().set( Collections.singletonList( createFormField( "name", FormField.TEXT ) ) );
    return builder.newInstance();
}
 
Example #8
Source File: ClientCache.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private String getIdentityPath( Reference ref )
{
    String path = ref.getPath();
    if( !path.endsWith( "/" ) )
    {
        path = path.substring( 0, path.lastIndexOf( '/' ) + 1 );
    }
    return path;
}
 
Example #9
Source File: EntryPointResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private EntryPoint createEntryPoint()
        {
            Map<String, RestLink> entryPoints = new HashMap<>();
            for( Route r : parameters.router().get().getRoutes() )
            {
                if( r instanceof TemplateRoute)
                {
                    TemplateRoute route = (TemplateRoute) r;
                    Template template = route.getTemplate();
                    // Only include patterns that doesn't have variables, and has a proper name.
                    if( template.getVariableNames().isEmpty() && route.getName().indexOf( '>' ) == -1 )
                    {
                        Reference hostRef = parameters.request().get().getOriginalRef();
//                        Reference reference = new Reference( hostRef, template.getPattern() );
                        RestLink link;
                        if( route.getDescription() == null )
                        {
                            link = resourceBuilder.createRestLink( template.getPattern(), hostRef, Method.GET );
                        }
                        else
                        {
                            link = resourceBuilder.createRestLink( template.getPattern(), hostRef, Method.GET, route.getDescription() );
                        }
                        entryPoints.put( route.getName(), link );
                    }
                }
            }
            ValueBuilder<EntryPoint> builder = vbf.newValueBuilder( EntryPoint.class );
            builder.prototype().identity().set( StringIdentity.identityOf( "/" ) );
            builder.prototype().api().set( entryPoints );
            return builder.newInstance();
        }
 
Example #10
Source File: ResourceBuilder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public Command createCommand( Reference base )
{
    RestForm form = createNameForm( base );
    ValueBuilder<Command> builder = vbf.newValueBuilder( Command.class );
    builder.prototype().name().set( "create" );
    builder.prototype().form().set( form );
    return builder.newInstance();
}
 
Example #11
Source File: ResourceBuilder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public RestLink createRestLink( String name, Reference base, Method method, String description )
{
    ValueBuilder<RestLink> builder = vbf.newValueBuilder( RestLink.class );
    RestLink prototype = builder.prototype();
    prototype.path().set( base.toUri().resolve( name ).getPath() + "/" );
    prototype.method().set( method.getName() );
    prototype.description().set( description );
    return builder.newInstance();
}
 
Example #12
Source File: ResourceBuilder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public RestLink createRestLink( String name, Reference base, Method method )
{
    ValueBuilder<RestLink> builder = vbf.newValueBuilder( RestLink.class );
    RestLink prototype = builder.prototype();
    String path = base.toUri().resolve( name ).getPath();
    prototype.path().set( path.endsWith( "/" ) ? path : path + "/" );
    prototype.method().set( method.getName() );
    return builder.newInstance();
}
 
Example #13
Source File: ResourceBuilder.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public EntityRef createEntityRef( Identity identity, Reference base )
{
    String name = identityManager.extractName( identity );

    RestLink get = createRestLink( name, base, Method.GET );
    RestLink put = createRestLink( name, base, Method.PUT );
    RestLink delete = createRestLink( name, base, Method.DELETE );
    return createEntityRef( identity, get, put, delete );
}
 
Example #14
Source File: ContextResourceClient.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private HandlerCommand invokeQuery( Reference ref, Object queryRequest, ResponseHandler resourceHandler, ResponseHandler processingErrorHandler )
{
    Request request = new Request( Method.GET, ref );

    if( queryRequest != null )
    {
        contextResourceFactory.writeRequest( request, queryRequest );
    }

    contextResourceFactory.updateQueryRequest( request );

    User user = request.getClientInfo().getUser();
    if ( user != null)
        request.setChallengeResponse( new ChallengeResponse( ChallengeScheme.HTTP_BASIC, user.getName(), user.getSecret() ) );

    Response response = new Response( request );

    contextResourceFactory.getClient().handle( request, response );

    if( response.getStatus().isSuccess() )
    {
        contextResourceFactory.updateCache( response );

        return resourceHandler.handleResponse( response, this );
    } else if (response.getStatus().isRedirection())
    {
        Reference redirectedTo = response.getLocationRef();
        return invokeQuery( redirectedTo, queryRequest, resourceHandler, processingErrorHandler );
    } else
    {
        if (response.getStatus().equals(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY) && processingErrorHandler != null)
        {
            return processingErrorHandler.handleResponse( response, this );
        } else
        {
            // TODO This needs to be expanded to allow custom handling of all the various cases
            return errorHandler.handleResponse( response, this );
        }
    }
}
 
Example #15
Source File: EntityListResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public EntityList get()
{
    Property<Request> request = parameters.request();
    Reference base = request.get().getResourceRef();
    String name = "list[" + parameters.entityType().get().getSimpleName() + "]";
    Identity identity = identityManager.generate( EntityListResource.class, name );
    ValueBuilder<EntityList> builder = vbf.newValueBuilder( EntityList.class );
    List<EntityRef> result = getEntityRefs( base );
    EntityList prototype = builder.prototype();
    prototype.identity().set( identity );
    prototype.entities().set( Collections.unmodifiableList( result ) );
    prototype.commands().set( Collections.singletonList( resourceBuilder.createCommand( base ) ) );
    return builder.newInstance();
}
 
Example #16
Source File: EntityListResource.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public RestLink post( RestForm form )
{
    FormField nameField = form.field( "name" );
    String name = null;
    if( nameField != null )
    {
        name = nameField.value().get();
    }
    Reference base = parameters.request().get().getResourceRef();
    Class<T> entityType = parameters.entityType().get();
    Identity identity = identityManager.generate(entityType, name);
    locator.find( entityType ).create( identity );
    return resourceBuilder.createRestLink( identity.toString(), base, Method.GET );
}
 
Example #17
Source File: CarsResource.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
@Get("json")
public List<CarRepresentation> all() {
    List<io.github.cdelmas.spike.common.domain.Car> cars = carRepository.all();
    getResponse().getHeaders().add("total-count", String.valueOf(cars.size()));
    return cars.stream().map(c -> {
        CarRepresentation carRepresentation = new CarRepresentation(c);
        carRepresentation.addLink(Link.self(new Reference(getReference()).addSegment(String.valueOf(c.getId())).toString()));
        return carRepresentation;
    }).collect(toList());
}
 
Example #18
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 5 votes vote down vote up
void deleteUrl(String url, boolean hasException) throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.DELETE, resourceRef);
  Response response = _gClient.handle(request);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);
  Assert.assertTrue(hasException == sw.toString().toLowerCase().contains("exception"));
}
 
Example #19
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 5 votes vote down vote up
String getUrl(String url) throws IOException {
  Reference resourceRef = new Reference(url);
  Request request = new Request(Method.GET, resourceRef);
  Response response = _gClient.handle(request);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);
  return sw.toString();
}
 
Example #20
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetResources() throws IOException {
  final String clusterName = "TestTagAwareness_testGetResources";
  final String TAG = "tag";
  final String URL_BASE =
      "http://localhost:" + ADMIN_PORT + "/clusters/" + clusterName + "/resourceGroups";

  _gSetupTool.addCluster(clusterName, true);
  HelixAdmin admin = _gSetupTool.getClusterManagementTool();

  // Add a tagged resource
  IdealState taggedResource = new IdealState("taggedResource");
  taggedResource.setInstanceGroupTag(TAG);
  taggedResource.setStateModelDefRef("OnlineOffline");
  admin.addResource(clusterName, taggedResource.getId(), taggedResource);

  // Add an untagged resource
  IdealState untaggedResource = new IdealState("untaggedResource");
  untaggedResource.setStateModelDefRef("OnlineOffline");
  admin.addResource(clusterName, untaggedResource.getId(), untaggedResource);

  // Now make a REST call for all resources
  Reference resourceRef = new Reference(URL_BASE);
  Request request = new Request(Method.GET, resourceRef);
  Response response = _gClient.handle(request);
  ZNRecord responseRecord =
      ClusterRepresentationUtil.JsonToObject(ZNRecord.class, response.getEntityAsText());

  // Ensure that the tagged resource has information and the untagged one doesn't
  Assert.assertNotNull(responseRecord.getMapField("ResourceTags"));
  Assert
      .assertEquals(TAG, responseRecord.getMapField("ResourceTags").get(taggedResource.getId()));
  Assert.assertFalse(responseRecord.getMapField("ResourceTags").containsKey(
      untaggedResource.getId()));
}
 
Example #21
Source File: TestClusterManagementWebapp.java    From helix with Apache License 2.0 5 votes vote down vote up
void verifyAddCluster() throws IOException, InterruptedException {
  String httpUrlBase = "http://localhost:" + ADMIN_PORT + "/clusters";
  Map<String, String> paraMap = new HashMap<String, String>();

  paraMap.put(JsonParameters.CLUSTER_NAME, clusterName);
  paraMap.put(JsonParameters.MANAGEMENT_COMMAND, ClusterSetup.addCluster);

  Reference resourceRef = new Reference(httpUrlBase);

  Request request = new Request(Method.POST, resourceRef);

  request.setEntity(
      JsonParameters.JSON_PARAMETERS + "=" + ClusterRepresentationUtil.ObjectToJson(paraMap),
      MediaType.APPLICATION_ALL);
  Response response = _gClient.handle(request);

  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);

  // System.out.println(sw.toString());

  ObjectMapper mapper = new ObjectMapper();
  ZNRecord zn = mapper.readValue(new StringReader(sw.toString()), ZNRecord.class);
  AssertJUnit.assertTrue(zn.getListField("clusters").contains(clusterName));

}
 
Example #22
Source File: TestClusterManagementWebapp.java    From helix with Apache License 2.0 5 votes vote down vote up
private ZNRecord get(Client client, String url, ObjectMapper mapper) throws Exception {
  Request request = new Request(Method.GET, new Reference(url));
  Response response = client.handle(request);
  Representation result = response.getEntity();
  StringWriter sw = new StringWriter();
  result.write(sw);
  String responseStr = sw.toString();
  Assert.assertTrue(responseStr.toLowerCase().indexOf("error") == -1);
  Assert.assertTrue(responseStr.toLowerCase().indexOf("exception") == -1);

  ZNRecord record = mapper.readValue(new StringReader(responseStr), ZNRecord.class);
  return record;
}
 
Example #23
Source File: ServerResource.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Reference getURL()
{
    final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
    final String realURL = headers.getFirstValue("X-Real-URL", true);
    if (realURL != null)
        return new Reference(realURL);
    else
        return getRequest().getOriginalRef();
}
 
Example #24
Source File: ServerResource.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Reference getURL()
{
    final Series<Header> headers = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
    final String realURL = headers.getFirstValue("X-Real-URL", true);
    if (realURL != null)
        return new Reference(realURL);
    else
        return getRequest().getOriginalRef();
}
 
Example #25
Source File: TestRestManager.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveResourceIdDecodeUrlEntities () throws Exception {
  Request testRequest = new Request();
  Reference rootRef = new Reference("http://solr.apache.org/");
  testRequest.setRootRef(rootRef);

  Reference resourceRef = new Reference("http://solr.apache.org/schema/analysis/synonyms/de/%C3%84ndern");
  testRequest.setResourceRef(resourceRef);

  String resourceId = RestManager.ManagedEndpoint.resolveResourceId(testRequest);
  assertEquals(resourceId, "/schema/analysis/synonyms/de/Ă„ndern");
}
 
Example #26
Source File: TestRestManager.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveResourceId () throws Exception {
  Request testRequest = new Request();
  Reference rootRef = new Reference("http://solr.apache.org/");
  testRequest.setRootRef(rootRef);

  Reference resourceRef = new Reference("http://solr.apache.org/schema/analysis/synonyms/de");
  testRequest.setResourceRef(resourceRef);

  String resourceId = RestManager.ManagedEndpoint.resolveResourceId(testRequest);
  assertEquals(resourceId, "/schema/analysis/synonyms/de");
}
 
Example #27
Source File: TicketResource.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Accept credentials and attempt to create the TGT.
 *
 * @param entity the entity
 */
@Post
public final void acceptRepresentation(final Representation entity)  {
    LOGGER.debug("Obtaining credentials...");
    final Credential c = obtainCredentials();

    if (c == null) {
        LOGGER.trace("No credentials could be obtained from the REST entity representation");
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid or missing credentials");
        return;
    }

    try (final Formatter fmt = new Formatter()) {
        final TicketGrantingTicket ticketGrantingTicketId = this.centralAuthenticationService.createTicketGrantingTicket(c);
        getResponse().setStatus(determineStatus());
        final Reference ticketReference = getRequest().getResourceRef().addSegment(ticketGrantingTicketId.getId());
        getResponse().setLocationRef(ticketReference);

        fmt.format("<!DOCTYPE HTML PUBLIC \\\"-//IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        fmt.format("%s %s", getResponse().getStatus().getCode(), getResponse().getStatus().getDescription())
           .format("</title></head><body><h1>TGT Created</h1><form action=\"%s", ticketReference)
           .format("\" method=\"POST\">Service:<input type=\"text\" name=\"service\" value=\"\">")
           .format("<br><input type=\"submit\" value=\"Submit\"></form></body></html>");

        getResponse().setEntity(fmt.toString(), MediaType.TEXT_HTML);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
    }
}
 
Example #28
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 4 votes vote down vote up
static String assertSuccessPostOperation(String url, Map<String, String> jsonParameters,
    Map<String, String> extraForm, boolean hasException) throws IOException {
  Reference resourceRef = new Reference(url);

  int numRetries = 0;
  while (numRetries <= MAX_RETRIES) {
    Request request = new Request(Method.POST, resourceRef);

    if (extraForm != null) {
      String entity =
          JsonParameters.JSON_PARAMETERS + "="
              + ClusterRepresentationUtil.ObjectToJson(jsonParameters);
      for (String key : extraForm.keySet()) {
        entity = entity + "&" + (key + "=" + extraForm.get(key));
      }
      request.setEntity(entity, MediaType.APPLICATION_ALL);
    } else {
      request
          .setEntity(
              JsonParameters.JSON_PARAMETERS + "="
                  + ClusterRepresentationUtil.ObjectToJson(jsonParameters),
              MediaType.APPLICATION_ALL);
    }

    Response response = _gClient.handle(request);
    Representation result = response.getEntity();
    StringWriter sw = new StringWriter();

    if (result != null) {
      result.write(sw);
    }

    int code = response.getStatus().getCode();
    boolean successCode =
        code == Status.SUCCESS_NO_CONTENT.getCode() || code == Status.SUCCESS_OK.getCode();
    if (successCode || numRetries == MAX_RETRIES) {
      Assert.assertTrue(successCode);
      Assert.assertTrue(hasException == sw.toString().toLowerCase().contains("exception"));
      return sw.toString();
    }
    numRetries++;
  }
  Assert.fail("Request failed after all retries");
  return null;
}
 
Example #29
Source File: StuffApplication.java    From spring-5-examples with MIT License 4 votes vote down vote up
@Override
public synchronized void start() throws Exception {
  Router router = new Router(getContext());


  Properties props = new Properties();
  props.load(getClass().getResourceAsStream("/velocity.properties"));

  VelocityEngine velocity = new VelocityEngine(props);

  Function<String, Function<Identifier, ? extends Entity>> entityFactory =
      type -> identifier ->
      {
        switch (type) {
          case "task":
            return new Task(identifier);

          case "project":
            return new Project(identifier);
        }

        throw new IllegalArgumentException(type);
      };

  eventStore = new InMemoryEventStore();
  Repository repository = new InMemoryRepository(eventStore, eventStore, entityFactory);

  graphDb = new GraphDatabaseFactory().newEmbeddedDatabase("graphdb");

  InboxModel inboxModel = new Neo4jInboxModel(graphDb);
  eventStore.addInteractionContextSink(inboxModel);

  ObjectMapper mapper = new ObjectMapper();
  mapper.registerModule(new SimpleModule("EventSourcing", new Version(1, 0, 0, null, "eventsourcing", "eventsourcing")).
      addSerializer(InteractionContext.class, new InteractionContextSerializer()).
      addDeserializer(InteractionContext.class, new InteractionContextDeserializer()).setMixInAnnotation(Event.class, JacksonEvent.class)
  );

  File file = new File("events.log").getAbsoluteFile();
  LoggerFactory.getLogger(getClass()).info("Event log:" + file);
  storage = new FileEventStorage(mapper);

  if (file.exists())
    storage.load(file, eventStore);

  storage.save(file, eventStore);

  eventStore.addInteractionContextSink(new LoggingModel(mapper));

  InboxResource inboxResource = new InboxResource(velocity, repository,
      new TaskResource(velocity, repository, inboxModel), inboxModel);
  router.attach("inbox/{task}/{command}", inboxResource);
  router.attach("inbox/{task}/", inboxResource);
  router.attach("inbox/{command}", inboxResource);
  router.attach("inbox/", inboxResource);

  Reference staticContent = new Reference(new File(getClass().getResource("/htdocs/index.html").getFile()).getParentFile().toURI());
  router.attachDefault(new Directory(getContext(), staticContent)).setMatchingMode(Template.MODE_STARTS_WITH);

  setInboundRoot(router);

  super.start();
}
 
Example #30
Source File: TestHelixAdminScenariosRest.java    From helix with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetInstances() throws IOException {
  final String clusterName = "TestTagAwareness_testGetResources";
  final String[] TAGS = {
      "tag1", "tag2"
  };
  final String URL_BASE =
      "http://localhost:" + ADMIN_PORT + "/clusters/" + clusterName + "/instances";

  _gSetupTool.addCluster(clusterName, true);
  HelixAdmin admin = _gSetupTool.getClusterManagementTool();

  // Add 4 participants, each with differint tag characteristics
  InstanceConfig instance1 = new InstanceConfig("localhost_1");
  instance1.addTag(TAGS[0]);
  admin.addInstance(clusterName, instance1);
  InstanceConfig instance2 = new InstanceConfig("localhost_2");
  instance2.addTag(TAGS[1]);
  admin.addInstance(clusterName, instance2);
  InstanceConfig instance3 = new InstanceConfig("localhost_3");
  instance3.addTag(TAGS[0]);
  instance3.addTag(TAGS[1]);
  admin.addInstance(clusterName, instance3);
  InstanceConfig instance4 = new InstanceConfig("localhost_4");
  admin.addInstance(clusterName, instance4);

  // Now make a REST call for all resources
  Reference resourceRef = new Reference(URL_BASE);
  Request request = new Request(Method.GET, resourceRef);
  Response response = _gClient.handle(request);
  ListInstancesWrapper responseWrapper =
      ClusterRepresentationUtil.JsonToObject(ListInstancesWrapper.class,
          response.getEntityAsText());
  Map<String, List<String>> tagInfo = responseWrapper.tagInfo;

  // Ensure tag ownership is reported correctly
  Assert.assertTrue(tagInfo.containsKey(TAGS[0]));
  Assert.assertTrue(tagInfo.containsKey(TAGS[1]));
  Assert.assertTrue(tagInfo.get(TAGS[0]).contains("localhost_1"));
  Assert.assertFalse(tagInfo.get(TAGS[0]).contains("localhost_2"));
  Assert.assertTrue(tagInfo.get(TAGS[0]).contains("localhost_3"));
  Assert.assertFalse(tagInfo.get(TAGS[0]).contains("localhost_4"));
  Assert.assertFalse(tagInfo.get(TAGS[1]).contains("localhost_1"));
  Assert.assertTrue(tagInfo.get(TAGS[1]).contains("localhost_2"));
  Assert.assertTrue(tagInfo.get(TAGS[1]).contains("localhost_3"));
  Assert.assertFalse(tagInfo.get(TAGS[1]).contains("localhost_4"));
}