public void setResourceConfig(@NonNull ResourceConfig resourceConfig) {
   mResourceConfig = resourceConfig;
   refreshArrowImg.setImageResource(mResourceConfig.getImageResIds()[0]);
   loadArrowImg.setImageResource(mResourceConfig.getImageResIds()[0]);
   refreshHintText.setText(mResourceConfig.getTextResIds()[0]);
   refreshHintText.setText(mResourceConfig.getTextResIds()[5]);
 }
  public ApplicationHandler setupApplication1() {
    final ResourceConfig rc = new ResourceConfig();

    Resource.Builder rb;

    rb = Resource.builder("a/b/c");
    rb.addMethod("GET").handledBy(new AsyncInflector("A-B-C"));
    rc.addResources(rb.build());

    rb = Resource.builder("a/b/d");
    rb.addMethod("GET").handledBy(new AsyncInflector("A-B-D"));
    rc.addResources(rb.build());

    return new ApplicationHandler(rc);
  }
  private void initView() {
    // 初始化下拉布局
    refreshArrowImg = (ImageView) refreshView.findViewById(R.id.head_xw_ptr_arrow_img);
    refreshHintText = (TextView) refreshView.findViewById(R.id.head_xw_ptr_hint_text);
    refreshingBar = (ProgressBar) refreshView.findViewById(R.id.head_xw_ptr_progress_bar);
    // 初始化上拉布局
    loadArrowImg = (ImageView) loadMoreView.findViewById(R.id.foot_xw_ptr_arrow_img);
    rotateArrow(loadArrowImg);
    loadHintText = (TextView) loadMoreView.findViewById(R.id.foot_xw_ptr_hint_text);
    loadingBar = (ProgressBar) loadMoreView.findViewById(R.id.foot_xw_ptr_progress_bar);

    if (mResourceConfig != null) {
      refreshArrowImg.setImageResource(mResourceConfig.getImageResIds()[0]);
      loadArrowImg.setImageResource(mResourceConfig.getImageResIds()[0]);
    }
  }
Exemplo n.º 4
0
  /**
   * Create a new Jersey server-side application handler configured by an instance of a {@link
   * Application JAX-RS Application sub-class}.
   *
   * @param application an instance of a JAX-RS {@code Application} (sub-)class that will be used to
   *     configure the new Jersey application handler.
   */
  public ApplicationHandler(Application application) {
    this.locator = Injections.createLocator(new ServerBinder(), new ApplicationBinder());
    this.application = application;
    if (application instanceof ResourceConfig) {
      final ResourceConfig rc = (ResourceConfig) application;
      if (rc.getApplicationClass() != null) {
        rc.setApplication(createApplication(rc.getApplicationClass()));
      }
    }
    this.runtimeConfig = ResourceConfig.createRuntimeConfig(application);

    Errors.processWithException(
        new Runnable() {
          @Override
          public void run() {
            initialize();
          }
        });
  }
Exemplo n.º 5
0
 private Application createApplication(Class<? extends Application> applicationClass) {
   // need to handle ResourceConfig and Application separately as invoking forContract() on these
   // will trigger the factories which we don't want at this point
   if (applicationClass == ResourceConfig.class) {
     return new ResourceConfig();
   } else if (applicationClass == Application.class) {
     return new Application();
   } else {
     Application app = locator.createAndInitialize(applicationClass);
     if (app instanceof ResourceConfig) {
       final ResourceConfig _rc = (ResourceConfig) app;
       final Class<? extends Application> innerAppClass = _rc.getApplicationClass();
       if (innerAppClass != null) {
         final Application innerApp = createApplication(innerAppClass);
         _rc.setApplication(innerApp);
       }
     }
     return app;
   }
 }
