下面列出了javax.inject.Qualifier#com.google.inject.name.Named 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public ObjectBuilder createModuleAdapter(String moduleName, Class<?> sourceClass, TypeWidget moduleType, TypeWidget contextType, BytecodeExpression sourceProvider) {
gambitScope.addClass(sourceClass);
ObjectBuilder adapter = gambitScope.createObject();
ObjectBuilder.ConstructorBuilder cb = adapter.getConstructor();
ObjectBuilder.FieldBuilder fld = adapter.field("$module", moduleType);
fld.addModifiers(Opcodes.ACC_FINAL);
cb.exec(fld.get(cb.local("this")).write(cb.cast(moduleType,
cb.invokeExact(Location.NONE, "get", Provider.class, AnyTypeWidget.getInstance(), sourceProvider))));
adapter.addParameterField(fld);
ObjectBuilder.FieldBuilder programName = adapter.field("$programName", BaseTypeAdapter.STRING);
programName.annotate(Inject.class);
programName.annotate(Named.class).put("value", "programName");
adapter.addParameterField(programName);
BytecodeExpression metric = gambitScope.constant(PhysicalExprOperatorCompiler.EMPTY_DIMENSION);
metric = metricWith(cb, metric, "source", moduleName);
return adapter;
}
@Inject
public void setTokenDefProvider(@Named(LexerIdeBindings.HIGHLIGHTING) ITokenDefProvider tokenDefProvider) {
Map<Integer, String> map = tokenDefProvider.getTokenDefMap();
int minTokenType = org.antlr.runtime.Token.MIN_TOKEN_TYPE;
allTokenTypesAsString = new String[map.size() + minTokenType];
for(Map.Entry<Integer, String> entry: map.entrySet()) {
String tokenName = entry.getValue();
if ("RULE_RICH_TEXT_START".equals(tokenName) ||
"RULE_RICH_TEXT_END".equals(tokenName) ||
"RULE_RICH_TEXT_INBETWEEN".equals(tokenName) ||
"RULE_COMMENT_RICH_TEXT_END".equals(tokenName) ||
"RULE_COMMENT_RICH_TEXT_INBETWEEN".equals(tokenName)) {
allTokenTypesAsString[entry.getKey()] = tokenName;
}
}
}
@Post
@At("/:port/filter/response")
public Reply<?> addResponseFilter(@Named("port") int port, Request request) throws IOException, ScriptException {
LOG.info("POST /" + port + "/filter/response");
MitmProxyServer proxy = proxyManager.get(port);
if (proxy == null) {
return Reply.saying().notFound();
}
JavascriptRequestResponseFilter requestResponseFilter = new JavascriptRequestResponseFilter();
String script = getEntityBodyFromRequest(request);
requestResponseFilter.setResponseFilterScript(script);
proxy.addResponseFilter(requestResponseFilter);
return Reply.saying().ok();
}
@Inject
public LongPollingChannelLifecycle(CloseableHttpClient httpclient,
RequestConfig defaultRequestConfig,
@Named(MessagingPropertyKeys.CHANNELID) String channelId,
@Named(MessagingPropertyKeys.RECEIVERID) String receiverId,
ObjectMapper objectMapper,
HttpConstants httpConstants,
HttpRequestFactory httpRequestFactory) {
this.httpclient = httpclient;
this.defaultRequestConfig = defaultRequestConfig;
this.channelId = channelId;
this.receiverId = receiverId;
this.objectMapper = objectMapper;
this.httpConstants = httpConstants;
this.httpRequestFactory = httpRequestFactory;
}
@Inject
public ValidatorTester(T validator, EValidatorRegistrar registrar, @Named(Constants.LANGUAGE_NAME) final String languageName) {
this.validator = validator;
EValidator.Registry originalRegistry = registrar.getRegistry();
EValidatorRegistryImpl newRegistry = new EValidatorRegistryImpl();
registrar.setRegistry(newRegistry);
this.validator.register(registrar);
diagnostician = new Diagnostician(newRegistry) {
@Override
public java.util.Map<Object,Object> createDefaultContext() {
java.util.Map<Object,Object> map = super.createDefaultContext();
map.put(AbstractInjectableValidator.CURRENT_LANGUAGE_NAME, languageName);
return map;
}
};
registrar.setRegistry(originalRegistry);
validatorCalled = false;
}
@Inject
public CarbonTextServer(FilterEventBus eventBus,
TagParser tagParser, @Named("kairosdb.carbon.text.port") int port,
@Named("kairosdb.carbon.text.address") String address)
{
m_port = port;
m_publisher = checkNotNull(eventBus).createPublisher(DataPointEvent.class);
m_tagParser = tagParser;
m_address = null;
try
{
m_address = InetAddress.getByName(address);
}
catch (UnknownHostException e)
{
logger.error("Unknown host name " + address + ", will bind to 0.0.0.0");
}
}
@Inject
protected SceneTemplateRequestHandler(
@Named(PROP_THREADPOOL) Executor executor,
PlatformMessageBus platformBus,
SceneTemplateManager sceneTemplateDao,
BeanAttributesTransformer<SceneTemplateEntity> transformer,
GetAttributesModelRequestHandler getAttributesRequestHandler,
CreateRequestHandler createHandler,
ResolveActionsRequestHandler resolveActionsHandler
) {
super(platformBus, SceneTemplateCapability.NAMESPACE, executor);
this.sceneTemplateManager = sceneTemplateDao;
this.transformer = transformer;
// TODO change to a builder pattern?
this.dispatcher =
RequestHandlers
.toDispatcher(
platformBus,
RequestHandlers.toRequestHandler(templateModelLoader, getAttributesRequestHandler),
RequestHandlers.toRequestHandler(templateEntityLoader, createHandler),
RequestHandlers.toRequestHandler(templateLoader, resolveActionsHandler)
);
}
@Inject
public IpcdService(
PlatformMessageBus platformBus,
@Named(PROP_THREADPOOL) Executor executor,
IpcdRegistry registry,
IpcdDeviceDao ipcdDeviceDao,
DeviceDAO devDao,
BeanAttributesTransformer<com.iris.messages.model.Device> devTransformer,
PlacePopulationCacheManager populationCacheMgr
) {
super(platformBus, executor);
this.registry = registry;
this.bus = platformBus;
this.ipcdDeviceDao = ipcdDeviceDao;
this.devDao = devDao;
this.devTransformer = devTransformer;
this.populationCacheMgr = populationCacheMgr;
}
private ProxyDriverIntegrator getProxyDriverIntegrator(RequestFilter recordRequestFilter,
WebDriverSupplier webDriverSupplier,
DriverServiceSupplier driverServiceSupplier,
@Named(PATH_TO_DRIVER) String pathToDriverExecutable,
@Named(SCREEN) String screen,
@Named(TIMEOUT) int timeout,
ResponseFilter responseFilter) throws IOException {
BrowserMobProxy proxy = createBrowserMobProxy(timeout, recordRequestFilter, responseFilter);
proxy.start(0);
logger.info("Proxy running on port " + proxy.getPort());
Proxy seleniumProxy = createSeleniumProxy(proxy);
DesiredCapabilities desiredCapabilities = createDesiredCapabilities(seleniumProxy);
DriverService driverService = driverServiceSupplier.getDriverService(pathToDriverExecutable, screen);
WebDriver driver = webDriverSupplier.get(driverService, desiredCapabilities);
return new ProxyDriverIntegrator(driver, proxy, driverService);
}
@Inject
public ScheduledRetryProcessor(
NotificationServiceConfig config,
RetryManager retryManager,
NotificationAuditor auditor,
Dispatcher dispatcher,
@Named("notifications.executor") ExecutorService executor
) {
this.retryManager = retryManager;
this.auditor = auditor;
this.dispatcher = dispatcher;
this.executor = executor;
ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("notifications-retry-%d").build();
this.scheduler = Executors.newScheduledThreadPool(config.getMaxRetryThreads(), factory);
}
@Inject
public StaticCapabilitiesProvisioning(@Named(PROPERTY_PROVISIONED_CAPABILITIES_FILE) String provisionedCapabilitiesFile,
@Named(CHANNELID) String localChannelId,
ObjectMapper objectMapper,
LegacyCapabilitiesProvisioning legacyCapabilitiesProvisioning,
ResourceContentProvider resourceContentProvider,
@Named(MessagingPropertyKeys.GBID_ARRAY) String[] gbids) {
internalInterfaces = new HashSet<String>();
internalInterfaces.add(GlobalCapabilitiesDirectory.INTERFACE_NAME);
internalInterfaces.add(GlobalDomainAccessController.INTERFACE_NAME);
internalInterfaces.add(GlobalDomainRoleController.INTERFACE_NAME);
internalInterfaces.add(GlobalDomainAccessControlListEditor.INTERFACE_NAME);
discoveryEntries = new HashSet<>();
this.gbids = gbids.clone();
this.resourceContentProvider = resourceContentProvider;
addEntriesFromJson(provisionedCapabilitiesFile, objectMapper, localChannelId);
logger.trace("{} provisioned discovery entries loaded from JSON: {}",
discoveryEntries.size(),
discoveryEntries);
overrideEntriesFromLegacySettings(legacyCapabilitiesProvisioning);
logger.trace("{} provisioned discovery entries after adding legacy entries: {}",
discoveryEntries.size(),
discoveryEntries);
logger.debug("Statically provisioned discovery entries loaded: {}", discoveryEntries);
}
@Named("webhook:create-webhook")
@Documentation({"https://docs.atlassian.com/bitbucket-server/rest/5.14.1/bitbucket-rest.html#idm45367160974656"})
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{project}/repos/{repo}/webhooks")
@Fallback(BitbucketFallbacks.WebHookOnError.class)
@POST
WebHook create(@PathParam("project") String project,
@PathParam("repo") String repo,
@BinderParam(BindToJsonPayload.class) CreateWebHook webHook);
@Inject
public VideoRecordingServer(
PlaceDAO placeDao,
VideoRecordingManager dao,
RecordingEventPublisher eventPublisher,
VideoStorage videoStorage,
VideoRecordingServerConfig videoConfig,
VideoSessionRegistry registry,
BridgeServerTlsContext serverTlsContext,
Provider<TrafficHandler> trafficHandlerProvider,
@Named("videoBossGroup") EventLoopGroup videoBossGroup,
@Named("videoWorkerGroup") EventLoopGroup videoWorkerGroup,
@Named("videoTcpChannelOptions") Map<ChannelOption<?>, Object> videoChildChannelOptions,
@Named("videoTcpParentChannelOptions") Map<ChannelOption<?>, Object> videoParentChannelOptions,
@Named("bridgeEventLoopProvider") BridgeServerEventLoopProvider eventLoopProvider,
VideoTtlResolver ttlResolver
) {
this.placeDao = placeDao;
this.dao = dao;
this.eventPublisher = eventPublisher;
this.videoStorage = videoStorage;
this.videoConfig = videoConfig;
this.registry = registry;
this.videoBossGroup = videoBossGroup;
this.videoWorkerGroup = videoWorkerGroup;
this.serverTlsContext = serverTlsContext;
this.videoChildChannelOptions = videoChildChannelOptions;
this.videoParentChannelOptions = videoParentChannelOptions;
this.trafficHandlerProvider = trafficHandlerProvider;
this.eventLoopProvider = eventLoopProvider;
this.ttlResolver = ttlResolver;
}
@ProvidesIntoMap
@StringMapKey("amqp_queue")
@Singleton
@Named(EVENT_QUEUE_PROVIDERS_QUALIFIER)
public EventQueueProvider getAMQQueueEventQueueProvider(Configuration config) {
return new AMQPEventQueueProvider(config, false);
}
@Inject
public ProductCatalogService(
PlatformMessageBus platformBus,
@Named(PROP_THREADPOOL) Executor executor,
Set<ContextualRequestMessageHandler<ProductCatalog>> handlers,
PopulationDAO populationDao,
ProductCatalogManager manager
) {
super(platformBus, executor, handlers, Collections.<ContextualEventMessageHandler<ProductCatalog>>emptySet());
this.populationDao = populationDao;
this.manager = manager;
}
@Provides
@Named(BARAGON_URI_BASE)
String getBaragonUriBase(final BaragonConfiguration configuration,
@Named(BARAGON_SERVICE_DW_CONFIG) BaragonServiceDWSettings dwSettings) {
final String baragonUiPrefix = configuration.getUiConfiguration().getBaseUrl().or(dwSettings.getContextPath());
return (baragonUiPrefix.endsWith("/")) ? baragonUiPrefix.substring(0, baragonUiPrefix.length() - 1) : baragonUiPrefix;
}
/**
* Provides a immutable map with Shard id to Shard Host Model mapping.
*
* @param masterSlavePairList
* @return
*/
@Provides
@Singleton
@Named("fluxShardIdToShardPairMap")
public Map<ShardId, ShardPairModel> getFluxRWShardIdToShardMapping(@Named("fluxMasterSlavePairList") List<ShardPairModel> masterSlavePairList) {
Map shardIdToShardHostModelMap = new HashMap<ShardId, ShardPairModel>();
masterSlavePairList.forEach(masterSlavePair -> {
shardIdToShardHostModelMap.put(masterSlavePair.getShardId(), masterSlavePair);
});
assert masterSlavePairList.size() == shardIdToShardHostModelMap.size();
return shardIdToShardHostModelMap;
}
@Post
@At("/:port/headers")
public Reply<?> updateHeaders(@Named("port") int port, Request request) {
LOG.info("POST /" + port + "/headers");
MitmProxyServer proxy = proxyManager.get(port);
if (proxy == null) {
return Reply.saying().notFound();
}
Map<String, String> headers = request.read(Map.class).as(Json.class);
headers.forEach(proxy::addHeader);
return Reply.saying().ok();
}
@Named("webhook:delete-webhook")
@Documentation({"https://docs.atlassian.com/bitbucket-server/rest/5.14.1/bitbucket-rest.html#idm45367160891616"})
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{project}/repos/{repo}/webhooks/{webHookKey}")
@Fallback(BitbucketFallbacks.RequestStatusOnError.class)
@ResponseParser(RequestStatusParser.class)
@DELETE
RequestStatus delete(@PathParam("project") String project,
@PathParam("repo") String repo,
@PathParam("webHookKey") String webHookKey);
@Inject
public void init(LoggerFactory lfactory,
MetricRegistry mRegistry,
@Named("kafka-producerProperties") Map<String, String> producerProps) {
logger = lfactory.getLogger(KafkaMessageForwarder.class) ;
logger.info("Start init()");
logger.info("Kafka Producer Properties: \n" + JSONSerializer.INSTANCE.toString(producerProps));
producer = new KafkaMessageProducer(producerProps, mRegistry, "127.0.0.1:9092") ;
logger.info("Finish init()");
}
@Provides
@Singleton
protected StashStateListener provideStashStateListener(MetricsStashStateListener metricsListener,
Optional<SNSStashStateListener> snsListener,
@Named("plugin") List<StashStateListener> pluginListeners) {
List<StashStateListener> listeners = Lists.newArrayListWithCapacity(3);
listeners.add(metricsListener);
if (snsListener.isPresent()) {
listeners.add(snsListener.get());
}
listeners.addAll(pluginListeners);
return MultiStashStateListener.combine(listeners);
}
@Inject
public CassandraActivityDao(
@Named(CassandraHistory.NAME) Session session,
HistoryAppenderConfig config
) {
this.bucketSizeMs = (int) TimeUnit.SECONDS.toMillis(config.getActivityBucketSizeSec());
this.rowTtlMs = TimeUnit.HOURS.toMillis(config.getActivitySubsysTtlHours());
this.session = session;
this.upsert =
CassandraQueryBuilder
.update(TABLE_NAME)
.set(
// anything that was active in this window counts as active
Columns.ACTIVE_DEVICES + " = " + Columns.ACTIVE_DEVICES + " + ?, " +
// only things that are inactive *at the end of the window* count as inactive
Columns.DEACTIVATED_DEVICES + " = ?"
)
.addWhereColumnEquals(Columns.PLACE_ID)
.addWhereColumnEquals(Columns.TIME)
.withTtlSec(TimeUnit.HOURS.toSeconds(config.getActivitySubsysTtlHours()))
.usingTimestamp()
.prepare(session);
this.listByRange =
CassandraQueryBuilder
.select(TABLE_NAME)
.addColumns(Columns.PLACE_ID, Columns.TIME, Columns.ACTIVE_DEVICES, Columns.DEACTIVATED_DEVICES)
.where(Columns.PLACE_ID + " = ? AND " + Columns.TIME + " >= ? AND " + Columns.TIME + " < ?")
.withConsistencyLevel(ConsistencyLevel.LOCAL_ONE)
.prepare(session);
}
/**
* Optionally returns the qualifier annotation of a class.
*/
public static Optional<Annotation> getQualifier(AnnotatedElement annotatedElement) {
AnnotatedElement cleanedAnnotatedElement;
if (annotatedElement instanceof Class<?>) {
cleanedAnnotatedElement = ProxyUtils.cleanProxy((Class<?>) annotatedElement);
} else {
cleanedAnnotatedElement = annotatedElement;
}
return Annotations.on(cleanedAnnotatedElement)
.findAll()
.filter(annotationAnnotatedWith(Qualifier.class, false).or(annotationIsOfClass(Named.class)))
.findFirst();
}
@Named("hook:get-hook")
@Documentation({"https://developer.atlassian.com/static/rest/bitbucket-server/5.0.1/bitbucket-rest.html#idm45993794409760"})
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{project}/repos/{repo}/settings/hooks/{hookKey}")
@Fallback(BitbucketFallbacks.HookOnError.class)
@GET
Hook get(@PathParam("project") String project,
@PathParam("repo") String repo,
@PathParam("hookKey") String hookKey);
@Provides
@Singleton
@Named("dao")
RoleManager provideRoleManagerDAO(AuthorizationConfiguration config, DataStore dataStore,
PermissionManager permissionManager, @SystemTablePlacement String tablePlacement) {
return new TableRoleManagerDAO(dataStore, config.getRoleTable(), config.getRoleGroupTable(),
tablePlacement, permissionManager);
}
@Inject
public Fabric8AuthServiceClient(
@Named("che.fabric8.auth.endpoint") String baseAuthUrl,
KeycloakSettings keycloakSettings,
JwtParser jwtParser) {
super(keycloakSettings, jwtParser);
this.githubTokenEndpoint = baseAuthUrl + GITHUB_TOKEN_API_PATH;
this.githubLinkEndpoint = baseAuthUrl + GITHUB_LINK_API_PATH;
}
@Inject
public ApplicationA(@Named("Init") CountDownLatch initLatch,
@Named("Start") CountDownLatch startLatch,
@Named("Stop") CountDownLatch stopLatch,
@Named("Destroy") CountDownLatch destroyLatch)
{
this.startLatch = startLatch;
this.stopLatch = stopLatch;
this.destroyLatch = destroyLatch;
initLatch.countDown();
}
@Inject
public SmartHomeSkillV3Handler(
ShsConfig config,
PlatformMessageBus bus,
@Named(VoiceBridgeConfig.NAME_EXECUTOR) ExecutorService executor,
VoiceBridgeMetrics metrics,
PlacePopulationCacheManager populationCacheMgr
) {
this.config = config;
this.executor = executor;
this.busClient = new PlatformBusClient(bus, executor, ImmutableSet.of(AddressMatchers.equals(AlexaUtil.ADDRESS_BRIDGE)));
this.metrics = metrics;
this.populationCacheMgr = populationCacheMgr;
}
@Provides
@Singleton
@Inject
@Named("ActiveApiRegistry")
protected OperationServiceRegistry provideActiveApiRegistry(Injector injector) {
return new ActiveApiOperationServiceRegistry(injector);
}
@Inject
public HttpPermissionCheckerImpl(
@Named("che.api") String apiEndpoint, HttpJsonRequestFactory requestFactory) {
// TODO mb make configurable size of cache and expiration time
this.permissionsCache =
CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(1, TimeUnit.MINUTES)
.build(
new CacheLoader<Key, Set<String>>() {
@Override
public Set<String> load(Key key) throws Exception {
UriBuilder currentUsersPermissions =
UriBuilder.fromUri(apiEndpoint).path("permissions/" + key.domain);
if (key.instance != null) {
currentUsersPermissions.queryParam("instance", key.instance);
}
String userPermissionsUrl = currentUsersPermissions.build().toString();
try {
PermissionsDto usersPermissions =
requestFactory
.fromUrl(userPermissionsUrl)
.useGetMethod()
.request()
.asDto(PermissionsDto.class);
return new HashSet<>(usersPermissions.getActions());
} catch (NotFoundException e) {
// user doesn't have permissions
return new HashSet<>();
}
}
});
}