Java org.glassfish.hk2.utilities.binding.AbstractBinder 代码实例

・19 分钟阅读

以下是展示如何使用org.glassfish.hk2.utilities.binding.AbstractBinder的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Override
@SuppressWarnings("unchecked")
public void install(final AbstractBinder binder, final Injector injector, final Class<Object> type) {
    if (is(type, Factory.class)) {
        // register factory directly (without wrapping)
        bindFactory(binder, injector, type);
    } else {
        // support multiple extension interfaces on one type
        final Set<Class<?>> extensions = Sets.intersection(EXTENSION_TYPES,
                GenericsResolver.resolve(type).getGenericsInfo().getComposingTypes());
        if (!extensions.isEmpty()) {
            for (Class<?> ext : extensions) {
                bindSpecificComponent(binder, injector, type, ext);
            }
        } else {
            // no known extension found
            bindComponent(binder, injector, type);
        }
    }
}
 

实例 2


@Override
public final void run(T configuration, Environment environment) throws Exception
{
    environment.jersey().register(DiscoveryResource.class);
    environment.jersey().register(AttributesResource.class);
    environment.jersey().register(PreferencesResource.class);
    environment.jersey().register(AuthResource.class);
    AbstractBinder binder = new AbstractBinder()
    {
        @Override
        protected void configure()
        {
            AuthSpecHolder holder = new AuthSpecHolder(builder.getAuthSpec());
            bind(holder).to(AuthSpecHolder.class);
        }
    };
    environment.jersey().register(binder);
    if ( builder.getAuthSpec() != null )
    {
        environment.servlets().setSessionHandler(new SessionHandler());
    }
    ComponentManager componentManager = SoaBundle.getFeatures(environment).getNamed(ComponentManager.class, SoaFeatures.DEFAULT_NAME);
    for ( TabComponent component : componentManager.getTabs() )
    {
        int index = 0;
        for ( AssetsPath assetsPath : component.getAssetsPaths() )
        {
            AssetServlet servlet = new AssetServlet(assetsPath.getResourcePath(), assetsPath.getUriPath(), null, Charsets.UTF_8);
            environment.servlets().addServlet(component.getName() + index++, servlet).addMapping(assetsPath.getUriPath() + '*');
        }
    }
}
 

实例 3


private Set<? extends Binder> getAdditionalBinders() {
    return Collections.singleton(new AbstractBinder() {
        @Override
        protected void configure() {
            bindFactory(RestAdapter.SubjectReferenceFactory.class).to(new TypeLiteral<Ref<Subject>>() {
            }).in(PerLookup.class);
            bindFactory(ReferencingFactory.<Subject>referenceFactory()).to(new TypeLiteral<Ref<Subject>>() {
            }).in(RequestScoped.class);
        }
    });
}
 

实例 4


public XbddApplication() {
        packages(getClass().getPackage().getName());
        // MVC feature
        register(JspMvcFeature.class);
        register(MultiPartFeature.class);
        // Logging.
        // register(LoggingFilter.class);
        property(ServerProperties.TRACING, TracingConfig.ON_DEMAND.name());
        property(JspProperties.TEMPLATES_BASE_PATH, "WEB-INF/jsp");
        register(new AbstractBinder() {
                @Override
                protected void configure() {
                        bindFactory(ServletContextMongoClientFactory.class).to(MongoDBAccessor.class).in(Singleton.class);
                }
        });
}
 

实例 5


/**
 * Instantiate the main application running on the Myria master.
 * 
 * @param server the Myria server running on this master.
 * @param daemon the Myria daemon running on this master.
 */
public MasterApplication(final Server server, final MasterDaemon daemon) {
  /*
   * Tell Jersey to look for resources inside the entire project, and also for Swagger.
   */
  packages(new String[] { "edu.washington.escience.myria", "com.wordnik.swagger.jersey.listing" });
  /*
   * Disable WADL - throws error messages when using Swagger, and not needed.
   */
  property(ServerProperties.WADL_FEATURE_DISABLE, true);
  /* Enable Jackson's JSON Serialization/Deserialization. */
  register(JacksonJsonProvider.class);
  /* Enable Multipart. */
  register(MultiPartFeature.class);
  /* Register the singleton binder. */
  register(new AbstractBinder() {
    @Override
    protected void configure() {
      /* Singletons binding. */
      bind(server).to(Server.class);
      bind(daemon).to(MasterDaemon.class);
    }
  });
  /* Enable GZIP compression/decompression */
  register(EncodingFilter.class);
  register(GZipEncoder.class);
  /* Swagger configuration -- must come BEFORE Swagger classes are added. */
  BeanConfig myriaBeanConfig = new BeanConfig();
  /*
   * TODO(dhalperi): make this more dynamic based on either Catalog or runtime option.
   */
  myriaBeanConfig.setBasePath("http://rest.myria.cs.washington.edu:1776");
  myriaBeanConfig.setVersion("0.1.0");
  myriaBeanConfig.setResourcePackage("edu.washington.escience.myria.api");
  myriaBeanConfig.setScan(true);
  /* Add a response filter (i.e., runs on all responses) that sets headers for cross-origin objects. */
  register(new CrossOriginResponseFilter());
  /* Add an admin authentication filter. */
  register(new AdminAuthFilter());
}
 