Exemplo n.º 6
0
  /**
   * Create a new Jersey server-side application handler configured by a {@link Application JAX-RS
   * Application (sub-)class}.
   *
   * @param jaxrsApplicationClass JAX-RS {@code Application} (sub-)class that will be instantiated
   *     and used to configure the new Jersey application handler.
   */
  public ApplicationHandler(Class<? extends Application> jaxrsApplicationClass) {
    this.locator = Injections.createLocator(new ServerBinder(), new ApplicationBinder());
    this.application = createApplication(jaxrsApplicationClass);
    this.runtimeConfig = ResourceConfig.createRuntimeConfig(application);

    Errors.processWithException(
        new Runnable() {
          @Override
          public void run() {
            initialize();
          }
        });
  }
  /**
   * 加载完毕,显示加载结果。注意:加载完成后一定要调用这个方法
   *
   * @param isSuccess true成功,false代表失败
   */
  public void loadMoreFinish(boolean isSuccess) {
    if (loadingBar == null || loadHintText == null) {
      return;
    }
    loadingBar.clearAnimation();
    loadingBar.setVisibility(View.INVISIBLE);

    if (showRefreshResultEnable) {
      if (isSuccess) { // 加载更多成功
        loadHintText.setText(mResourceConfig.getTextResIds()[8]);
        Drawable drawable =
            ContextCompat.getDrawable(getContext(), mResourceConfig.getImageResIds()[3]);
        loadHintText.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        loadHintText.setCompoundDrawablePadding(dp2px(10));
      } else { // 加载更多失败
        loadHintText.setText(mResourceConfig.getTextResIds()[9]);
        Drawable drawable =
            ContextCompat.getDrawable(getContext(), mResourceConfig.getImageResIds()[4]);
        loadHintText.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        loadHintText.setCompoundDrawablePadding(dp2px(10));
      }
    }
    if (pullUpY < 0) {
      postDelayed(
          new Runnable() {
            @Override
            public void run() {
              changeStage(DONE);
              hide();
            }
          },
          showRefreshResultEnable ? 1000 : 0); // 判断刷新结果停留1秒
    } else {
      changeStage(DONE);
      hide();
    }
  }
  private void changeStage(int to) {
    stage = to;
    switch (stage) {
      case INIT: // 下拉布局初始状态
        refreshHintText.setText(mResourceConfig.getTextResIds()[0]);
        refreshHintText.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        refreshArrowImg.setVisibility(View.VISIBLE);
        rotateArrow(refreshArrowImg);

        // 上拉布局初始状态
        loadHintText.setText(mResourceConfig.getTextResIds()[5]);
        loadHintText.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        loadArrowImg.setVisibility(View.VISIBLE);
        rotateArrow(loadArrowImg);
        break;
      case RELEASE_TO_REFRESH: // 释放刷新状态
        refreshHintText.setText(mResourceConfig.getTextResIds()[1]);
        rotateArrow(refreshArrowImg);
        break;
      case REFRESHING: // 正在刷新状态
        refreshArrowImg.clearAnimation();
        refreshingBar.setVisibility(View.VISIBLE);
        refreshArrowImg.setVisibility(View.INVISIBLE);
        refreshHintText.setText(mResourceConfig.getTextResIds()[2]);
        break;
      case RELEASE_TO_LOAD: // 释放加载状态
        loadHintText.setText(mResourceConfig.getTextResIds()[6]);
        rotateArrow(loadArrowImg);
        break;
      case LOADING: // 正在加载状态
        loadArrowImg.clearAnimation();
        loadingBar.setVisibility(View.VISIBLE);
        loadArrowImg.setVisibility(View.INVISIBLE);
        loadHintText.setText(mResourceConfig.getTextResIds()[7]);
        break;
      case DONE: // 刷新或加载完毕,切换到DONE状态
        break;
    }
  }