实例 6


public ServerApplication() {
        register(new AbstractBinder() {
                @Override
                protected void configure() {
                        bind(createResourceSet()).to(ResourceSet.class);
                        bind(SampleStore.class).to(ModelStore.class).in(Singleton.class);
                }
        });
        packages("example.server.resources");
        register(JsonResourceBodyReader.class);
        register(JsonResourceBodyWriter.class);
}
 

实例 7


@Override
public Set<Object> getSingletons() {
    return Collections.singleton(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(twitter).to(DataAggregator.class);
        }
    });
}
 

实例 8


public MyApplication() {
    register(JsonApiController.class);
    register(JsonApiObjectMapperResolver.class);
    register(new AbstractBinder() {
        @Override
        protected void configure() {
            bindAsContract(ProjectRepository.class);
            bindAsContract(TaskRepository.class);
            bindAsContract(TaskToProjectRepository.class);
            bindFactory(RequestDispatcherFactory.class).to(RequestDispatcher.class);
            bindFactory(JsonPathFactory.class).to(JsonPath.class);
            bindFactory(RequestParamsFactory.class).to(RequestParams.class);
            bindFactory(ResourceRegistryFactory.class).to(ResourceRegistry.class);
            bindFactory(JsonApiObjectMapperResolver.class).to(ObjectMapper.class);
            bind(JsonInjectResolver.class)
                    .to(new TypeLiteral<InjectionResolver<JsonInject>>() {
                    })
                    .in(Singleton.class);
        }
    });
}
 

实例 9


public DrillRestServer(final WorkManager workManager) {
  register(DrillRoot.class);
  register(StatusResources.class);
  register(StorageResources.class);
  register(ProfileResources.class);
  register(QueryResources.class);
  register(MetricsResources.class);
  register(ThreadsResources.class);
  register(FreemarkerMvcFeature.class);
  register(MultiPartFeature.class);
  property(ServerProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
  //disable moxy so it doesn't conflict with jackson.
  final String disableMoxy = PropertiesHelper.getPropertyNameForRuntime(CommonProperties.MOXY_JSON_FEATURE_DISABLE, getConfiguration().getRuntimeType());
  property(disableMoxy, true);
  register(JsonParseExceptionMapper.class);
  register(JsonMappingExceptionMapper.class);
  register(GenericExceptionMapper.class);
  JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
  provider.setMapper(workManager.getContext().getLpPersistence().getMapper());
  register(provider);
  register(new AbstractBinder() {
    @Override
    protected void configure() {
      bind(workManager).to(WorkManager.class);
      bind(workManager.getContext().getLpPersistence().getMapper()).to(ObjectMapper.class);
      bind(workManager.getContext().getPersistentStoreProvider()).to(PStoreProvider.class);
      bind(workManager.getContext().getStorage()).to(StoragePluginRegistry.class);
    }
  });
}
 

实例 10


private Server(
    int port,
    String path,
    final Collection<DatasetDirectory> datasets,
    final int pageSize) {
  server = GrizzlyHttpServerFactory.createHttpServer(
      uri = URI.create(String.format("http://localhost:%d/%s", port, path)),
      new ResourceConfig()
          .register(Datasets.class)
          .register(Reads.class)
          .register(Readsets.class)
          .register(
              new AbstractBinder() {
                @Override protected void configure() {
                  bind(Backend.create(datasets, pageSize));
                }
              })
          .register(
              new JacksonJaxbJsonProvider() {{
                setMapper(DataTransferObject.OBJECT_MAPPER);
              }}),
      false);
}
 

实例 11


/**
 * This is the constructor called directly by unit tests. This allows us to pass in a mocked version of the
 * {@link SetCallHandler} to just test the functionality of the API and not the handler itself.
 */
public SetApplication(final SetCallHandler setCallHandler) {
        /*
         * Register the mapping between internal exceptions and their outward facing messages.
         */
        register(InvalidRequestExceptionMapper.class);
        register(new AbstractBinder() {
                @Override
                protected void configure() {
                        bind(setCallHandler).to(SetCallHandler.class);
                }
        });
        /*
         * Specify where resource classes are located. These are the classes that constitute the API.
         */
        packages(true, "com.aetherworks.example.jersey2.api");
}
 

实例 12


/**
 * {@inheritDoc}
 */
@Override
public boolean configure(final FeatureContext context) {
    final Configuration config = context.getConfiguration();
    final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(),
            InternalProperties.JSON_FEATURE, JSON_FEATURE, String.class);
    // Other JSON providers registered.
    if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) {
        return false;
    }
    // Disable other JSON providers.
    context.property(
            PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()),
            JSON_FEATURE);
    if (!config.isRegistered(JacksonJaxbJsonProvider.class)) {
        ServiceLocatorUtilities.bind(locator, new AbstractBinder() {
            @Override
            protected void configure() {
                XmlMapper xmlMapper = new XmlMapper();
                ObjectMapper objectMapper = new ObjectMapper();
                JacksonUtils.configureMapper(xmlMapper);
                JacksonUtils.configureMapper(objectMapper);
                bind(xmlMapper).to(XmlMapper.class).proxy(false);
                bind(objectMapper).to(ObjectMapper.class).proxy(false);
            }
        });
        context.register(JsonProcessingExceptionMapper.class);
        if (EntityFilteringFeature.enabled(config)) {
            context.register(JacksonFilteringFeature.class);
            context.register(FilteringJacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
            context.register(FilteringJacksonXMLProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
        } else {
            context.register(JacksonJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
            context.register(JacksonXMLProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
        }
        Collections.addAll(HttpPatchProperties.SUPPORT_PATCH_MEDIA_TYPES,
                MediaType.APPLICATION_JSON,
                MediaType.APPLICATION_XML,
                MediaType.TEXT_XML);
        return true;
    }
    return false;
}
 

实例 13


@Override
protected Application configure() {
    final ResourceConfig resourceConfig = new ResourceConfig(BusinessActionResource.class);
    resourceConfig.register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(new TestBusinessActionHandler()).to(BusinessActionHandler.class);
        }
    });
    resourceConfig.register(ParameterMessageBodyReaderWriter.class);
    return resourceConfig;
}
 