Exemplo n.º 9
0
  private void run() throws Exception {
    InetSocketAddress address;

    if (this.host != null) {
      address = new InetSocketAddress(this.host, this.port);
    } else {
      address = new InetSocketAddress(this.port);
    }

    Server server = new Server(address);

    ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ModelRegistry modelRegistry = new ModelRegistry();

    final MetricRegistry metricRegistry = new MetricRegistry();

    Binder binder =
        new AbstractBinder() {

          @Override
          protected void configure() {
            bind(modelRegistry).to(ModelRegistry.class);
            bind(metricRegistry).to(MetricRegistry.class);
          }
        };

    ResourceConfig config = new ResourceConfig(ModelResource.class);
    config.register(binder);
    config.register(JacksonFeature.class);
    config.register(MultiPartFeature.class);
    config.register(ObjectMapperProvider.class);
    config.register(RolesAllowedDynamicFeature.class);

    // Naive implementation that grants the "admin" role to all local network users
    config.register(NetworkSecurityContextFilter.class);

    ServletContextHandler servletHandler = new ServletContextHandler();
    servletHandler.setContextPath(this.contextPath);

    ServletContainer jerseyServlet = new ServletContainer(config);

    servletHandler.addServlet(new ServletHolder(jerseyServlet), "/*");

    InstrumentedHandler instrumentedHandler = new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(servletHandler);

    handlerCollection.addHandler(instrumentedHandler);

    if (this.consoleWar != null) {
      WebAppContext consoleHandler = new WebAppContext();
      consoleHandler.setContextPath(this.contextPath + "/console"); // XXX
      consoleHandler.setWar(this.consoleWar.getAbsolutePath());

      handlerCollection.addHandler(consoleHandler);
    }

    server.setHandler(handlerCollection);

    DirectoryDeployer deployer = null;

    if (this.modelDir != null) {

      if (!this.modelDir.isDirectory()) {
        throw new IOException(this.modelDir.getAbsolutePath() + " is not a directory");
      }

      deployer = new DirectoryDeployer(modelRegistry, this.modelDir.toPath());
    }

    server.start();

    if (deployer != null) {
      deployer.start();
    }

    server.join();

    if (deployer != null) {
      deployer.interrupt();

      deployer.join();
    }
  }
Exemplo n.º 10
0
  private void bindProvidersAndResources(
      final Set<ComponentProvider> componentProviders,
      final ComponentBag componentBag,
      final Set<Class<?>> resourceClasses,
      final Set<Object> resourceInstances) {

    final JerseyResourceContext resourceContext = locator.getService(JerseyResourceContext.class);
    final DynamicConfiguration dc = Injections.getConfiguration(locator);
    final Set<Class<?>> registeredClasses = runtimeConfig.getRegisteredClasses();

    // Merge programmatic resource classes with component classes.
    Set<Class<?>> classes = Sets.newIdentityHashSet();
    classes.addAll(
        Sets.filter(
            componentBag.getClasses(ComponentBag.EXCLUDE_META_PROVIDERS),
            new Predicate<Class<?>>() {
              @Override
              public boolean apply(Class<?> componentClass) {
                return Providers.checkProviderRuntime(
                    componentClass,
                    componentBag.getModel(componentClass),
                    RuntimeType.SERVER,
                    !registeredClasses.contains(componentClass),
                    resourceClasses.contains(componentClass));
              }
            }));
    classes.addAll(resourceClasses);

    // Bind classes.
    for (Class<?> componentClass : classes) {
      ContractProvider model = componentBag.getModel(componentClass);
      if (resourceClasses.contains(componentClass)) {
        if (bindWithComponentProvider(componentClass, model, componentProviders)) {
          continue;
        }

        if (!Resource.isAcceptable(componentClass)) {
          LOGGER.warning(LocalizationMessages.NON_INSTANTIABLE_COMPONENT(componentClass));
          continue;
        }

        if (model != null
            && !Providers.checkProviderRuntime(
                componentClass,
                model,
                RuntimeType.SERVER,
                !registeredClasses.contains(componentClass),
                true)) {
          model = null;
        }
        resourceContext.unsafeBindResource(componentClass, model, dc);
      } else {
        ProviderBinder.bindProvider(componentClass, model, dc);
      }
    }

    // Merge programmatic resource instances with other component instances.
    Set<Object> instances = Sets.newHashSet();
    instances.addAll(
        Sets.filter(
            componentBag.getInstances(ComponentBag.EXCLUDE_META_PROVIDERS),
            new Predicate<Object>() {
              @Override
              public boolean apply(Object component) {
                final Class<?> componentClass = component.getClass();
                return Providers.checkProviderRuntime(
                    componentClass,
                    componentBag.getModel(componentClass),
                    RuntimeType.SERVER,
                    !registeredClasses.contains(componentClass),
                    resourceInstances.contains(component));
              }
            }));
    instances.addAll(resourceInstances);

    // Bind instances.
    for (Object component : instances) {
      ContractProvider model = componentBag.getModel(component.getClass());
      if (resourceInstances.contains(component)) {
        if (model != null
            && !Providers.checkProviderRuntime(
                component.getClass(),
                model,
                RuntimeType.SERVER,
                !registeredClasses.contains(component.getClass()),
                true)) {
          model = null;
        }
        resourceContext.unsafeBindResource(component, model, dc);
      } else {
        ProviderBinder.bindProvider(component, model, dc);
      }
    }

    dc.commit();
  }