实例 14


public static ServiceLocator createServiceLocator(Binder... customBinders) {
    Binder[] binders = new Binder[customBinders.length + 2];
    binders[0] = new AbstractBinder() {
        @Override
        protected void configure() {
            bindFactory(new Factory<Configuration>() {
                @Override
                public Configuration provide() {
                    return EMPTY_CONFIG;
                }
                @Override
                public void dispose(Configuration instance) {
                    //not used
                }
            }).to(Configuration.class);
            bindFactory(SaxParserFactoryInjectionProvider.class, Singleton.class)
                    .to(SAXParserFactory.class)
                    .in(PerThread.class);
            bindAsContract(MySPFProvider.class).in(Singleton.class);
        }
    };
    binders[1] = new ContextInjectionResolver.Binder();
    System.arraycopy(customBinders, 0, binders, 2, customBinders.length);
    return Injections.createLocator(binders);
}
 

实例 15


public RestAPIResourceConfig() {
  register(new AbstractBinder() {
    @Override
    protected void configure() {
      bindFactory(PipelineStoreInjector.class).to(PipelineStoreTask.class);
      bindFactory(StageLibraryInjector.class).to(StageLibraryTask.class);
      bindFactory(PrincipalInjector.class).to(Principal.class);
      bindFactory(URIInjector.class).to(URI.class);
      bindFactory(ConfigurationInjector.class).to(Configuration.class);
      bindFactory(RuntimeInfoInjector.class).to(RuntimeInfo.class);
      bindFactory(BuildInfoInjector.class).to(BuildInfo.class);
      bindFactory(StandAndClusterManagerInjector.class).to(Manager.class);
    }
  });
  register(RolesAllowedDynamicFeature.class);
  //Hooking up Swagger-Core
  register(ApiListingResource.class);
  register(SwaggerSerializers.class);
  //Configure and Initialize Swagger
  BeanConfig beanConfig = new BeanConfig();
  beanConfig.setVersion("1.0.0");
  beanConfig.setBasePath("/rest");
  beanConfig.setResourcePackage(RestAPI.class.getPackage().getName());
  beanConfig.setScan(true);
  beanConfig.setTitle("Data Collector RESTful API");
  Info info = new Info();
  info.setTitle("Data Collector RESTful API");
  info.setDescription("An Enterprise-Grade Approach to Managing Big Data in Motion");
  info.setVersion("1.0.0");
  beanConfig.setInfo(info);
}
 
讨论
淘淘あ西西 profile image