Exemplo n.º 11
0
  /** Assumes the configuration field is initialized with a valid ResourceConfig. */
  private void initialize() {
    LOGGER.info(LocalizationMessages.INIT_MSG(Version.getBuildId()));

    // Lock original ResourceConfig.
    if (application instanceof ResourceConfig) {
      ((ResourceConfig) application).lock();
    }

    // add WADL support
    runtimeConfig.register(WadlModelProcessorFeature.class);

    // Configure binders and features.
    runtimeConfig.configureMetaProviders(locator);

    // Introspecting classes & instances
    final ResourceBag.Builder resourceBagBuilder = new ResourceBag.Builder();
    for (Class<?> c : runtimeConfig.getClasses()) {
      try {
        Resource resource = Resource.from(c);
        if (resource != null) {
          resourceBagBuilder.registerResource(c, resource);
        }
      } catch (IllegalArgumentException ex) {
        LOGGER.warning(ex.getMessage());
      }
    }

    for (Object o : runtimeConfig.getSingletons()) {
      try {
        Resource resource = Resource.from(o.getClass());
        if (resource != null) {
          resourceBagBuilder.registerResource(o, resource);
        }
      } catch (IllegalArgumentException ex) {
        LOGGER.warning(ex.getMessage());
      }
    }

    // Adding programmatic resource models
    for (Resource programmaticResource : runtimeConfig.getResources()) {
      resourceBagBuilder.registerProgrammaticResource(programmaticResource);
    }

    final ResourceBag resourceBag = resourceBagBuilder.build();

    runtimeConfig.lock();

    // Registering Injection Bindings
    final Set<ComponentProvider> componentProviders = new HashSet<ComponentProvider>();

    for (ComponentProvider provider : ServiceFinder.find(ComponentProvider.class)) {
      provider.initialize(locator);
      componentProviders.add(provider);
    }

    final ComponentBag componentBag = runtimeConfig.getComponentBag();
    bindProvidersAndResources(
        componentProviders, componentBag, resourceBag.classes, resourceBag.instances);
    for (ComponentProvider componentProvider : componentProviders) {
      componentProvider.done();
    }

    // scan for NameBinding annotations attached to the application class
    Collection<Class<? extends Annotation>> applicationNameBindings =
        ReflectionHelper.getAnnotationTypes(application.getClass(), NameBinding.class);

    // find all filters, interceptors and dynamic features
    final Iterable<RankedProvider<ContainerResponseFilter>> responseFilters =
        Providers.getAllRankedProviders(locator, ContainerResponseFilter.class);
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<ContainerResponseFilter>>
        nameBoundResponseFilters =
            filterNameBound(responseFilters, null, componentBag, applicationNameBindings);

    final Iterable<RankedProvider<ContainerRequestFilter>> requestFilters =
        Providers.getAllRankedProviders(locator, ContainerRequestFilter.class);
    final List<RankedProvider<ContainerRequestFilter>> preMatchFilters = Lists.newArrayList();
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<ContainerRequestFilter>>
        nameBoundRequestFilters =
            filterNameBound(requestFilters, preMatchFilters, componentBag, applicationNameBindings);

    final Iterable<RankedProvider<ReaderInterceptor>> readerInterceptors =
        Providers.getAllRankedProviders(locator, ReaderInterceptor.class);
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<ReaderInterceptor>>
        nameBoundReaderInterceptors =
            filterNameBound(readerInterceptors, null, componentBag, applicationNameBindings);

    final Iterable<RankedProvider<WriterInterceptor>> writerInterceptors =
        Providers.getAllRankedProviders(locator, WriterInterceptor.class);
    final MultivaluedMap<Class<? extends Annotation>, RankedProvider<WriterInterceptor>>
        nameBoundWriterInterceptors =
            filterNameBound(writerInterceptors, null, componentBag, applicationNameBindings);
    final Iterable<DynamicFeature> dynamicFeatures =
        Providers.getAllProviders(locator, DynamicFeature.class);

    ResourceModel resourceModel =
        new ResourceModel.Builder(resourceBag.getRootResources(), false).build();

    resourceModel = processResourceModel(resourceModel);
    // validate the models
    validate(resourceModel);

    bindEnhancingResourceClasses(resourceModel, resourceBag, componentProviders);

    final RuntimeModelBuilder runtimeModelBuilder = locator.getService(RuntimeModelBuilder.class);
    runtimeModelBuilder.setGlobalInterceptors(readerInterceptors, writerInterceptors);
    runtimeModelBuilder.setBoundProviders(
        nameBoundRequestFilters,
        nameBoundResponseFilters,
        nameBoundReaderInterceptors,
        nameBoundWriterInterceptors,
        dynamicFeatures);

    // assembly request processing chain
    /**
     * Root hierarchical request matching acceptor. Invoked in a single linear stage as part of the
     * main linear accepting chain.
     */
    final Router resourceRoutingRoot =
        runtimeModelBuilder.buildModel(resourceModel.getRuntimeResourceModel(), false);

    final ContainerFilteringStage preMatchRequestFilteringStage =
        locator
            .createAndInitialize(ContainerFilteringStage.Builder.class)
            .build(preMatchFilters, responseFilters);
    final RoutingStage routingStage =
        locator.createAndInitialize(RoutingStage.Builder.class).build(resourceRoutingRoot);
    final ContainerFilteringStage resourceFilteringStage =
        locator
            .createAndInitialize(ContainerFilteringStage.Builder.class)
            .build(requestFilters, null);
    final RoutedInflectorExtractorStage routedInflectorExtractorStage =
        locator.createAndInitialize(RoutedInflectorExtractorStage.class);
    /**
     * Root linear request acceptor. This is the main entry point for the whole request processing.
     */
    final Stage<ContainerRequest> rootStage =
        Stages.chain(locator.createAndInitialize(ReferencesInitializer.class))
            .to(locator.createAndInitialize(ContainerMessageBodyWorkersInitializer.class))
            .to(preMatchRequestFilteringStage)
            .to(routingStage)
            .to(resourceFilteringStage)
            .build(routedInflectorExtractorStage);

    // Inject instances.
    for (Object instance : componentBag.getInstances(ComponentBag.EXCLUDE_META_PROVIDERS)) {
      locator.inject(instance);
    }
    for (Object instance : resourceBag.instances) {
      locator.inject(instance);
    }

    // initiate resource model into JerseyResourceContext
    JerseyResourceContext jerseyResourceContext = locator.getService(JerseyResourceContext.class);
    jerseyResourceContext.setResourceModel(resourceModel);

    this.runtime = locator.createAndInitialize(ServerRuntime.Builder.class).build(rootStage);

    // inject self
    locator.inject(this);
  }