com.google.inject.TypeLiteral

Here are the examples of the java api com.google.inject.TypeLiteral taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

71 Examples 7

19 Source : AppControllerRegistrarBase.java
with Apache License 2.0
from YANG-DB

public abstract clreplaced AppControllerRegistrarBase<TController> implements AppRegistrar {

    // region Constructors
    public AppControllerRegistrarBase(Clreplaced<? extends TController> klreplaced) {
        this.klreplaced = klreplaced;
    }

    public AppControllerRegistrarBase(TypeLiteral<TController> typeLiteral) {
        this.typeLiteral = typeLiteral;
    }

    // endregion
    // region Protected Methods
    protected TController getController(Jooby app) {
        if (this.klreplaced != null) {
            return app.require(this.klreplaced);
        }
        if (this.typeLiteral != null) {
            return app.require(this.typeLiteral);
        }
        return null;
    }

    // endregion
    // region Fields
    private Clreplaced<? extends TController> klreplaced;

    private TypeLiteral<TController> typeLiteral;
    // endregion
}

19 Source : PlanOperatorTypes.java
with Apache License 2.0
from yahoo

public final clreplaced PlanOperatorTypes {

    public static final TypeLiteral<List<OperatorNode<StreamOperator>>> STREAM_OPERATORS = new TypeLiteral<List<OperatorNode<StreamOperator>>>() {
    };

    private PlanOperatorTypes() {
    }

    public static final TypeLiteral<List<OperatorNode<PhysicalExprOperator>>> EXPRS = new TypeLiteral<List<OperatorNode<PhysicalExprOperator>>>() {
    };

    public static final TypeLiteral<List<OperatorValue>> VALUES = new TypeLiteral<List<OperatorValue>>() {
    };
}

19 Source : PrimitiveParserManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Binds {@link Parser<T>} to the given type, and {@link NodeParser<T>} to {@link PrimitiveNodeParser<T>}
 */
public clreplaced PrimitiveParserManifest<T> extends KeyedManifest implements ParserTypeLiterals {

    private final TypeLiteral<T> T;

    private final TypeLiteral<? extends Parser<T>> ParserTImpl;

    public PrimitiveParserManifest(Clreplaced<T> type, Clreplaced<? extends Parser<T>> ParserTImpl) {
        this(TypeLiteral.get(type), TypeLiteral.get(ParserTImpl));
    }

    public PrimitiveParserManifest(TypeLiteral<T> T, TypeLiteral<? extends Parser<T>> ParserTImpl) {
        this.T = T;
        this.ParserTImpl = ParserTImpl;
    }

    @Override
    protected Object manifestKey() {
        return Pair.of(T, ParserTImpl);
    }

    @Override
    protected void configure() {
        bind(ParserTImpl);
        bind(Parser(T)).to(ParserTImpl);
        bind(NodeParser(T)).to(PrimitiveNodeParser(T));
        bind(ElementParser(T)).to(NodeParser(T));
        bind(DoreplacedentParser(T)).to(NodeParser(T));
    }
}

19 Source : EnumParser.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public clreplaced EnumParser<T extends Enum<T>> implements Parser<T> {

    private final TypeLiteral<T> type;

    @Inject
    private EnumParser(TypeLiteral<T> type) {
        this.type = type;
    }

    @Override
    public TypeLiteral<T> paramLiteral() {
        return type;
    }

    @Override
    public TypeToken<T> paramToken() {
        return Types.toToken(type);
    }

    @Override
    public T parse(String text) throws ParseException {
        final Clreplaced<T> type = paramClreplaced();
        text = text.trim().replace(' ', '_');
        try {
            // First, try the fast way
            return Enum.valueOf(type, text.toUpperCase());
        } catch (IllegalArgumentException ex) {
            // If that fails, search for a case-insensitive match, without replaceduming enums are always uppercase
            for (T value : type.getEnumConstants()) {
                if (value.name().equalsIgnoreCase(text))
                    return value;
            }
            throw new ValueException("Unknown " + readableTypeName() + " value '" + text + "'");
        }
    }
}

19 Source : EnumParserManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Configures parsing for enum type {@link T} using {@link EnumParser <T>}
 */
public clreplaced EnumParserManifest<T extends Enum<T>> extends KeyedManifest implements ParserTypeLiterals {

    private final TypeLiteral<T> T;

    public EnumParserManifest(Clreplaced<T> T) {
        this(TypeLiteral.get(T));
    }

    public EnumParserManifest(TypeLiteral<T> T) {
        this.T = T;
    }

    @Override
    protected Object manifestKey() {
        return T;
    }

    @Override
    protected void configure() {
        install(new PrimitiveParserManifest<>(T, EnumParser(T)));
    }
}

19 Source : ProxiedManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * @see Proxied
 */
public clreplaced ProxiedManifest<T> extends KeyedManifest {

    private final TypeLiteral<T> type;

    public ProxiedManifest(TypeLiteral<T> type) {
        this.type = type;
    }

    @Override
    protected Object manifestKey() {
        return type;
    }

    @Override
    protected void configure() {
        if (!type.getRawType().isInterface()) {
            addError("Cannot proxy " + type + " because it is not an interface");
        }
        bind(type).annotatedWith(Proxied.clreplaced).toProvider(new ResolvableType<ProxyProvider<T>>() {
        }.where(new TypeParameter<T>() {
        }, type));
    }
}

19 Source : EnumParserManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public clreplaced EnumParserManifest<T extends Enum<T>> extends TypeManifest<T> implements ParserBinders {

    private final TypeLiteral<EnumParser<T>> parserType;

    protected EnumParserManifest() {
        this((TypeLiteral) null);
    }

    public EnumParserManifest(Clreplaced<T> type) {
        this(TypeLiteral.get(type));
    }

    public EnumParserManifest(@Nullable TypeLiteral<T> type) {
        super(type);
        this.parserType = resolve(new TypeLiteral<EnumParser<T>>() {
        });
    }

    @Override
    protected void configure() {
        bind(parserType);
        bindPrimitiveParser(type).to(parserType);
    }
}

19 Source : FeatureManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Links {@link Parser}, {@link ElementParser}, and {@link PrimitiveParser} to {@link FeatureParser} for feature {@link T}.
 *
 * This manifest does not bind {@link FeatureParser} explicitly, but it is eligible for JIT binding.
 */
public clreplaced FeatureManifest<T extends FeatureDefinition> extends KeyedManifest implements ParserTypeLiterals, FeatureTypeLiterals {

    private final TypeLiteral<T> T;

    protected FeatureManifest() {
        this((TypeLiteral<T>) null);
    }

    public FeatureManifest(@Nullable Clreplaced<T> T) {
        this(TypeLiteral.get(T));
    }

    public FeatureManifest(@Nullable TypeLiteral<T> T) {
        this.T = T != null ? Types.replacedertFullySpecified(T) : new ResolvableType<T>() {
        }.in(getClreplaced());
    }

    @Override
    protected Object manifestKey() {
        return T;
    }

    @Override
    protected void configure() {
        bind(Parser(T)).to(ElementParser(T));
        bind(ElementParser(T)).to(FeatureParser(T));
        bind(PrimitiveParser(T)).to(FeatureParser(T));
    }
}

19 Source : SchedulerModule.java
with Apache License 2.0
from Netflix

public final clreplaced SchedulerModule extends AbstractModule {

    public static final String KUBE_CONSTRAINT = "kubeConstraint";

    private static final TypeLiteral<ConstraintEvaluatorTransformer<Pair<String, String>>> V3_CONSTRAINT_EVALUATOR_TRANSFORMER_TYPE = new TypeLiteral<ConstraintEvaluatorTransformer<Pair<String, String>>>() {
    };

    @Override
    protected void configure() {
        bind(VMOperations.clreplaced).to(VMOperationsImpl.clreplaced);
        bind(TierSlaUpdater.clreplaced).to(DefaultTierSlaUpdater.clreplaced);
        bind(PreferentialNamedConsumableResourceEvaluator.clreplaced).to(replacedusNetworkInterfaceFitnessEvaluator.clreplaced);
        bind(new TypeLiteral<SchedulingService<? extends TaskRequest>>() {
        }).to(DefaultSchedulingService.clreplaced).asEagerSingleton();
        bind(AgentResourceCache.clreplaced).to(DefaultAgentResourceCache.clreplaced);
        bind(SystemSoftConstraint.clreplaced).to(DefaultSystemSoftConstraint.clreplaced);
        bind(SystemHardConstraint.clreplaced).to(DefaultSystemHardConstraint.clreplaced);
        bind(AgentQualityTracker.clreplaced).to(ContainerFailureBasedAgentQualityTracker.clreplaced);
        bind(V3_CONSTRAINT_EVALUATOR_TRANSFORMER_TYPE).to(V3ConstraintEvaluatorTransformer.clreplaced);
        bind(SchedulerServiceGrpc.SchedulerServiceImplBase.clreplaced).to(DefaultSchedulerServiceGrpc.clreplaced);
        bind(SchedulerService.clreplaced).to(DefaultSchedulerService.clreplaced);
    }

    @Provides
    @Singleton
    public SchedulerConfiguration getSchedulerConfiguration(ConfigProxyFactory factory) {
        return factory.newProxy(SchedulerConfiguration.clreplaced);
    }

    @Provides
    @Singleton
    @Named(KUBE_CONSTRAINT)
    public SystemConstraint getKubeConstraint(MesosConfiguration mesosConfiguration, Injector injector) {
        if (mesosConfiguration.isKubeApiServerIntegrationEnabled()) {
            return injector.getInstance(KubeConstraint.clreplaced);
        }
        return new NoOpConstraint();
    }
}

19 Source : V3EndpointModule.java
with Apache License 2.0
from Netflix

public clreplaced V3EndpointModule extends AbstractModule {

    public static final TypeLiteral<LogStorageInfo<Task>> V3_LOG_STORAGE_INFO = new TypeLiteral<LogStorageInfo<Task>>() {
    };

    @Override
    protected void configure() {
        bind(JobManagementServiceImplBase.clreplaced).to(DefaultJobManagementServiceGrpc.clreplaced);
    }
}

19 Source : TitusGatewayModule.java
with Apache License 2.0
from Netflix

// Common module dependencies
// Server dependencies
/**
 * This is the "main" module where we wire everything up. If you see this module getting overly
 * complex, it's a good idea to break things off into separate ones and install them here instead.
 */
public final clreplaced replacedusGatewayModule extends AbstractModule {

    public static final TypeLiteral<LogStorageInfo<Task>> V3_LOG_STORAGE_INFO = new TypeLiteral<LogStorageInfo<Task>>() {
    };

    private final boolean enableREST;

    private final boolean enableRelocationService;

    public replacedusGatewayModule() {
        this(true, true);
    }

    public replacedusGatewayModule(boolean enableREST, boolean enableRelocationService) {
        this.enableREST = enableREST;
        this.enableRelocationService = enableRelocationService;
    }

    @Override
    protected void configure() {
        bind(Archaius2ConfigurationLogger.clreplaced).asEagerSingleton();
        bind(Registry.clreplaced).toInstance(new DefaultRegistry());
        bind(SystemLogService.clreplaced).to(LoggingSystemLogService.clreplaced);
        bind(SystemAbortListener.clreplaced).to(LoggingSystemAbortListener.clreplaced);
        install(new ContainerEventBusModule());
        install(new replacedusContainerRegistryModule());
        install(new replacedusEnreplacedySanitizerModule());
        install(new replacedusAdmissionModule());
        install(new JobSecurityValidatorModule());
        // Feature flags
        install(new FeatureFlagModule());
        install(new GatewayEndpointModule(enableREST));
        install(new replacedusMasterConnectorModule());
        install(new JobManagerConnectorModule());
        install(new JobManagerDataReplicationModule());
        install(new EvictionConnectorModule());
        install(new MachineConnectorModule());
        // Integration with the task relocation service is required, as we have to inject a migration plan
        // into GRPC Task object context. This is needed to preserve the API compatibility with the legacy
        // task migration API.
        if (enableRelocationService) {
            install(new RelocationClientConnectorModule());
        } else {
            install(new NoOpRelocationConnectorModule());
        }
        install(new RelocationDataReplicationModule());
        bind(V3_LOG_STORAGE_INFO).toInstance(EmptyLogStorageInfo.INSTANCE);
        install(new V3ServiceModule());
        install(new StoreModule());
    }

    @Provides
    @Singleton
    replacedusGatewayConfiguration getConfiguration(ConfigProxyFactory factory) {
        return factory.newProxy(replacedusGatewayConfiguration.clreplaced);
    }

    @Provides
    @Singleton
    public replacedusRuntime getreplacedusRuntime(SystemLogService systemLogService, SystemAbortListener systemAbortListener, Registry registry) {
        CodeInvariants codeInvariants = new CompositeCodeInvariants(LoggingCodeInvariants.getDefault(), new SpectatorCodeInvariants(registry.createId("replacedus.runtime.invariant.violations"), registry));
        return new DefaultreplacedusRuntime(codeInvariants, systemLogService, false, systemAbortListener, registry);
    }

    @Provides
    @Singleton
    public GrpcToReactorServerFactory getGrpcToReactorServerFactory(CallMetadataResolver callMetadataResolver) {
        return new DefaultGrpcToReactorServerFactory<>(CallMetadata.clreplaced, () -> callMetadataResolver.resolve().orElse(CallMetadataConstants.UNDEFINED_CALL_METADATA));
    }
}

19 Source : BindingsTest.java
with Apache License 2.0
from aurora-scheduler

public clreplaced BindingsTest {

    private static final TypeLiteral<List<String>> STRING_LIST = new TypeLiteral<List<String>>() {
    };

    @Retention(RUNTIME)
    @BindingAnnotation
    @interface BindKey {
    }

    @Retention(RUNTIME)
    @Qualifier
    @interface QualifierKey {
    }

    @Test
    public void testCheckBindingAnnotation() {
        Bindings.checkBindingAnnotation(BindKey.clreplaced);
        try {
            Bindings.checkBindingAnnotation((Clreplaced<? extends Annotation>) null);
            fail();
        } catch (NullPointerException e) {
        // expected
        }
        try {
            Bindings.checkBindingAnnotation(BindingAnnotation.clreplaced);
            fail();
        } catch (IllegalArgumentException e) {
        // expected
        }
    }

    public BindingsTest() {
        // To change body of overridden methods use File | Settings | File Templates.
        super();
    }

    @Test
    public void testPlainKeyFactory() {
        replacedert.replacedertEquals(Key.get(String.clreplaced), Bindings.KeyFactory.PLAIN.create(String.clreplaced));
        replacedert.replacedertEquals(Key.get(STRING_LIST), Bindings.KeyFactory.PLAIN.create(STRING_LIST));
    }

    @Test
    public void testAnnotationTypeKeyFactory() {
        Bindings.KeyFactory factory = Bindings.annotatedKeyFactory(QualifierKey.clreplaced);
        replacedertEquals(Key.get(String.clreplaced, QualifierKey.clreplaced), factory.create(String.clreplaced));
        replacedertEquals(Key.get(STRING_LIST, QualifierKey.clreplaced), factory.create(STRING_LIST));
    }

    @Test
    public void testExposing() {
        Injector injector = Guice.createInjector(Bindings.exposing(Key.get(String.clreplaced), new AbstractModule() {

            @Override
            protected void configure() {
                bind(String.clreplaced).toInstance("jake");
                bind(Integer.clreplaced).toInstance(42);
            }
        }));
        replacedertTrue(injector.getBindings().containsKey(Key.get(String.clreplaced)));
        replacedertEquals("jake", injector.getInstance(String.clreplaced));
        replacedertFalse(injector.getBindings().containsKey(Key.get(Integer.clreplaced)));
    }
}

19 Source : GoogleModule.java
with Apache License 2.0
from arcus-smart-home

public clreplaced GoogleModule extends AbstractIrisModule {

    private static final TypeLiteral<String> KEY_LITERAL = new TypeLiteral<String>() {
    };

    private static final TypeLiteral<ProactiveReportHandler> VALUE_LITERAL = new TypeLiteral<ProactiveReportHandler>() {
    };

    @Override
    protected void configure() {
        MapBinder<String, ProactiveReportHandler> handlers = MapBinder.newMapBinder(binder(), KEY_LITERAL, VALUE_LITERAL);
        handlers.addBinding(VoiceService.StartPlaceRequest.replacedISTANT_GOOGLE).to(GoogleProactiveReportHandler.clreplaced);
        Multibinder<VoiceProvider> providerMultibinder = bindSetOf(VoiceProvider.clreplaced);
        providerMultibinder.addBinding().to(GoogleService.clreplaced);
    }
}

19 Source : AlexaModule.java
with Apache License 2.0
from arcus-smart-home

public clreplaced AlexaModule extends AbstractIrisModule {

    private static final TypeLiteral<String> KEY_LITERAL = new TypeLiteral<String>() {
    };

    private static final TypeLiteral<ProactiveReportHandler> VALUE_LITERAL = new TypeLiteral<ProactiveReportHandler>() {
    };

    @Override
    protected void configure() {
        MapBinder<String, ProactiveReportHandler> handlers = MapBinder.newMapBinder(binder(), KEY_LITERAL, VALUE_LITERAL);
        handlers.addBinding(VoiceService.StartPlaceRequest.replacedISTANT_ALEXA).to(AlexaProactiveReportHandler.clreplaced);
        Multibinder<VoiceProvider> providerMultibinder = bindSetOf(VoiceProvider.clreplaced);
        providerMultibinder.addBinding().to(AlexaService.clreplaced);
    }
}

18 Source : TypeCheckers.java
with Apache License 2.0
from yahoo

public final clreplaced TypeCheckers {

    public static final TypeLiteral<List<String>> LIST_OF_STRING = new TypeLiteral<List<String>>() {
    };

    public static final TypeLiteral<List<List<String>>> LIST_OF_LIST_OF_STRING = new TypeLiteral<List<List<String>>>() {
    };

    public static final TypeLiteral<List<OperatorNode<SequenceOperator>>> SEQUENCES = new TypeLiteral<List<OperatorNode<SequenceOperator>>>() {
    };

    public static final TypeLiteral<List<OperatorNode<ExpressionOperator>>> EXPRS = new TypeLiteral<List<OperatorNode<ExpressionOperator>>>() {
    };

    public static final TypeLiteral<List<List<OperatorNode<ExpressionOperator>>>> LIST_OF_EXPRS = new TypeLiteral<List<List<OperatorNode<ExpressionOperator>>>>() {
    };

    public static final ImmutableSet<Clreplaced<?>> LITERAL_TYPES = ImmutableSet.<Clreplaced<?>>builder().add(String.clreplaced).add(Integer.clreplaced).add(Double.clreplaced).add(Boolean.clreplaced).add(Float.clreplaced).add(Byte.clreplaced).add(Long.clreplaced).add(List.clreplaced).add(Map.clreplaced).build();

    private TypeCheckers() {
    }

    public static ArgumentsTypeChecker make(Operator target, Object... types) {
        // Clreplaced<?> extends Operator -> NodeTypeChecker
        if (types == null) {
            types = new Object[0];
        }
        List<OperatorTypeChecker> checkers = Lists.newArrayListWithCapacity(types.length);
        for (int i = 0; i < types.length; ++i) {
            checkers.add(createChecker(target, i, types[i]));
        }
        return new ArgumentsTypeChecker(target, checkers);
    }

    // this is festooned with instance checkes before all the casting
    @SuppressWarnings("unchecked")
    private static OperatorTypeChecker createChecker(Operator parent, int idx, Object value) {
        if (value instanceof TypeLiteral) {
            TypeLiteral<?> lit = (TypeLiteral<?>) value;
            Clreplaced<?> raw = lit.getRawType();
            if (List.clreplaced.isreplacedignableFrom(raw)) {
                Preconditions.checkArgument(lit.getType() instanceof ParameterizedType, "TypeLiteral without a ParameterizedType for List");
                ParameterizedType type = (ParameterizedType) lit.getType();
                TypeLiteral<?> arg = TypeLiteral.get(type.getActualTypeArguments()[0]);
                if (OperatorNode.clreplaced.isreplacedignableFrom(arg.getRawType())) {
                    Preconditions.checkArgument(arg.getType() instanceof ParameterizedType, "Type spec must be List<OperatorNode<?>>");
                    Clreplaced<? extends Operator> optype = (Clreplaced<? extends Operator>) TypeLiteral.get(((ParameterizedType) arg.getType()).getActualTypeArguments()[0]).getRawType();
                    return new OperatorNodeListTypeChecker(parent, idx, optype, ImmutableSet.<Operator>of());
                } else {
                    return new JavaListTypeChecker(parent, idx, arg.getRawType());
                }
            }
            throw new IllegalArgumentException("don't know how to handle TypeLiteral " + value);
        }
        if (value instanceof Clreplaced) {
            Clreplaced<?> clazz = (Clreplaced<?>) value;
            if (Operator.clreplaced.isreplacedignableFrom(clazz)) {
                return new NodeTypeChecker(parent, idx, (Clreplaced<? extends Operator>) clazz, ImmutableSet.<Operator>of());
            } else {
                return new JavaTypeChecker(parent, idx, clazz);
            }
        } else if (value instanceof Operator) {
            Operator operator = (Operator) value;
            Clreplaced<? extends Operator> clazz = operator.getClreplaced();
            Set<? extends Operator> allowed;
            if (Enum.clreplaced.isInstance(value)) {
                Clreplaced<? extends Enum> enumClazz = (Clreplaced<? extends Enum>) clazz;
                allowed = (Set<? extends Operator>) EnumSet.of(enumClazz.cast(value));
            } else {
                allowed = ImmutableSet.of(operator);
            }
            return new NodeTypeChecker(parent, idx, clazz, allowed);
        } else if (value instanceof EnumSet) {
            EnumSet<?> v = (EnumSet<?>) value;
            Enum elt = Iterables.get(v, 0);
            if (elt instanceof Operator) {
                Clreplaced<? extends Operator> opclreplaced = (Clreplaced<? extends Operator>) elt.getClreplaced();
                Set<? extends Operator> allowed = (Set<? extends Operator>) v;
                return new NodeTypeChecker(parent, idx, opclreplaced, allowed);
            }
        } else if (value instanceof Set) {
            // Set<Clreplaced<?>>
            return new JavaUnionTypeChecker(parent, idx, (Set<Clreplaced<?>>) value);
        }
        throw new IllegalArgumentException("I don't know how to create a checker from " + value);
    }
}

18 Source : ReflectiveJavaTypeWidget.java
with Apache License 2.0
from yahoo

public clreplaced ReflectiveJavaTypeWidget extends BaseTypeWidget {

    private final ProgramValueTypeAdapter adapter;

    private final Type type;

    private final TypeLiteral<?> typeLiteral;

    private final Clreplaced<?> clazz;

    private final MethodDispatcher dispatcher;

    private PropertyAdapter propertyAdapter;

    public ReflectiveJavaTypeWidget(ProgramValueTypeAdapter adapter, Clreplaced<?> clazz) {
        this(adapter, TypeLiteral.get(clazz));
    }

    public ReflectiveJavaTypeWidget(ProgramValueTypeAdapter adapter, TypeLiteral<?> typeLiteral) {
        super(Type.getType(typeLiteral.getRawType()));
        this.clazz = typeLiteral.getRawType();
        Preconditions.checkArgument(!clazz.isPrimitive(), "ReflectiveTypeWidget used on primitive: %s", clazz.getName());
        Preconditions.checkArgument(!clazz.isArray(), "ReflectiveTypeWidget used on array: %s", clazz.getName());
        Preconditions.checkArgument(TypeUtilities.getPrimitiveType(clazz) == null, "ReflectiveTypeWidget used on boxed primitive: %s", clazz.getName());
        this.adapter = adapter;
        this.type = Type.getType(typeLiteral.getRawType());
        this.typeLiteral = typeLiteral;
        this.dispatcher = new MethodDispatcher(typeLiteral);
    }

    @Override
    public YQLCoreType getValueCoreType() {
        if (isIterable()) {
            return YQLCoreType.ARRAY;
        } else if (hasProperties()) {
            return YQLCoreType.STRUCT;
        } else {
            return YQLCoreType.OBJECT;
        }
    }

    @Override
    public boolean isPrimitive() {
        return clazz.isPrimitive();
    }

    @Override
    public boolean isNullable() {
        return !clazz.isPrimitive();
    }

    @Override
    public Type getJVMType() {
        return type;
    }

    @Override
    public boolean isIterable() {
        return Iterable.clreplaced.isreplacedignableFrom(clazz);
    }

    @Override
    public IterateAdapter gereplacederableAdapter() {
        if (isIterable()) {
            try {
                TypeLiteral<?> iteratorType = typeLiteral.getReturnType(clazz.getMethod("iterator"));
                return new JavaIterableAdapter(adapter.adaptInternal(JVMTypes.getTypeArgument(iteratorType.getType(), 0)));
            } catch (NoSuchMethodException e) {
                throw new UnsupportedOperationException();
            }
        } else {
            throw new UnsupportedOperationException();
        }
    }

    @Override
    public boolean isIndexable() {
        return hasProperties();
    }

    @Override
    public IndexAdapter getIndexAdapter() {
        if (hasProperties()) {
            return new StructIndexAdapter(this, getPropertyAdapter());
        }
        throw new UnsupportedOperationException();
    }

    @Override
    public BytecodeExpression invoke(final BytecodeExpression target, String methodName, final List<BytecodeExpression> arguments) {
        final Type[] argTypes = new Type[arguments.size()];
        for (int i = 0; i < arguments.size(); ++i) {
            argTypes[i] = arguments.get(i).getType().getJVMType();
        }
        // how to determine the return type?
        // loop f
        TypeLiteral<?> result = dispatcher.lookup(methodName, argTypes);
        if (result == null) {
            throw new ProgramCompileException("Unknown method %s.%s", clazz.getName(), methodName);
        }
        TypeWidget resultType = adapter.adaptInternal(result);
        // semi-gross that we always use invokedynamic here, fix later
        List<BytecodeExpression> fullArgs = Lists.newArrayListWithCapacity(arguments.size() + 1);
        fullArgs.add(target);
        fullArgs.addAll(arguments);
        return new InvokeDynamicExpression(Dynamic.H_BOOTSTRAP, "dyn:callMethod:" + methodName, resultType, fullArgs);
    }

    @Override
    public BytecodeExpression invoke(BytecodeExpression target, TypeWidget outputType, String methodName, List<BytecodeExpression> arguments) {
        final Type[] argTypes = new Type[arguments.size()];
        for (int i = 0; i < arguments.size(); ++i) {
            argTypes[i] = arguments.get(i).getType().getJVMType();
        }
        // semi-gross that we always use invokedynamic here, fix later
        List<BytecodeExpression> fullArgs = Lists.newArrayListWithCapacity(arguments.size() + 1);
        fullArgs.add(target);
        fullArgs.addAll(arguments);
        return new InvokeDynamicExpression(Dynamic.H_BOOTSTRAP, "dyn:callMethod:" + methodName, outputType, fullArgs);
    }

    @Override
    public boolean hasProperties() {
        if (Iterable.clreplaced.isreplacedignableFrom(clazz)) {
            return false;
        }
        PropertyAdapter properties = resolveProperties();
        if (properties == null) {
            return false;
        }
        if (properties.isClosed() && Iterables.isEmpty(properties.getProperties())) {
            return false;
        }
        return true;
    }

    @Override
    public PropertyAdapter getPropertyAdapter() {
        return resolveProperties();
    }

    private PropertyAdapter resolveProperties() {
        if (propertyAdapter == null) {
            propertyAdapter = ReflectivePropertyAdapter.create(this, adapter, typeLiteral);
        }
        return propertyAdapter;
    }

    @Override
    protected SerializationAdapter getJsonSerializationAdapter() {
        if (hasProperties()) {
            return new NativeObjectSerializer(getPropertyAdapter(), NativeEncoding.JSON);
        } else if (isIterable()) {
            return new IteratingSerializing(gereplacederableAdapter(), NativeEncoding.JSON);
        } else {
            return new EmptyObjectSerializer(this, NativeEncoding.JSON);
        }
    }
}

18 Source : MethodDispatcher.java
with Apache License 2.0
from yahoo

public clreplaced MethodDispatcher {

    private final TypeLiteral<?> target;

    private Map<String, TypeLiteral<?>> matches = Maps.newHashMap();

    public MethodDispatcher(TypeLiteral<?> target) {
        this.target = target;
    }

    private String toKey(String methodName, List<TypeWidget> argumentTypes) {
        StringBuilder out = new StringBuilder();
        out.append(methodName).append('(');
        Joiner.on(",").appendTo(out, Iterables.transform(argumentTypes, new Function<TypeWidget, String>() {

            @Override
            public String apply(TypeWidget input) {
                return input.getJVMType().getDescriptor();
            }
        }));
        out.append(')');
        return out.toString();
    }

    private String toKey(String methodName, Iterable<Type> argumentTypes) {
        StringBuilder out = new StringBuilder();
        out.append(methodName).append('(');
        Joiner.on(",").appendTo(out, Iterables.transform(argumentTypes, new Function<Type, String>() {

            @Override
            public String apply(Type input) {
                return input.getDescriptor();
            }
        }));
        out.append(')');
        return out.toString();
    }

    static clreplaced MethodMatch implements Comparable<MethodMatch> {

        TypeLiteral<?> returnType;

        Method method;

        int score;

        MethodMatch(TypeLiteral<?> returnType, Method method, int score) {
            this.returnType = returnType;
            this.method = method;
            this.score = score;
        }

        @Override
        public int compareTo(MethodMatch o) {
            return Integer.compare(this.score, o.score);
        }
    }

    // for now, we only worry about argument count, leaving coercion of type to runtime
    public TypeLiteral<?> lookup(String methodName, Type[] argumentTypes) {
        String key = toKey(methodName, Arrays.asList(argumentTypes));
        if (matches.containsKey(key)) {
            return matches.get(key);
        }
        List<MethodMatch> candidate = Lists.newArrayList();
        Clreplaced<?> clazz = target.getRawType();
        for (Method method : clazz.getMethods()) {
            if (!Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())) {
                if (methodName.equals(method.getName())) {
                    int count = target.getParameterTypes(method).size();
                    if (count == argumentTypes.length) {
                        candidate.add(new MethodMatch(target.getReturnType(method), method, 0));
                    } else if (method.isVarArgs() && count >= (argumentTypes.length - 1)) {
                        candidate.add(new MethodMatch(target.getReturnType(method), method, 1));
                    }
                }
            }
        }
        Collections.sort(candidate);
        if (candidate.size() == 0) {
            return null;
        } else {
            TypeLiteral<?> returnType = candidate.get(0).returnType;
            matches.put(key, returnType);
            return returnType;
        }
    }
}

18 Source : InnerFactoryManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Generate and install an {@link InnerFactory}
 * @param <O>    Outer type
 * @param <I>    Inner type
 */
public clreplaced InnerFactoryManifest<O, I> extends KeyedManifest {

    private final TypeLiteral<I> innerType;

    private final TypeLiteral<O> outerType;

    private final Key<InnerFactory<O, I>> factoryKey;

    public static <I> InnerFactoryManifest<?, I> forInnerClreplaced(Clreplaced<I> type) {
        return forInnerClreplaced(Key.get(type));
    }

    public static <I> InnerFactoryManifest<?, I> forInnerClreplaced(TypeLiteral<I> type) {
        return forInnerClreplaced(Key.get(type));
    }

    public static <I> InnerFactoryManifest<?, I> forInnerClreplaced(Key<I> key) {
        final Clreplaced<?> outer = key.getTypeLiteral().getRawType().getEnclosingClreplaced();
        if (outer == null) {
            throw new IllegalArgumentException(key + " is not an inner clreplaced");
        }
        return new InnerFactoryManifest(key, TypeLiteral.get(outer));
    }

    protected InnerFactoryManifest() {
        this(null, null);
    }

    public InnerFactoryManifest(Key<I> innerKey, TypeLiteral<O> outerType) {
        if (innerKey == null) {
            innerKey = Key.get(new ResolvableType<I>() {
            }.in(getClreplaced()));
        }
        this.innerType = innerKey.getTypeLiteral();
        this.outerType = outerType != null ? outerType : new ResolvableType<O>() {
        }.in(getClreplaced());
        this.factoryKey = innerKey.ofType(new ResolvableType<InnerFactory<O, I>>() {
        }.with(new TypeArgument<O>(this.outerType) {
        }, new TypeArgument<I>(this.innerType) {
        }));
    }

    @Override
    protected Object manifestKey() {
        return factoryKey;
    }

    @Override
    protected void configure() {
        final InjectionPoint point = InjectionPoint.forConstructorOf(innerType);
        final Constructor<I> constructor = (Constructor<I>) point.getMember();
        constructor.setAccessible(true);
        if (point.getDependencies().isEmpty() || !Types.isreplacedignable(point.getDependencies().get(0).getKey().getTypeLiteral(), outerType)) {
            addError("Expected %s to take %s as the first parameter of its injectable constructor", innerType, outerType);
            return;
        }
        final Set<Dependency<?>> dependencies = point.getDependencies().stream().skip(1).collect(Collectors.toImmutableSet());
        final List<Provider<?>> providers = dependencies.stream().map(dep -> getProvider(dep.getKey())).collect(Collectors.toImmutableList());
        final MembersInjector<I> membersInjector = getMembersInjector(innerType);
        clreplaced FactoryImpl implements InnerFactory<O, I>, HasDependencies {

            @Override
            public Set<Dependency<?>> getDependencies() {
                return dependencies;
            }

            public I create(O outer) {
                final Object[] args = new Object[providers.size() + 1];
                args[0] = outer;
                for (int i = 0; i < providers.size(); i++) {
                    args[i + 1] = providers.get(i).get();
                }
                return Injection.wrappingExceptions(() -> {
                    final I instance = constructor.newInstance(args);
                    membersInjector.injectMembers(instance);
                    return instance;
                });
            }
        }
        bind(factoryKey).toInstance(new FactoryImpl());
    }
}

18 Source : InjectionRequest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Hacky replacement for broken {@link com.google.inject.Binder#requestInjection(TypeLiteral, Object)}
 */
public clreplaced InjectionRequest<T> extends Manifest {

    private final T instance;

    private final TypeLiteral<T> type;

    public InjectionRequest(T instance, TypeLiteral<T> type) {
        this.instance = instance;
        this.type = type;
    }

    protected InjectionRequest(T instance) {
        this.instance = instance;
        this.type = new ResolvableType<T>() {
        }.in(getClreplaced());
    }

    @Override
    public int hashCode() {
        return System.idenreplacedyHashCode(instance);
    }

    @Override
    public boolean equals(Object that) {
        return this == that || (that instanceof InjectionRequest && this.instance == ((InjectionRequest) that).instance);
    }

    @Override
    protected void configure() {
        requestInjection(this);
        injector = getMembersInjector(type);
    }

    private MembersInjector<T> injector;

    @Inject
    private void inject() {
        injector.injectMembers(instance);
    }
}

18 Source : InjectableMethod.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public static <D> List<InjectableMethod<?>> forInheritedMethods(@Nullable TypeLiteral<D> targetType, @Nullable D target, Predicate<? super Method> filter) {
    final TypeLiteral<D> finalTargetType = targetType(targetType, target, null);
    return new MethodScanner<>(finalTargetType, filter).methods().stream().map(method -> (InjectableMethod<?>) forMethod(finalTargetType, target, method)).collect(Collectors.toImmutableList());
}

18 Source : InjectableMethod.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public static <D> List<InjectableMethod<?>> forDeclaredMethods(@Nullable TypeLiteral<D> targetType, @Nullable D target, Predicate<? super Method> filter) {
    final TypeLiteral<D> finalTargetType = targetType(targetType, target, null);
    return Stream.of(targetType.getRawType().getDeclaredMethods()).filter(filter).map(method -> (InjectableMethod<?>) forMethod(finalTargetType, target, method)).collect(Collectors.toImmutableList());
}

18 Source : PropertyManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public clreplaced PropertyManifest<T, B extends PropertyBuilder<T, B>> extends KeyedManifest {

    private final TypeLiteral<T> type;

    private final TypeArgument<T> typeArg;

    private final TypeLiteral<B> builderType;

    private final TypeArgument<B> builderTypeArg;

    private final boolean defaultForType;

    public PropertyManifest(Clreplaced<T> type) {
        this(TypeLiteral.get(type));
    }

    public PropertyManifest(Clreplaced<T> type, Clreplaced<B> builderType) {
        this(type, builderType, true);
    }

    public PropertyManifest(Clreplaced<T> type, Clreplaced<B> builderType, boolean defaultForType) {
        this(TypeLiteral.get(type), TypeLiteral.get(builderType), defaultForType);
    }

    public PropertyManifest(TypeLiteral<T> type) {
        this(type, (TypeLiteral<B>) new ResolvableType<PropertyBuilder<T, ?>>() {
        }.where(new TypeParameter<T>() {
        }, type));
    }

    public PropertyManifest(TypeLiteral<T> type, TypeLiteral<B> builderType) {
        this(type, builderType, true);
    }

    public PropertyManifest(TypeLiteral<T> type, TypeLiteral<B> builderType, boolean defaultForType) {
        this.type = Types.replacedertFullySpecified(checkNotNull(type));
        this.builderType = Types.replacedertFullySpecified(checkNotNull(builderType));
        this.typeArg = new TypeArgument<T>(this.type) {
        };
        this.builderTypeArg = new TypeArgument<B>(this.builderType) {
        };
        this.defaultForType = defaultForType;
    }

    @Override
    protected Object manifestKey() {
        return type;
    }

    @Override
    protected void configure() {
        final TypeLiteral<PropertyBuilderFactory<T, B>> factoryType = new ResolvableType<PropertyBuilderFactory<T, B>>() {
        }.with(typeArg, builderTypeArg);
        install(new FactoryModuleBuilder().build(factoryType));
        if (defaultForType) {
            final TypeLiteral<PropertyBuilderFactory<T, ?>> baseFactoryType = new ResolvableType<PropertyBuilderFactory<T, ?>>() {
            }.with(typeArg);
            bind(baseFactoryType).to(factoryType);
        }
    }
}

18 Source : PropertyManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

@Override
protected void configure() {
    final TypeLiteral<PropertyBuilderFactory<T, B>> factoryType = new ResolvableType<PropertyBuilderFactory<T, B>>() {
    }.with(typeArg, builderTypeArg);
    install(new FactoryModuleBuilder().build(factoryType));
    if (defaultForType) {
        final TypeLiteral<PropertyBuilderFactory<T, ?>> baseFactoryType = new ResolvableType<PropertyBuilderFactory<T, ?>>() {
        }.with(typeArg);
        bind(baseFactoryType).to(factoryType);
    }
}

18 Source : RangeParserManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public clreplaced RangeParserManifest<T extends Comparable<T>> extends KeyedManifest implements ParserBinders {

    private final TypeLiteral<T> type;

    private TypeArgument<T> typeArg;

    protected RangeParserManifest() {
        this(null);
    }

    public RangeParserManifest(@Nullable TypeLiteral<T> type) {
        this.type = type != null ? type : new ResolvableType<T>() {
        }.in(getClreplaced());
        this.typeArg = new TypeArgument<T>(this.type) {
        };
    }

    @Override
    protected Object manifestKey() {
        return type;
    }

    @Override
    protected void configure() {
        final TypeLiteral<Range<T>> rangeType = Ranges.typeOf(type);
        final TypeLiteral<RangeParser<T>> rangeParserType = new ResolvableType<RangeParser<T>>() {
        }.with(typeArg);
        final TypeLiteral<RangeProperty<T>> rangePropertyType = new ResolvableType<RangeProperty<T>>() {
        }.with(typeArg);
        // NodeParser<Range<T>> -> RangeParser<T>
        bindPrimitiveParser(rangeType).to(rangeParserType);
        // RangeParser<T>
        bind(rangeParserType);
        install(new PropertyManifest<>(rangeType, rangePropertyType));
    }
}

18 Source : ProvisionWrapper.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Contains the result of provisioning a module, and the module instance
 * itself, if it was provided.
 *
 * This exists in order to distinguish between absent modules and modules
 * that failed due to a user error. Knowing the difference allows us to
 * avoid chain reactions that can spew tons of superfluous errors.
 *
 * @see UpstreamProvisionFailure
 */
public clreplaced ProvisionWrapper<T> {

    static <T> Key<ProvisionWrapper<T>> keyOf(TypeLiteral<T> type) {
        return Key.get(new ResolvableType<ProvisionWrapper<T>>() {
        }.where(new TypeParameter<T>() {
        }, type));
    }

    final TypeLiteral<T> type;

    final ProvisionResult result;

    @Nullable
    final T instance;

    public ProvisionWrapper(TypeLiteral<T> type, ProvisionResult result) {
        this(type, result, null);
    }

    public ProvisionWrapper(TypeLiteral<T> type, ProvisionResult result, @Nullable T instance) {
        this.type = type;
        this.result = result;
        this.instance = instance;
    }

    public T require(@Nullable TypeLiteral<?> dependee) {
        switch(result) {
            case PRESENT:
                return instance;
            case FAILED:
                throw new UpstreamProvisionFailure();
        }
        // Don't throw a ProvisionException because it doesn't give you a stack trace
        if (dependee == null) {
            throw new IllegalStateException("Missing required module " + type);
        } else {
            throw new IllegalStateException("Missing module " + type + " which is required by " + dependee);
        }
    }

    public Optional<T> optional() {
        switch(result) {
            case PRESENT:
                return Optional.of(instance);
            case FAILED:
                throw new UpstreamProvisionFailure();
        }
        return Optional.empty();
    }
}

18 Source : ModuleManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Common manifest for map/match modules.
 *
 * Binds {@link Module} and {@link Optional< Module >} to a provider that ultimately calls
 * {@link #provisionModuleWithoutDependencies()} to provision the module instance.
 * The optional binding is whatever that method returns, and the direct binding
 * throws an exception if the optional is not present. The scoping for these
 * bindings is determined from the {@link Scope} parameter.
 *
 * Before trying to provision the module itself, any explicit dependencies
 * in a {@link ModuleDescription} are provisioned. If any necessary dependencies
 * do not load then no attempt is made to provision this module.
 *
 * @param <Base> Base type for all modules in the scope
 * @param <Scope> Scope annotation type
 * @param <Context> Context type
 * @param <Module> Type of this module
 */
public abstract clreplaced ModuleManifest<Base, Scope extends Annotation, Context extends ModuleContext<Base, Scope>, Module extends Base> extends HybridManifest implements MatchBinders {

    protected final TypeLiteral<Module> type;

    protected final Clreplaced<Module> rawType;

    protected final Clreplaced<Scope> scope;

    protected final String simpleName;

    protected final Key<Module> key;

    protected final Key<Optional<Module>> optionalKey;

    protected final Key<ProvisionWrapper<Module>> wrapperKey;

    protected final Key<Context> contextKey;

    protected final Key<ProvisionWrapper<? extends Base>> setElementKey;

    public ModuleManifest(@Nullable TypeLiteral<Module> type) {
        // Figure out the module type. If the given type is null,
        // then try to resolve it from this object's superclreplaced.
        this.type = type != null ? Types.replacedertFullySpecified(type) : new ResolvableType<Module>() {
        }.in(getClreplaced());
        this.rawType = (Clreplaced<Module>) this.type.getRawType();
        this.simpleName = rawType.getSimpleName();
        // Resolve the scope type automatically
        this.scope = (Clreplaced<Scope>) new ResolvableType<Scope>() {
        }.in(getClreplaced()).getRawType();
        // Construct various keys related to the module/scope
        this.key = Key.get(this.type);
        this.optionalKey = Keys.optional(this.key);
        this.wrapperKey = ProvisionWrapper.keyOf(this.type);
        this.contextKey = Key.get(new ResolvableType<Context>() {
        }.in(getClreplaced()));
        this.setElementKey = Key.get(new ResolvableType<ProvisionWrapper<? extends Base>>() {
        }.in(getClreplaced()));
    }

    @Override
    protected void configure() {
        // Inject this object. A few subclreplacedes rely on this.
        requestInjection(this);
        // Register the module in the big list of all modules
        inSet(setElementKey).addBinding().to(wrapperKey);
        // Bind the wrapper to the provider that does everything
        bind(wrapperKey).toProvider(new WrapperProvider()).in(scope);
        // Link M and Optional<M> to the wrapper
        final Provider<ProvisionWrapper<Module>> wrapperProvider = getProvider(wrapperKey);
        bind(optionalKey).toProvider(() -> wrapperProvider.get().optional()).in(scope);
        bind(key).toProvider(() -> wrapperProvider.get().require(null)).in(scope);
    }

    /**
     * Provisions any the explicit dependencies of the module (from a {@link ModuleDescription} annotation),
     * followed by the module itself.
     *
     * Also implements {@link com.google.inject.spi.HasDependencies}, though I have no idea
     * if that does anything useful.
     *
     * TODO: Replace all explicit dependencies with plain old injections so we don't need
     * all this complex reflection and logic.
     *
     * @see ModuleDescription
     * @see ProvisionWrapper
     */
    private clreplaced WrapperProvider implements ProviderWithDependencies<ProvisionWrapper<Module>> {

        final Provider<Context> contextProvider = getProvider(contextKey);

        final Set<Dependency<?>> dependencies = new HashSet<>();

        final List<Provider<? extends ProvisionWrapper<?>>> requires = new ArrayList<>();

        final List<Provider<? extends ProvisionWrapper<?>>> depends = new ArrayList<>();

        final List<Provider<? extends ProvisionWrapper<?>>> follows = new ArrayList<>();

        WrapperProvider() {
            final ModuleDescription annotation = type.getRawType().getAnnotation(ModuleDescription.clreplaced);
            if (annotation != null) {
                for (Clreplaced<?> cls : annotation.requires()) {
                    addDependency(requires, cls);
                }
                for (Clreplaced<?> cls : annotation.depends()) {
                    addDependency(depends, cls);
                }
                for (Clreplaced<?> cls : annotation.follows()) {
                    addDependency(follows, cls);
                }
            }
        }

        <T> void addDependency(List<Provider<? extends ProvisionWrapper<?>>> list, Clreplaced<T> module) {
            final Key<ProvisionWrapper<T>> key = ProvisionWrapper.keyOf(TypeLiteral.get(module));
            final Provider<ProvisionWrapper<T>> provider = getProvider(key);
            dependencies.add(Dependency.get(key));
            list.add(provider);
        }

        @Override
        public Set<Dependency<?>> getDependencies() {
            return dependencies;
        }

        @Override
        public ProvisionWrapper<Module> get() {
            // Note that all dependencies are provisioned, in the same order,
            // regardless of any intermediate result. This keeps the loading
            // process predictable, even when there are errors.
            boolean failed = false;
            boolean absent = false;
            // Required modules - These are expected to be present
            for (Provider<? extends ProvisionWrapper<?>> provider : requires) {
                final ProvisionWrapper<?> wrapper = provider.get();
                switch(wrapper.result) {
                    case FAILED:
                        failed = true;
                        break;
                    default:
                        wrapper.require(type);
                        break;
                }
            }
            // Chained module - If any of these are absent, so are we
            for (Provider<? extends ProvisionWrapper<?>> provider : depends) {
                final ProvisionWrapper<?> wrapper = provider.get();
                switch(wrapper.result) {
                    case FAILED:
                        failed = true;
                        break;
                    case ABSENT:
                        absent = true;
                        break;
                }
            }
            // Prior module - Provision these first, but we don't care if they are absent
            for (Provider<? extends ProvisionWrapper<?>> provider : follows) {
                final ProvisionWrapper<?> wrapper = provider.get();
                switch(wrapper.result) {
                    case FAILED:
                        failed = true;
                        break;
                }
            }
            if (absent) {
                // Decline to load because an upstream module also declined
                return new ProvisionWrapper<>(type, ProvisionResult.ABSENT);
            } else if (failed) {
                // Fail because an upstream module failed
                return new ProvisionWrapper<>(type, ProvisionResult.FAILED);
            } else {
                try {
                    // Load this module and add it to the context (if present)
                    return contextProvider.get().loadModule(ModuleManifest.this::provisionModuleWithoutDependencies).map(module -> new ProvisionWrapper<>(type, ProvisionResult.PRESENT, module)).orElseGet(() -> new ProvisionWrapper<>(type, ProvisionResult.ABSENT));
                } catch (UpstreamProvisionFailure e) {
                    // Upstream module failed, we don't have to report this one failing too
                    return new ProvisionWrapper<>(type, ProvisionResult.FAILED);
                }
            }
        }
    }

    /**
     * Provision the module, replaceduming explicit dependencies have already been provisioned
     *
     * @return The module instance, or empty if the module declines to load
     *
     * @throws ModuleLoadException If a *user* error occurred while loading the module i.e.
     *                             something that should be reported to the mapmaker.
     *                             The error is reported to the {@link ModuleContext} and
     *                             loading continues, skipping any modules dependent on this one.
     */
    protected abstract Optional<Module> provisionModuleWithoutDependencies() throws ModuleLoadException;
}

18 Source : MatchFacetContextManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

@Override
protected void configure() {
    final TypeLiteral<FacetContext<F>> fc = new ResolvableType<FacetContext<F>>() {
    }.with(facetType);
    final TypeLiteral<BukkitFacetContext<F>> bfc = new ResolvableType<BukkitFacetContext<F>>() {
    }.with(facetType);
    final TypeLiteral<MatchFacetContext<F>> mfc = new ResolvableType<MatchFacetContext<F>>() {
    }.with(facetType);
    bind(mfc).to(contextType);
    bind(bfc).to(mfc);
    bind(fc).to(bfc);
}

18 Source : MatchModuleFeatureManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Configure a match module {@link M} that loads if and only if at least one instance of feature {@link F} is defined.
 *
 * A binding for List<F> must exist.
 */
public clreplaced MatchModuleFeatureManifest<M extends MatchModule, F extends FeatureDefinition> extends MatchModuleFixtureManifest<M> {

    private final TypeLiteral<F> featureType;

    protected MatchModuleFeatureManifest() {
        this(null, null);
    }

    public MatchModuleFeatureManifest(@Nullable TypeLiteral<M> moduleType, @Nullable TypeLiteral<F> featureType) {
        super(moduleType);
        this.featureType = featureType != null ? featureType : new ResolvableType<F>() {
        }.in(getClreplaced());
    }

    @Override
    protected void configure() {
        super.configure();
        featureListProvider = getProvider(Keys.listOf(Key.get(featureType)));
    }

    private Provider<List<F>> featureListProvider;

    @Override
    protected boolean shouldLoad() {
        return !featureListProvider.get().isEmpty();
    }
}

18 Source : RootFeatureManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Configures a {@link FeatureDefinition} that is parsed from the root
 * of the {@link Doreplacedent} using a {@link NodeFinder}, and binds the
 * results into List<T> in {@link MapScoped}.
 *
 * If no {@link NodeFinder} is specified, a typical structure is replacedumed,
 * based on the {@link FeatureInfo} annotation present on {@link T}.
 */
public clreplaced RootFeatureManifest<T extends FeatureDefinition> extends KeyedManifest implements MapBinders {

    private final TypeLiteral<T> featureType;

    private final TypeArgument<T> featureTypeArg;

    private final TypeLiteral<List<T>> featureListType;

    private final Clreplaced<T> rawType;

    private final NodeFinder nodeFinder;

    protected RootFeatureManifest() {
        this(null);
    }

    public RootFeatureManifest(@Nullable TypeLiteral<T> type) {
        this(type, null);
    }

    public RootFeatureManifest(@Nullable Clreplaced<T> type, @Nullable NodeFinder nodeFinder) {
        this(type == null ? null : TypeLiteral.get(type), nodeFinder);
    }

    public RootFeatureManifest(@Nullable TypeLiteral<T> type, @Nullable NodeFinder nodeFinder) {
        this.featureType = type != null ? type : new ResolvableType<T>() {
        }.in(getClreplaced());
        this.featureTypeArg = new TypeArgument<T>(this.featureType) {
        };
        this.featureListType = new ResolvableType<List<T>>() {
        }.with(featureTypeArg);
        this.rawType = (Clreplaced<T>) featureType.getRawType();
        if (nodeFinder == null) {
            final FeatureInfo info = Features.info(rawType);
            final Set<String> singular = info.singular().length > 0 ? ImmutableSet.copyOf(info.singular()) : ImmutableSet.of(info.name());
            final Set<String> plural = info.plural().length > 0 ? ImmutableSet.copyOf(info.plural()) : singular.stream().map(StringUtils::pluralize).collect(Collectors.toImmutableSet());
            final ElementFlattener flattener = new ElementFlattener(plural, singular, 1);
            nodeFinder = (parent, name) -> flattener.flattenChildren(parent).map(Node::of);
        }
        this.nodeFinder = nodeFinder;
    }

    @Override
    protected Object manifestKey() {
        return featureType;
    }

    @Override
    protected void configure() {
        provisionAtParseTime(featureListType).toProvider(new FeatureListProvider()).in(MapScoped.clreplaced);
    }

    private clreplaced FeatureListProvider implements Provider<List<T>> {

        @Inject
        Provider<Doreplacedent> doreplacedentProvider;

        @Inject
        Provider<ModuleExceptionHandler> exceptionHandlerProvider;

        final Provider<FeatureParser<T>> parserProvider = getProvider(Key.get(Types.parameterizedTypeLiteral(FeatureParser.clreplaced, featureType)));

        @Override
        public List<T> get() {
            final Doreplacedent doreplacedent = doreplacedentProvider.get();
            final ModuleExceptionHandler exceptionHandler = exceptionHandlerProvider.get();
            final Parser<T> parser = parserProvider.get();
            // Skip over features that throw and keep loading the rest.
            return nodeFinder.findNodes(doreplacedent.getRootElement(), "").flatMap(child -> Optionals.stream(exceptionHandler.ignoringFailures(() -> parser.parse(child)))).collect(Collectors.toImmutableList());
        }
    }
}

18 Source : ComposableManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public clreplaced ComposableManifest<T> extends KeyedManifest implements ParserBinders {

    private final TypeLiteral<T> type;

    private final TypeArgument<T> typeArg;

    protected ComposableManifest() {
        this(null);
    }

    public ComposableManifest(@Nullable TypeLiteral<T> type) {
        this.type = type != null ? type : new ResolvableType<T>() {
        }.in(getClreplaced());
        this.typeArg = new TypeArgument<T>(this.type) {
        };
    }

    @Override
    protected Object manifestKey() {
        return type;
    }

    @Override
    protected void configure() {
        bindElementParser(new ResolvableType<Composition<T>>() {
        }.with(typeArg)).to(new ResolvableType<CompositionParser<T>>() {
        }.with(typeArg));
    }
}

18 Source : V3JobManagerModule.java
with Apache License 2.0
from Netflix

public clreplaced V3JobManagerModule extends AbstractModule {

    private static final Logger logger = LoggerFactory.getLogger(V3JobManagerModule.clreplaced);

    private static final String STUCK_IN_STATE = "stuckInStateTokenBucketConfig";

    private static final TypeLiteral<DifferenceResolver<JobManagerReconcilerEvent>> JOB_DIFFERENCE_RESOLVER = new TypeLiteral<DifferenceResolver<JobManagerReconcilerEvent>>() {
    };

    @Override
    protected void configure() {
        bind(Key.get(JOB_DIFFERENCE_RESOLVER, Names.named(JobReconciliationFrameworkFactory.BATCH_RESOLVER))).to(BatchDifferenceResolver.clreplaced);
        bind(Key.get(JOB_DIFFERENCE_RESOLVER, Names.named(JobReconciliationFrameworkFactory.SERVICE_RESOLVER))).to(ServiceDifferenceResolver.clreplaced);
        bind(V3JobOperations.clreplaced).to(DefaultV3JobOperations.clreplaced);
        bind(ReadOnlyJobOperations.clreplaced).to(DefaultV3JobOperations.clreplaced);
        bind(JobSubmitLimiter.clreplaced).to(DefaultJobSubmitLimiter.clreplaced);
        bind(TaskInfoRequestFactory.clreplaced).to(DefaultV3TaskInfoRequestFactory.clreplaced);
        bind(KubeNotificationProcessorInitializer.clreplaced).asEagerSingleton();
        bind(JobAndTaskMetrics.clreplaced).asEagerSingleton();
        bind(ArchivedTasksGc.clreplaced).asEagerSingleton();
    }

    @Provides
    @Singleton
    public JobManagerConfiguration getJobManagerConfiguration(ConfigProxyFactory factory) {
        return factory.newProxy(JobManagerConfiguration.clreplaced);
    }

    @Provides
    @Singleton
    @Named(JobManagerConfiguration.STUCK_IN_STATE_TOKEN_BUCKET)
    public TokenBucket getStuckInStateRateLimiter(@Named(STUCK_IN_STATE) FixedIntervalTokenBucketConfiguration config, replacedusRuntime runtime) {
        return Limiters.createInstrumentedFixedIntervalTokenBucket(JobManagerConfiguration.STUCK_IN_STATE_TOKEN_BUCKET, config, currentTokenBucket -> logger.info("Detected {} token bucket configuration update: {}", JobManagerConfiguration.STUCK_IN_STATE_TOKEN_BUCKET, currentTokenBucket), runtime);
    }

    @Provides
    @Singleton
    @Named(STUCK_IN_STATE)
    public FixedIntervalTokenBucketConfiguration getStuckInStateTokenBucketConfiguration(ConfigProxyFactory factory) {
        return factory.newProxy(FixedIntervalTokenBucketConfiguration.clreplaced, "replacedusMaster.jobManager.stuckInStateTokenBucket");
    }

    @Singleton
    private static clreplaced KubeNotificationProcessorInitializer {

        @Inject
        public KubeNotificationProcessorInitializer(FeatureActivationConfiguration configuration, Injector injector) {
            if (configuration.isKubeSchedulerEnabled()) {
                logger.info("Kube-scheduler enabled: starting KubeNotificationProcessor...");
                injector.getInstance(KubeNotificationProcessor.clreplaced);
            } else {
                logger.info("Kube-scheduler disabled: not starting KubeNotificationProcessor");
            }
        }
    }

    @Provides
    @Singleton
    public ArchivedTasksGcConfiguration getArchivedTasksGcConfiguration(ConfigProxyFactory factory) {
        return factory.newProxy(ArchivedTasksGcConfiguration.clreplaced);
    }
}

18 Source : DynamicBindingProviderImpl.java
with Apache License 2.0
from cerner

/**
 * Internal implementation of {@link DynamicBindingProvider}.
 *
 * @author John Leacox
 * @since 1.2
 */
clreplaced DynamicBindingProviderImpl<T> implements DynamicBindingProvider<T> {

    private Injector injector;

    private TypeLiteral<T> type;

    DynamicBindingProviderImpl(TypeLiteral<T> type) {
        this.type = type;
    }

    @Inject
    void init(Injector injector) {
        this.injector = injector;
    }

    @Override
    public synchronized T get(Clreplaced<? extends Annotation> bindingAnnotation) {
        BindingAnnotations.checkIsBindingAnnotation(bindingAnnotation);
        Key<T> key = Key.get(type, bindingAnnotation);
        return injector.getInstance(key);
    }
}

18 Source : VoiceBridgeModule.java
with Apache License 2.0
from arcus-smart-home

@Modules(include = { KafkaModule.clreplaced, ClusterAwareServerModule.clreplaced, ShiroModule.clreplaced, PersonDAOSecurityModule.clreplaced, TemplateModule.clreplaced, HttpHealthCheckModule.clreplaced, PlacePopulationCacheModule.clreplaced })
public clreplaced VoiceBridgeModule extends AbstractIrisModule {

    private static final TypeLiteral<ChannelInitializer<SocketChannel>> CHANNEL_INITIALIZER_TYPE_LITERAL = new TypeLiteral<ChannelInitializer<SocketChannel>>() {
    };

    @Override
    protected void configure() {
        bind(BridgeServerConfig.clreplaced);
        bind(BridgeServerTlsContext.clreplaced).to(BridgeServerTlsContextImpl.clreplaced);
        bind(BridgeServerTrustManagerFactory.clreplaced).to(NullTrustManagerFactoryImpl.clreplaced);
        bind(ChannelInboundHandler.clreplaced).toProvider(BaseWebSocketServerHandlerProvider.clreplaced);
        bind(CHANNEL_INITIALIZER_TYPE_LITERAL).to(HttpRequestInitializer.clreplaced);
        bind(RequestMatcher.clreplaced).annotatedWith(Names.named("WebSocketUpgradeMatcher")).to(NeverMatcher.clreplaced);
        bind(IrisNettyAuthorizationContextLoader.clreplaced).to(IrisNettyNoopAuthorizationContextLoader.clreplaced);
        // No Session Listeners
        Multibinder<SessionListener> slBindings = Multibinder.newSetBinder(binder(), SessionListener.clreplaced);
        // Bind Http Handlers
        Multibinder<RequestHandler> rhBindings = Multibinder.newSetBinder(binder(), RequestHandler.clreplaced);
        rhBindings.addBinding().to(RootRedirect.clreplaced);
        rhBindings.addBinding().to(IndexPage.clreplaced);
        rhBindings.addBinding().to(CheckPage.clreplaced);
        rhBindings.addBinding().to(SessionLogin.clreplaced);
        rhBindings.addBinding().to(SessionLogout.clreplaced);
        rhBindings.addBinding().to(ListPlacesRESTHandler.clreplaced);
        rhBindings.addBinding().to(TokenHandler.clreplaced);
        rhBindings.addBinding().to(RevokeHandler.clreplaced);
        rhBindings.addBinding().to(AuthorizeHandler.clreplaced);
        // oauth
        bind(OAuthDAO.clreplaced).to(CreplacedandraOAuthDAO.clreplaced);
        bind(RequestAuthorizer.clreplaced).annotatedWith(Names.named("SessionAuthorizer")).to(SessionAuth.clreplaced);
        bind(SessionFactory.clreplaced).to(DefaultSessionFactoryImpl.clreplaced);
        bind(SessionRegistry.clreplaced).to(DefaultSessionRegistryImpl.clreplaced);
        bind(Responder.clreplaced).annotatedWith(Names.named("SessionLogin")).to(SessionLoginResponder.clreplaced);
        bind(Responder.clreplaced).annotatedWith(Names.named("SessionLogout")).to(SessionLogoutResponder.clreplaced);
        bind(Authenticator.clreplaced).to(ShiroAuthenticator.clreplaced);
        bind(PlaceSelectionHandler.clreplaced).to(VoicePlaceSelectionHandler.clreplaced);
    }
}

17 Source : ReflectiveJavaTypeWidget.java
with Apache License 2.0
from yahoo

@Override
public IterateAdapter gereplacederableAdapter() {
    if (isIterable()) {
        try {
            TypeLiteral<?> iteratorType = typeLiteral.getReturnType(clazz.getMethod("iterator"));
            return new JavaIterableAdapter(adapter.adaptInternal(JVMTypes.getTypeArgument(iteratorType.getType(), 0)));
        } catch (NoSuchMethodException e) {
            throw new UnsupportedOperationException();
        }
    } else {
        throw new UnsupportedOperationException();
    }
}

17 Source : ObservableProvider.java
with Apache License 2.0
from radixdlt

/**
 * Helper clreplaced to hook up observables to the environment
 */
public final clreplaced ObservableProvider<T> implements Provider<Observable<T>> {

    @Inject
    private Provider<RxEnvironment> rxEnvironmentProvider;

    private final Clreplaced<T> c;

    private final TypeLiteral<T> t;

    ObservableProvider(Clreplaced<T> c) {
        this.c = Objects.requireNonNull(c);
        this.t = null;
    }

    ObservableProvider(TypeLiteral<T> t) {
        this.t = Objects.requireNonNull(t);
        this.c = null;
    }

    @Override
    public Observable<T> get() {
        RxEnvironment e = rxEnvironmentProvider.get();
        if (c != null) {
            return e.getObservable(c);
        } else {
            return e.getObservable(t);
        }
    }
}

17 Source : MethodScanner.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Search a type hiearchy for methods matching a given filter.
 *
 * If matching methods override each other, only the most derived
 * method is included in the result.
 */
public clreplaced MethodScanner<D> {

    private clreplaced Signature {

        @Nullable
        final Object context;

        final String name;

        final List<Clreplaced<?>> parameters;

        final int hashCode;

        Signature(Method method) {
            name = method.getName();
            parameters = ListUtils.transformedCopyOf(decl.getParameterTypes(method), TypeLiteral::getRawType);
            if (Members.isPrivate(method)) {
                // Private methods are only visible within the same clreplaced (i.e. not overridable)
                context = method.getDeclaringClreplaced();
            } else if (Members.isProtected(method) || Members.isPublic(method)) {
                // Protected and public methods are visible throughout the entire hiearchy
                context = null;
            } else {
                // Package-local methods can only override within the same package
                context = method.getDeclaringClreplaced().getPackage();
            }
            hashCode = Objects.hash(context, name, parameters);
        }

        @Override
        public int hashCode() {
            return hashCode;
        }

        @Override
        public boolean equals(Object obj) {
            return Utils.equals(Signature.clreplaced, this, obj, that -> Objects.equals(this.context, that.context) && Objects.equals(this.name, that.name) && Objects.equals(this.parameters, that.parameters));
        }
    }

    private final TypeLiteral<D> decl;

    private final Map<Signature, Method> map = new HashMap<>();

    private final Predicate<? super Method> filter;

    public MethodScanner(Clreplaced<D> decl, Predicate<? super Method> filter) {
        this(TypeLiteral.get(decl), filter);
    }

    public MethodScanner(TypeLiteral<D> decl, Predicate<? super Method> filter) {
        this.decl = decl;
        this.filter = filter;
        visitClreplacedes(decl.getRawType());
        visitInterfaces(decl.getRawType());
    }

    public Collection<Method> methods() {
        return map.values();
    }

    private void visitType(Clreplaced<?> type) {
        if (!type.isInterface()) {
            visitClreplacedes(type);
        }
        visitInterfaces(type);
    }

    private void visitClreplacedes(@Nullable Clreplaced<?> type) {
        if (type != null) {
            visitMethods(type);
            visitClreplacedes(type.getSuperclreplaced());
        }
    }

    private void visitInterfaces(Clreplaced<?> type) {
        if (type.isInterface()) {
            visitMethods(type);
        }
        for (Clreplaced<?> iface : type.getInterfaces()) {
            visitInterfaces(iface);
        }
    }

    private void visitMethods(Clreplaced<?> type) {
        for (Method method : type.getDeclaredMethods()) {
            if (!method.isSynthetic() && !method.isBridge() && filter.test(method)) {
                map.merge(new Signature(method), method, (ma, mb) -> {
                    // Figure out which method overrides the other
                    final Clreplaced<?> ta = ma.getDeclaringClreplaced();
                    final Clreplaced<?> tb = mb.getDeclaringClreplaced();
                    // If one method is declared in a clreplaced and the other is declared
                    // in an interface, the clreplaced method always wins.
                    if (!ta.isInterface() && tb.isInterface())
                        return ma;
                    if (!tb.isInterface() && ta.isInterface())
                        return mb;
                    // If one method is a default (interface) method, and the other
                    // one isn't, keep the default one (the other method must be
                    // a normal interface method).
                    if (ma.isDefault() && !mb.isDefault())
                        return ma;
                    if (mb.isDefault() && !ma.isDefault())
                        return mb;
                    // If one method's owner is a subtype of the other method's owner,
                    // keep the subtype method.
                    if (tb.isreplacedignableFrom(ta))
                        return ma;
                    if (ta.isreplacedignableFrom(tb))
                        return mb;
                    // If all else fails, keep the method that was encountered first.
                    // I'm pretty sure this can only happen with two abstract methods
                    // in unrelated interfaces, in which case it probably doesn't
                    // matter which one is kept.
                    return ma;
                });
            }
        }
    }
}

17 Source : TypeMapBinder.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Binds the contents of an immutable {@link TypeMap} by wrapping a {@link MapBinder}.
 */
public clreplaced TypeMapBinder<K, V> {

    private final TypeLiteral<K> keyType;

    private final TypeLiteral<V> valueType;

    private final Key<TypeMap<K, V>> collectionKey;

    private final Key<Map<TypeToken<? extends K>, Set<V>>> backingCollectionKey;

    private final MapBinder<TypeToken<? extends K>, V> backingCollectionBinder;

    public TypeMapBinder(Binder binder, @Nullable TypeLiteral<K> keyType, @Nullable TypeLiteral<V> valueType) {
        this.keyType = keyType != null ? keyType : new ResolvableType<K>() {
        }.in(getClreplaced());
        this.valueType = valueType != null ? valueType : new ResolvableType<V>() {
        }.in(getClreplaced());
        final TypeArgument<K> keyTypeArg = new TypeArgument<K>(this.keyType) {
        };
        final TypeArgument<V> valueTypeArg = new TypeArgument<V>(this.valueType) {
        };
        this.collectionKey = Key.get(new ResolvableType<TypeMap<K, V>>() {
        }.with(keyTypeArg, valueTypeArg));
        this.backingCollectionKey = Key.get(new ResolvableType<Map<TypeToken<? extends K>, Set<V>>>() {
        }.with(keyTypeArg, valueTypeArg));
        this.backingCollectionBinder = MapBinder.newMapBinder(binder, new ResolvableType<TypeToken<? extends K>>() {
        }.with(keyTypeArg), this.valueType).permitDuplicates();
        binder.install(new KeyedManifest.Impl(collectionKey) {

            @Override
            public void configure() {
                final Provider<Map<TypeToken<? extends K>, Set<V>>> backingCollectionProvider = getProvider(backingCollectionKey);
                bind(collectionType()).toProvider(() -> ImmutableTypeMap.copyOf(backingCollectionProvider.get()));
            }
        });
    }

    protected TypeMapBinder(Binder binder) {
        this(binder, null, null);
    }

    public static <K1, V1> TypeMapBinder<K1, V1> ofType(Binder binder, TypeLiteral<K1> keyType, TypeLiteral<V1> valueType) {
        return new TypeMapBinder<>(binder, Types.replacedertFullySpecified(keyType), Types.replacedertFullySpecified(valueType));
    }

    public static <K1, V1> TypeMapBinder<K1, V1> inContext(Binder binder, Clreplaced<?> declaringClreplaced) {
        return new TypeMapBinder<>(binder, new ResolvableType<K1>() {
        }.in(declaringClreplaced), new ResolvableType<V1>() {
        }.in(declaringClreplaced));
    }

    public Key<TypeMap<K, V>> collectionKey() {
        return collectionKey;
    }

    public TypeLiteral<TypeMap<K, V>> collectionType() {
        return collectionKey().getTypeLiteral();
    }

    public LinkedBindingBuilder<V> addBinding(Clreplaced<? extends K> type) {
        return addBinding(TypeToken.of(type));
    }

    public LinkedBindingBuilder<V> addBinding(TypeLiteral<? extends K> type) {
        return addBinding(Types.toToken(type));
    }

    public LinkedBindingBuilder<V> addBinding(TypeToken<? extends K> type) {
        return backingCollectionBinder.addBinding(type);
    }
}

17 Source : SetBinder.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Handy wrapper around a {@link Multibinder}
 */
public clreplaced SetBinder<T> {

    private final Binder binder;

    private final TypeLiteral<T> elementType;

    private final TypeLiteral<Set<T>> collectionType;

    private final Multibinder<T> multibinder;

    protected SetBinder(Binder binder, @Nullable TypeLiteral<T> type) {
        this(binder, type == null ? null : Key.get(type));
    }

    protected SetBinder(Binder binder, @Nullable Key<T> key) {
        if (key == null) {
            key = Key.get(new ResolvableType<T>() {
            }.in(getClreplaced()));
        }
        this.binder = binder.skipSources(SetBinder.clreplaced);
        this.elementType = key.getTypeLiteral();
        this.collectionType = new ResolvableType<Set<T>>() {
        }.with(new TypeArgument<T>(this.elementType) {
        });
        this.multibinder = Multibinder.newSetBinder(binder, key);
    }

    /**
     * Resolve the element type using the clreplaced of this object. This will only work
     * with a subclreplaced of {@link SetBinder} that specifies {@link T}, hence this
     * constructor is protected.
     *
     * @throws IllegalArgumentException if the element type cannot be resolved
     */
    protected SetBinder(Binder binder) {
        this(binder, (Key) null);
    }

    /**
     * Create a new SetBinder with an explicit element type (which must be fully specified)
     *
     * @throws IllegalArgumentException if the element type is not fully specified
     */
    public static <E> SetBinder<E> ofType(Binder binder, TypeLiteral<E> elementType) {
        return new SetBinder<>(binder, Types.replacedertFullySpecified(elementType));
    }

    /**
     * Create a new SetBinder, resolving the element type {@link E} in the context of
     * the given clreplaced.
     *
     * @throws IllegalArgumentException if the element type cannot be resolved
     */
    public static <E> SetBinder<E> inContext(Binder binder, Clreplaced<?> declaringClreplaced) {
        return new SetBinder<>(binder, new ResolvableType<E>() {
        }.in(declaringClreplaced));
    }

    public TypeLiteral<T> elementType() {
        return elementType;
    }

    public TypeLiteral<Set<T>> collectionType() {
        return collectionType;
    }

    protected Binder binder() {
        return binder;
    }

    public LinkedBindingBuilder<T> addBinding() {
        return multibinder.addBinding();
    }
}

17 Source : FacetBinder.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public clreplaced FacetBinder<F extends Facet> {

    private final Binder binder;

    private final TypeLiteral<F> baseFacetType;

    private final Multibinder<F> facetBinder;

    protected FacetBinder(Binder binder) {
        this.binder = binder;
        this.baseFacetType = new ResolvableType<F>() {
        }.in(getClreplaced());
        this.facetBinder = Multibinder.newSetBinder(binder, baseFacetType);
    }

    /**
     * Register the given facet type
     */
    public void add(Clreplaced<? extends F> facetType) {
        facetBinder.addBinding().to(facetType);
    }

    /**
     * Register the given facet type, AND self-bind it in the given scope, defaulting to {@link InjectorScoped}
     */
    public void register(Clreplaced<? extends F> facetType, @Nullable Clreplaced<? extends Annotation> scope) {
        add(facetType);
        binder.bind(facetType).in(Optionals.first(Optional.ofNullable(scope), Injection.scopeAnnotation(facetType)).orElse(InjectorScoped.clreplaced));
    }

    /**
     * Register the given facet type, AND self-bind it as {@link InjectorScoped}
     */
    public void register(Clreplaced<? extends F> facetType) {
        register(facetType, null);
    }
}

17 Source : RangeParserManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

@Override
protected void configure() {
    final TypeLiteral<Range<T>> rangeType = Ranges.typeOf(type);
    final TypeLiteral<RangeParser<T>> rangeParserType = new ResolvableType<RangeParser<T>>() {
    }.with(typeArg);
    final TypeLiteral<RangeProperty<T>> rangePropertyType = new ResolvableType<RangeProperty<T>>() {
    }.with(typeArg);
    // NodeParser<Range<T>> -> RangeParser<T>
    bindPrimitiveParser(rangeType).to(rangeParserType);
    // RangeParser<T>
    bind(rangeParserType);
    install(new PropertyManifest<>(rangeType, rangePropertyType));
}

17 Source : ReflectiveFeatureManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Configures a reflectively parsed feature {@link T}, which must be an interface.
 *
 * @see tc.oc.pgm.xml.Parseable for details on reflective parsing
 */
public clreplaced ReflectiveFeatureManifest<T extends FeatureDefinition> extends KeyedManifest implements MapBinders {

    private final TypeLiteral<T> type;

    private final TypeArgument<T> typeArg;

    private final Key<FeatureDefinitionParser<T>> definitionParserKey;

    protected ReflectiveFeatureManifest() {
        this(null);
    }

    public ReflectiveFeatureManifest(@Nullable TypeLiteral<T> type) {
        this.type = type != null ? Types.replacedertFullySpecified(type) : new ResolvableType<T>() {
        }.in(getClreplaced());
        this.typeArg = new TypeArgument<T>(this.type) {
        };
        this.definitionParserKey = Key.get(new ResolvableType<FeatureDefinitionParser<T>>() {
        }.with(typeArg));
    }

    @Override
    protected Object manifestKey() {
        return type;
    }

    @Override
    protected void configure() {
        // Generate the reflective parser and bind it to ReflectiveParser<T>
        install(new ReflectiveParserManifest<>(type, FeatureDefinition.Impl.clreplaced));
        // Bind ReflectiveFeatureParser<T> as the definition parser for T
        bind(definitionParserKey).to(new ResolvableType<ReflectiveFeatureParser<T>>() {
        }.with(typeArg)).in(MapScoped.clreplaced);
    }
}

17 Source : ModelBinder.java
with GNU Affero General Public License v3.0
from OvercastNetwork

public clreplaced ModelBinder<M extends Model, P extends PartialModel> implements ModelTypeLiterals, TypeLiterals {

    private final TypeLiteral<M> M;

    private final TypeLiteral<P> P;

    private final Binders binder;

    private final Multibinder<ModelMeta> metas;

    private final OptionalBinder<QueryService<M>> queryServiceBinder;

    private final OptionalBinder<UpdateService<P>> updateServiceBinder;

    private final OptionalBinder<ModelService<M, P>> serviceBinder;

    private final OptionalBinder<ModelStore<M>> storeBinder;

    public static <M extends Model> ModelBinder<M, M> of(ProtectedBinder binder, Clreplaced<M> M) {
        return of(binder, M, M);
    }

    public static <M extends Model> ModelBinder<M, M> of(ProtectedBinder binder, TypeLiteral<M> M) {
        return of(binder, M, M);
    }

    public static <M extends Model, P extends PartialModel> ModelBinder<M, P> of(ProtectedBinder binder, Clreplaced<M> M, Clreplaced<P> P) {
        return of(binder, TypeLiteral.get(M), TypeLiteral.get(P));
    }

    public static <M extends Model, P extends PartialModel> ModelBinder<M, P> of(ProtectedBinder binder, TypeLiteral<M> M, TypeLiteral<P> P) {
        return new ModelBinder<>(binder, M, P);
    }

    private ModelBinder(ProtectedBinder protectedBinder, TypeLiteral<M> M, TypeLiteral<P> P) {
        this.binder = Binders.wrap(protectedBinder.publicBinder());
        this.M = M;
        this.P = P;
        this.metas = Multibinder.newSetBinder(binder, ModelMeta.clreplaced);
        this.serviceBinder = OptionalBinder.newOptionalBinder(binder, ModelService(M, P));
        this.queryServiceBinder = OptionalBinder.newOptionalBinder(binder, QueryService(M));
        this.updateServiceBinder = OptionalBinder.newOptionalBinder(binder, UpdateService(P));
        this.storeBinder = OptionalBinder.newOptionalBinder(binder, ModelStore(M));
        binder.install(new OneTime());
        binder.install(new PerModel());
    }

    public LinkedBindingBuilder<ModelStore<M>> bindStore() {
        binder.provisionEagerly(ModelStore(M));
        new SuspendableBinder(binder).addBinding().to(ModelStore(M));
        return storeBinder.setBinding();
    }

    public OptionalBinder<QueryService<M>> queryService() {
        return queryServiceBinder;
    }

    public OptionalBinder<UpdateService<P>> updateService() {
        return updateServiceBinder;
    }

    public LinkedBindingBuilder<ModelService<M, P>> bindDefaultService() {
        queryService().setDefault().to(ModelService(M, P));
        updateService().setDefault().to(ModelService(M, P));
        return serviceBinder.setDefault();
    }

    public LinkedBindingBuilder<ModelService<M, P>> bindService() {
        queryService().setBinding().to(ModelService(M, P));
        updateService().setBinding().to(ModelService(M, P));
        return serviceBinder.setBinding();
    }

    public TypeLiteral<NullModelService<M, P>> nullService() {
        return NullModelService(M, P);
    }

    public TypeLiteral<NullQueryService<M>> nullQueryService() {
        return NullQueryService(M);
    }

    public TypeLiteral<HttpModelService<M, P>> httpService() {
        return HttpModelService(M, P);
    }

    public TypeLiteral<HttpQueryService<M>> httpQueryService() {
        return HttpQueryService(M);
    }

    public TypeLiteral<QueueQueryService<M>> queueQueryService() {
        return QueueQueryService(M);
    }

    private clreplaced PerModel extends KeyedManifest {

        @Override
        protected Object manifestKey() {
            return M;
        }

        @Override
        protected void configure() {
            final TypeLiteral<ModelMeta<M, P>> meta = ModelMeta(M, P);
            metas.addBinding().to(meta);
            bind(meta).in(Singleton.clreplaced);
            bind(new ResolvableType<ModelMeta<M, ?>>() {
            }.with(new TypeArgument<M>(M) {
            })).to(meta);
            bind(new ResolvableType<ModelMeta<?, P>>() {
            }.with(new TypeArgument<P>(P) {
            })).to(meta);
        }
    }

    private clreplaced OneTime extends SingletonManifest {

        @Provides
        @Singleton
        Map<String, ModelMeta> byName(Set<ModelMeta> metas) {
            return metas.stream().collect(Collectors.indexingBy(ModelMeta::name));
        }

        @Provides
        @Singleton
        TypeMap<Model, ModelMeta> byType(Set<ModelMeta> metas) {
            final ImmutableTypeMap.Builder<Model, ModelMeta> builder = ImmutableTypeMap.builder();
            metas.forEach(meta -> builder.put(meta.completeType(), meta));
            return builder.build();
        }

        @Provides
        @Singleton
        TypeMap<PartialModel, ModelMeta> byPartialType(Set<ModelMeta> metas) {
            final ImmutableTypeMap.Builder<PartialModel, ModelMeta> builder = ImmutableTypeMap.builder();
            metas.forEach(meta -> builder.put(meta.partialType(), meta));
            return builder.build();
        }
    }
}

17 Source : EntityTrackerModule.java
with Apache License 2.0
from openequella

@SuppressWarnings("nls")
@Override
protected void configure() {
    TypeLiteral<AbstractEnreplacedyService<?, BaseEnreplacedy>> enreplacedyService = new TypeLiteral<AbstractEnreplacedyService<?, BaseEnreplacedy>>() {
    };
    bindTracker(enreplacedyService.getType(), "enreplacedyService", "serviceClreplaced").orderByParameter("order");
}

17 Source : ScannerModule.java
with Apache License 2.0
from openequella

@SuppressWarnings("unchecked")
private <T> void bindOne(Clreplaced<T> actualClreplaced, Bind bind) {
    Clreplaced<T> clazz = (Clreplaced<T>) bind.value();
    if (clazz == Bind.clreplaced || (clazz == actualClreplaced && bind.types().length == 0)) {
        bind(actualClreplaced);
        return;
    }
    com.tle.core.guice.Type[] types = bind.types();
    if (types.length == 0) {
        bind(clazz).to(actualClreplaced);
    } else {
        Type[] actualTypes = new Type[types.length];
        int i = 0;
        for (com.tle.core.guice.Type type : types) {
            Type paramType = type.value();
            if (type.unknown()) {
                paramType = Types.subtypeOf(paramType);
            }
            actualTypes[i++] = paramType;
        }
        TypeLiteral<T> typeLiteral = (TypeLiteral<T>) TypeLiteral.get(Types.newParameterizedType(clazz, actualTypes));
        bind(typeLiteral).to(actualClreplaced);
    }
}

17 Source : ApiBungeeModule.java
with GNU Lesser General Public License v3.0
from AnvilPowered

@Override
protected void configure() {
    super.configure();
    TypeLiteral<CommonCallbackCommand<TextComponent, CommandSender>> callbackCommandType = new TypeLiteral<CommonCallbackCommand<TextComponent, CommandSender>>() {
    };
    bind(callbackCommandType).toProvider(BindingExtensions.asInternalProvider(callbackCommandType));
    bind(CommandExecuteService.clreplaced).to(BungeeCommandExecuteService.clreplaced);
    bind(new TypeLiteral<CommandService<BiConsumer<CommandSender, String[]>, CommandSender>>() {
    }).to(BungeeCommandService.clreplaced);
    bind(KickService.clreplaced).to(BungeeKickService.clreplaced);
    bind(LocationService.clreplaced).to(BungeeLocationService.clreplaced);
    bind(PermissionService.clreplaced).to(BungeePermissionService.clreplaced);
    bind(new TypeLiteral<TextService<TextComponent, CommandSender>>() {
    }).to(BungeeTextService.clreplaced);
    bind(new TypeLiteral<UserService<ProxiedPlayer, ProxiedPlayer>>() {
    }).to(BungeeUserService.clreplaced);
}

16 Source : MemberInjectingFactory.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * A generic factory that creates {@link T} instances in the same way as an Injector,
 * but does not require any binding for {@link T} itself.
 *
 * The injectable constructor is used to instantiate the clreplaced, but none of the
 * parameters are injected, they must all be preplaceded to {@link #newInstance(Object...)}.
 * However, fields and instance methods *are* injected, and dependencies for those
 * injection points are statically propagated to this clreplaced.
 */
public clreplaced MemberInjectingFactory<T> implements HasDependencies {

    protected final TypeLiteral<T> type;

    protected final InjectionPoint injectionPoint;

    protected final Set<Dependency<?>> dependencies = new HashSet<>();

    private final Constructor<T> constructor;

    private final MembersInjector<T> injector;

    @Inject
    public MemberInjectingFactory(TypeLiteral<T> type, MembersInjector<T> injector) {
        this.type = type;
        this.injector = injector;
        this.injectionPoint = InjectionPoint.forConstructorOf(type);
        this.constructor = (Constructor<T>) injectionPoint.getMember();
        this.constructor.setAccessible(true);
        dependencies.addAll(Dependency.forInjectionPoints(InjectionPoint.forInstanceMethodsAndFields(type)));
    }

    @Override
    public Set<Dependency<?>> getDependencies() {
        return dependencies;
    }

    public T newInstance(Object... args) {
        final T instance = ExceptionUtils.propagate(() -> constructor.newInstance(args));
        injector.injectMembers(instance);
        return instance;
    }
}

16 Source : ReflectiveParserManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Generates and binds a {@link ReflectiveParser} by reflecting on {@link T}.
 *
 * Does not bind {@link Parser}.
 */
public clreplaced ReflectiveParserManifest<T extends Parseable> extends KeyedManifest {

    private final TypeLiteral<T> type;

    private final Key<ReflectiveParser<T>> parserKey;

    private final Clreplaced<?> baseClreplaced;

    public ReflectiveParserManifest(TypeLiteral<T> type) {
        this(type, Object.clreplaced);
    }

    public ReflectiveParserManifest(TypeLiteral<T> type, Clreplaced<?> baseClreplaced) {
        this.type = type;
        this.parserKey = Key.get(Types.parameterizedTypeLiteral(ReflectiveParser.clreplaced, type));
        this.baseClreplaced = checkNotNull(baseClreplaced);
        checkArgument(type.getRawType().isInterface());
    }

    @Override
    protected Object manifestKey() {
        return type;
    }

    @Override
    protected void configure() {
        final ImplementedBy implementedBy = type.getRawType().getAnnotation(ImplementedBy.clreplaced);
        bind(parserKey).toInstance(new ReflectiveParserImpl(implementedBy != null ? implementedBy.value() : this.baseClreplaced, Members.annotations(Parseable.Property.clreplaced, Methods.declaredMethodsInAncestors(type.getRawType())).merge(this::createProperty).collect(Collectors.toImmutableList())));
    }

    private Property<T, ?> createProperty(Method method, Parseable.Property annotation) {
        if (method.getParameterTypes().length > 0) {
            throw new MethodFormException(method, "Property method cannot take parameters");
        }
        final TypeToken<?> outerType = Types.box(TypeToken.of(method.getGenericReturnType()));
        // If the property method is callable, and the outer type is not already Optional,
        // then it becomes intrinsically Optional. The proxy handles the logic of unwrapping
        // the value or calling the method.
        final Aggregator aggregator;
        if (Methods.isCallable(method) && !Types.isreplacedignable(Optional.clreplaced, outerType)) {
            aggregator = new OptionalAggregator<>(outerType);
        } else {
            aggregator = Aggregator.forType(outerType);
        }
        return createProperty(method, annotation, aggregator);
    }

    private <O, I> Property<O, I> createProperty(Method method, Parseable.Property annotation, Aggregator<O, I> aggregator) {
        // Generate names/aliases
        final String name = StringUtils.nonEmpty(annotation.name()).orElseGet(() -> method.getName().replace('_', '-'));
        final List<String> aliases = ImmutableList.copyOf(annotation.alias());
        // Custom NodeFinders
        final List<Clreplaced<? extends NodeFinder>> finders = Members.annotation(Parseable.Nodes.clreplaced, method).map(annot -> Arrays.asList(annot.value())).orElse(PropertyParser.DEFAULT_NODE_FINDERS);
        // Custom NodeSplitter
        final Clreplaced<? extends NodeSplitter> splitter = Members.annotation(Parseable.Split.clreplaced, method).<Clreplaced<? extends NodeSplitter>>map(Parseable.Split::value).orElse(NodeSplitter.Atom.clreplaced);
        // Validations
        final Parseable.Validate validate = method.getAnnotation(Parseable.Validate.clreplaced);
        final ImmutableList.Builder<Clreplaced<Validation<? super I>>> validations = ImmutableList.builder();
        if (validate != null) {
            for (Clreplaced<? extends Validation> validation : validate.value()) {
                if (!Validation.type(validation).isreplacedignableFrom(aggregator.innerTypeToken())) {
                    throw new MethodFormException(method, "Validation " + validation.getSimpleName() + " is not applicable to property type " + aggregator.innerTypeToken());
                }
                validations.add((Clreplaced<Validation<? super I>>) validation);
            }
        }
        bindProxy(Types.parameterizedTypeLiteral(Parser.clreplaced, aggregator.innerTypeLiteral()));
        return new Property<>(method, new PropertyParser<>(binder(), name, aliases, finders, splitter, aggregator, validations.build()));
    }

    private static clreplaced Property<O, I> {

        final Method method;

        final PropertyParser<O, I> parser;

        final InspectableProperty inspectableProperty = new InspectableProperty() {

            @Override
            public String name() {
                return parser.name();
            }

            @Override
            public Object value(Inspectable inspectable) throws Throwable {
                return method.invoke(inspectable);
            }
        };

        Property(Method method, PropertyParser<O, I> parser) {
            this.method = method;
            this.parser = parser;
        }
    }

    private clreplaced ReflectiveParserImpl implements ReflectiveParser<T> {

        final Clreplaced<? extends T> impl;

        final List<Property<?, ?>> properties;

        final Set<String> propertyNames;

        final MembersInjector<T> injector;

        ReflectiveParserImpl(Clreplaced<?> base, List<Property<?, ?>> properties) {
            InjectionChecks.checkInjectableCGLibProxyBase(base);
            this.properties = properties;
            this.propertyNames = properties.stream().flatMap(property -> property.parser.names().stream()).collect(Collectors.toImmutableSet());
            final Enhancer enhancer = new Enhancer();
            enhancer.setSuperclreplaced(base);
            enhancer.setInterfaces(new Clreplaced[] { type.getRawType() });
            enhancer.setCallbackType(MethodInterceptor.clreplaced);
            enhancer.setUseFactory(true);
            this.impl = enhancer.createClreplaced();
            this.injector = getMembersInjector((Clreplaced<T>) impl);
        }

        @Override
        public T parseElement(Element parent) throws InvalidXMLException {
            // Property methods mapped to their parsed values
            final ImmutableMap.Builder<Method, Object> builder = ImmutableMap.builder();
            // Remember if any property claimed the parent element
            final Set<Node> used = new HashSet<>();
            for (Property<?, ?> property : properties) {
                // Find all nodes for the property
                final Set<Node> nodes = property.parser.findNodes(parent).collect(Collectors.toImmutableSet());
                used.addAll(nodes);
                // Parse!
                final Object value = property.parser.parse(parent, nodes.stream());
                // Handle default value logic
                if (Methods.isCallable(property.method)) {
                    // If the method is callable, then the parsed type is always an Optional (see createProperty() above).
                    final Optional optional = (Optional) value;
                    if (optional.isPresent()) {
                        // If the parsed Optional is present, add it to the map.
                        // Unwrap it if necessary, to match the method's return type.
                        builder.put(property.method, Optional.clreplaced.isreplacedignableFrom(property.method.getReturnType()) ? optional : optional.get());
                    }
                // If it's not present, leave it out of the map entirely, so that the proxy will call the method.
                } else {
                    // If the method is not callable, then the value will always match the method return type
                    builder.put(property.method, value);
                }
            }
            // Throw if any nodes were not parsed by any property
            final Node unused = findUnused(Node.of(parent), used);
            if (unused != null) {
                throw new UnrecognizedXMLException(unused);
            }
            ;
            // Create the proxy and inject it
            return ExceptionUtils.propagate(InvalidXMLException.clreplaced, Injection.unwrapExceptions(() -> {
                final T t = impl.newInstance();
                ((net.sf.cglib.proxy.Factory) t).setCallback(0, new Dispatcher(parent, builder.build()));
                injector.injectMembers(t);
                return t;
            }));
        }

        /**
         * Search the given node tree for the first completely unused node, if any.
         *
         * A node is unused if it's not in the used set, and neither are any of its ancestors or descendants.
         * Partly used nodes don't count as unused, but they are guaranteed to have a completely unused descendant.
         */
        @Nullable
        private Node findUnused(Node node, Set<Node> used) {
            // If node is used, return nothing
            if (used.contains(node))
                return null;
            // Search for unused descendants
            final List<Node> children = node.nodes().collect(Collectors.toImmutableList());
            Node firstUnused = null;
            boolean partlyUsed = false;
            for (Node child : children) {
                final Node unused = findUnused(child, used);
                // Remember the first unused node we find
                if (unused != null && firstUnused == null) {
                    firstUnused = unused;
                }
                // The child itself is not unused, then some descendant must be used
                if (unused != child) {
                    partlyUsed = true;
                }
            }
            // If all children are completely unused, then this node is unused as well
            // Otherwise, return the first completely unused node that we found, if any
            return partlyUsed ? firstUnused : node;
        }

        private clreplaced Dispatcher implements MethodInterceptor {

            // These are the methods we want to intercept
            clreplaced Delegate implements Parseable {

                @Override
                public Optional<Element> sourceElement() {
                    return sourceNode;
                }

                @Override
                public Map<Method, Object> parsedValues() {
                    return values;
                }

                @Override
                public String inspectType() {
                    return type.getRawType().getSimpleName();
                }

                @Override
                public Stream<? extends InspectableProperty> inspectableProperties() {
                    return Stream.concat(Parseable.super.inspectableProperties(), properties.stream().map(property -> property.inspectableProperty));
                }
            }

            final Optional<Element> sourceNode;

            final ImmutableMap<Method, Object> values;

            final Delegate delegate;

            private Dispatcher(Element element, Map<Method, Object> values0) {
                this.values = ImmutableMap.copyOf(values0);
                this.sourceNode = Optional.of(element);
                this.delegate = new Delegate();
            }

            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                // Give our delegate a chance to intercept, and cache the decision
                if (delegatedMethods.get(method, () -> method.getDeclaringClreplaced() != Object.clreplaced && Methods.hasOverrideIn(Delegate.clreplaced, method))) {
                    return method.invoke(delegate, args);
                }
                // If we have a value for the property, return that
                final Object value = values.get(method);
                if (value != null)
                    return value;
                // If there's no value, then the method MUST be callable (or the code is broken).
                // This can only fail for an abstract non-property method (which we should probably be checking for).
                if (method.isDefault()) {
                    // invokeSuper doesn't understand default methods
                    return defaultMethodHandles.get(method).bindTo(obj).invokeWithArguments(args);
                } else {
                    return proxy.invokeSuper(obj, args);
                }
            }
        }
    }

    private static final Cache<Method, Boolean> delegatedMethods = CacheUtils.newCache();

    private static final LoadingCache<Method, MethodHandle> defaultMethodHandles = CacheUtils.newCache(MethodHandleUtils::defaultMethodHandle);
}

16 Source : ParserManifest.java
with GNU Affero General Public License v3.0
from OvercastNetwork

private <T extends Number & Comparable<T>> void bindNumber(Clreplaced<T> rawType) {
    final TypeLiteral<T> type = TypeLiteral.get(rawType);
    final TypeArgument<T> typeArg = new TypeArgument<T>(type) {
    };
    final TypeLiteral<NumberParser<T>> parserType = new ResolvableType<NumberParser<T>>() {
    }.with(typeArg);
    bind(parserType);
    bind(new ResolvableType<TransfiniteParser<T>>() {
    }.with(typeArg)).to(parserType);
    bind(new ResolvableType<PrimitiveParser<T>>() {
    }.with(typeArg)).to(parserType);
    bind(new ResolvableType<Parser<T>>() {
    }.with(typeArg)).to(parserType);
    final TypeLiteral<VectorParser<T>> vectorParserType = new ResolvableType<VectorParser<T>>() {
    }.with(typeArg);
    bind(vectorParserType);
    install(new PropertyManifest<>(type, new ResolvableType<NumberProperty<T>>() {
    }.with(typeArg)));
    if (Types.isreplacedignable(Comparable.clreplaced, type)) {
        install(new RangeParserManifest(type));
    }
}

16 Source : FeatureBinder.java
with GNU Affero General Public License v3.0
from OvercastNetwork

/**
 * Shortcuts for configuring feature {@link T}
 */
public clreplaced FeatureBinder<T extends FeatureDefinition> {

    private final Binder binder;

    private final TypeLiteral<T> type;

    private final TypeArgument<T> typeArg;

    private final Key<T> key;

    protected FeatureBinder(Binder binder) {
        this(binder, (TypeLiteral<T>) null);
    }

    public FeatureBinder(Binder binder, Clreplaced<T> type) {
        this(binder, TypeLiteral.get(type));
    }

    public FeatureBinder(Binder binder, @Nullable TypeLiteral<T> type) {
        this.binder = binder;
        this.type = type != null ? type : new ResolvableType<T>() {
        }.in(getClreplaced());
        this.typeArg = new TypeArgument<T>(this.type) {
        };
        this.key = Key.get(this.type);
        binder.install(new FeatureManifest<>(this.type));
    }

    /**
     * Bind a specialized {@link FeatureParser} for {@link T}.
     *
     * Without this, {@link FeatureParser} itself will be used to parse {@link T}.
     */
    public LinkedBindingBuilder<FeatureParser<T>> bindParser() {
        return binder.bind(key.ofType(new ResolvableType<FeatureParser<T>>() {
        }.with(typeArg)));
    }

    /**
     * Bind the {@link FeatureDefinitionParser} for {@link T}.
     *
     * This binding must exist for {@link T} to be parseable.
     */
    public LinkedBindingBuilder<FeatureDefinitionParser<T>> bindDefinitionParser() {
        return binder.bind(key.ofType(new ResolvableType<FeatureDefinitionParser<T>>() {
        }.with(typeArg)));
    }

    /**
     * Configure a List of {@link T} to be parsed from the root of the doreplacedent automatically,
     * using the default element structure.
     *
     * @see RootFeatureManifest for details
     */
    public void installRootParser() {
        installRootParser(null);
    }

    /**
     * Configure a List of {@link T} to be parsed from the root of the doreplacedent automatically,
     * using the given {@link NodeFinder}.
     *
     * @see RootFeatureManifest for details
     */
    public void installRootParser(@Nullable NodeFinder nodeFinder) {
        binder.install(new RootFeatureManifest<>(type, nodeFinder));
    }

    /**
     * Generate a reflective parser for {@link T}.
     *
     * @see ReflectiveFeatureManifest
     * @see tc.oc.pgm.xml.Parseable
     */
    public void installReflectiveParser() {
        binder.install(new ReflectiveFeatureManifest<>(type));
    }

    /**
     * Configure the given {@link MatchModule} to load if any instances of {@link T} were parsed
     *
     * @see MatchModuleFeatureManifest
     */
    public void installMatchModule(Clreplaced<? extends MatchModule> matchModule) {
        binder.install(new MatchModuleFeatureManifest<>(TypeLiteral.get(matchModule), type));
    }
}

16 Source : DefaultModule.java
with MIT License
from hristo-vrigazov

/**
 * Guice module used for creation of the dependency graph
 */
public clreplaced DefaultModule extends AbstractModule {

    private static final Logger logger = LoggerFactory.getLogger(DefaultModule.clreplaced);

    private Injector dslInjector;

    private String command;

    private Map<String, Object> opts;

    private TypeLiteral<JavascriptGenerator<NameWebDriverActionConfiguration>> javascriptGeneratorByNameAndWebDriverActionConfiguration = new TypeLiteral<JavascriptGenerator<NameWebDriverActionConfiguration>>() {
    };

    private TypeLiteral<ASTNodeConverter<Model, ApplicationConfiguration>> modelASTconverter = new TypeLiteral<ASTNodeConverter<Model, ApplicationConfiguration>>() {
    };

    private TypeLiteral<ASTNodeConverter<ApplicationAction, ApplicationActionConfiguration>> applicationActionASTconverter = new TypeLiteral<ASTNodeConverter<ApplicationAction, ApplicationActionConfiguration>>() {
    };

    private TypeLiteral<ASTNodeConverter<WebDriverActionCondition, WebDriverActionConfiguration>> conditionASTconverter = new TypeLiteral<ASTNodeConverter<WebDriverActionCondition, WebDriverActionConfiguration>>() {
    };

    private TypeLiteral<ASTNodeConverter<WebDriverAction, WebDriverActionConfiguration>> actionASTconverter = new TypeLiteral<ASTNodeConverter<WebDriverAction, WebDriverActionConfiguration>>() {
    };

    private TypeLiteral<ASTNodeConverter<SyntaxDefinition, SyntaxDefinitionConfiguration>> syntaxASTconverter = new TypeLiteral<ASTNodeConverter<SyntaxDefinition, SyntaxDefinitionConfiguration>>() {
    };

    public DefaultModule(String command, Map<String, Object> opts) {
        this.command = command;
        this.opts = opts;
        this.dslInjector = new BromiumStandaloneSetup().createInjectorAndDoEMFRegistration();
    }

    @Override
    protected void configure() {
        bind(BaseRecorderFunctionFactory.clreplaced).to(PredefinedRecorderFunctionFactory.clreplaced);
        bind(FunctionRegistry.clreplaced).to(RecorderFunctionRegistry.clreplaced);
        bind(javascriptGeneratorByNameAndWebDriverActionConfiguration).to(new TypeLiteral<IncludeInvokeGenerator<NameWebDriverActionConfiguration>>() {
        });
        bind(new TypeLiteral<JavascriptGenerator<ApplicationActionConfiguration>>() {
        }).to(RecordingWebDriverActionsOnly.clreplaced);
        bind(new TypeLiteral<FunctionRegistry<NameWebDriverActionConfiguration>>() {
        }).to(RecorderFunctionRegistry.clreplaced);
        bind(new TypeLiteral<Predicate<HttpRequest>>() {
        }).annotatedWith(Names.named(SHOULD_INJECT_JS_PREDICATE)).to(GetHtmlFromCurrentHostPredicate.clreplaced);
        bind(HttpRequestToTestCaseStepConverter.clreplaced).annotatedWith(Names.named(CONVENTION_EVENT_DETECTOR_CONVERTOR)).to(SplitQueryStringOfRequest.clreplaced);
        bind(syntaxASTconverter).to(SyntaxDefinitionASTNodeConverter.clreplaced);
        bind(actionASTconverter).to(ActionASTNodeConverter.clreplaced);
        bind(conditionASTconverter).to(ConditionASTNodeConverter.clreplaced);
        bind(applicationActionASTconverter).to(ApplicationActionASTNodeConverter.clreplaced);
        bind(modelASTconverter).to(TraversingBasedASTNodeConverter.clreplaced);
        bind(ApplicationConfigurationParser.clreplaced).to(DslParser.clreplaced);
        // TODO: other OSes should have a different binding
        bind(VirtualScreenProcessCreator.clreplaced).to(UbuntuVirtualScreenProcessCreator.clreplaced);
        bindConstant().annotatedWith(Names.named(RECORD_TEMPLATE_RESOURCE)).to("/record.js");
        bindConstant().annotatedWith(Names.named(REPLAY_TEMPLATE_RESOURCE)).to("/replay.js");
        // state
        bind(RecordingState.clreplaced).in(Singleton.clreplaced);
        bind(ReplayingState.clreplaced).in(Singleton.clreplaced);
        install(ThrowingProviderBinder.forModule(this));
    }

    @Provides
    public Action.Actions getActions() {
        return new Action.Actions();
    }

    @Provides
    public ResourceSet getResourceSet() {
        return dslInjector.getInstance(ResourceSet.clreplaced);
    }

    @Provides
    public IResourceValidator getResourceValidator() {
        return dslInjector.getInstance(IResourceValidator.clreplaced);
    }

    @CheckedProvides(IOProvider.clreplaced)
    public Map<String, ApplicationActionConfiguration> getNameToActionConfigurationMap(IOProvider<ApplicationConfiguration> configurationIOProvider) throws IOException {
        Map<String, ApplicationActionConfiguration> actionConfigurationMap = new HashMap<>();
        for (ApplicationActionConfiguration applicationActionConfiguration : configurationIOProvider.get().getApplicationActionConfigurationList()) {
            actionConfigurationMap.put(applicationActionConfiguration.getName(), applicationActionConfiguration);
        }
        return actionConfigurationMap;
    }

    @CheckedProvides(IOProvider.clreplaced)
    public StepsDumper getStepsDumper(IOProvider<Map<String, ApplicationActionConfiguration>> configurationIOProvider) throws IOException {
        return new DslStepsDumper(configurationIOProvider.get());
    }

    @CheckedProvides(IOProvider.clreplaced)
    public StepsReader getStepsReader(IOProvider<Map<String, ApplicationActionConfiguration>> configurationIOProvider) throws IOException {
        return new DslStepsReader(configurationIOProvider.get());
    }

    @Provides
    @Named(CONVENTION_EVENT_DETECTOR_PREDICATE)
    public Predicate<HttpRequest> getConventionEventDetectorPredicate() {
        return new UriContainsStringPredicate(SUBMIT_EVENT_URL);
    }

    @Provides
    public ParsedOptions getParsedOptions() {
        return new ParsedOptions(opts);
    }

    @Provides
    @Named(BROWSER_TYPE)
    public String getBrowserType(ParsedOptions parsedOptions) {
        return parsedOptions.getBrowserType();
    }

    @Provides
    @Named(BASE_URL)
    public String getBaseUrl(ParsedOptions parsedOptions) {
        return parsedOptions.getBaseUrl();
    }

    @Provides
    @Named(PATH_TO_DRIVER)
    public String getPathToDriver(ParsedOptions parsedOptions) {
        return parsedOptions.getPathToDriver();
    }

    @Provides
    @Named(OUTPUT_FILE)
    public String getOutputFile(ParsedOptions parsedOptions) {
        return parsedOptions.getOutputFile();
    }

    @Provides
    @Named(TIMEOUT)
    public Integer getTimeout(ParsedOptions parsedOptions) {
        return parsedOptions.getTimeout();
    }

    @Provides
    @Named(MEASUREMENTS_PRECISION_MILLI)
    public Integer getMeasurementsPrecisionMilli(ParsedOptions parsedOptions) {
        return parsedOptions.getMeasurementsPrecisionMilli();
    }

    @Provides
    @Named(CONFIGURATION_FILE)
    public File getConfigurationFile(ParsedOptions parsedOptions) {
        return new File(parsedOptions.getPathToApplicationConfiguration());
    }

    @Provides
    @Named(MEASUREMENTS_FILE)
    public File getMeasurementsFile(ParsedOptions parsedOptions) {
        return new File(parsedOptions.getMeasurements());
    }

    @Provides
    @Named(HAR_FILE)
    public File getHarFile(ParsedOptions parsedOptions) {
        return new File(parsedOptions.getMeasurements() + HAR_EXTENSION);
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(CONFIGURATION_INPUT_STREAM)
    public InputStream getConfigurationInputStream(@Named(CONFIGURATION_FILE) File file) throws FileNotFoundException {
        return new FileInputStream(file);
    }

    @CheckedProvides(IOProvider.clreplaced)
    public ApplicationConfiguration getApplicationConfiguration(ApplicationConfigurationParser applicationConfigurationParser, @Named(CONFIGURATION_FILE) Provider<File> fileProvider) throws IOException {
        File file = fileProvider.get();
        return applicationConfigurationParser.parseApplicationConfiguration(file);
    }

    @Provides
    public WebDriverActionFactory getWebDriverActionFactory(ParsedOptions parsedOptions, Action.Actions actions) {
        Map<String, WebDriverActionParameterParser> additionalRegistry = actions.stream().collect(Collectors.toMap(Action::getWebDriverActionName, Action::getParser));
        return new PredefinedWebDriverActionFactory(parsedOptions.getBaseUrl(), additionalRegistry);
    }

    @Provides
    public PredefinedRecorderFunctionFactory getRecorderFunctionFactory(Action.Actions actions, RecorderFunctionProvider recorderFunctionProvider) {
        List<String> jsFunctionNames = getJsFunctionNames(actions);
        return new PredefinedRecorderFunctionFactory(recorderFunctionProvider, jsFunctionNames);
    }

    private List<String> getJsFunctionNames(Action.Actions actions) {
        return actions.stream().map(Action::getWebDriverActionName).collect(Collectors.toList());
    }

    @Provides
    @Named(COMMAND)
    public String getCommand() {
        return command;
    }

    @Provides
    @Named(CONVENTION_EVENT_DETECTOR)
    public EventDetector getConventionBasedEventDetector(@Named(CONVENTION_EVENT_DETECTOR_PREDICATE) Predicate<HttpRequest> detectorPredicate, @Named(CONVENTION_EVENT_DETECTOR_CONVERTOR) HttpRequestToTestCaseStepConverter detectorConverter) {
        return new EventDetectorImpl(detectorPredicate, detectorConverter);
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(PAGE_LOADING_EVENT_DETECTOR)
    public EventDetector getPageLoadingEventDetector(GetHtmlFromCurrentHostPredicate getHtmlFromCurrentHostPredicate, IOProvider<RequestToPageLoadingEventConverter> requestToPageLoadingEventConverterIOProvider) throws IOException {
        return new EventDetectorImpl(getHtmlFromCurrentHostPredicate, requestToPageLoadingEventConverterIOProvider.get());
    }

    @CheckedProvides(IOProvider.clreplaced)
    public List<EventDetector> getEventDetectors(@Named(CONVENTION_EVENT_DETECTOR) EventDetector conventionEventDetector, @Named(PAGE_LOADING_EVENT_DETECTOR) IOProvider<EventDetector> pageLoadingEventDetectorIOProvider) throws IOException {
        List<EventDetector> eventDetectors = new ArrayList<>();
        eventDetectors.add(conventionEventDetector);
        eventDetectors.add(pageLoadingEventDetectorIOProvider.get());
        return eventDetectors;
    }

    @Provides
    @Named(CONDITION_SATISFIED_PREDICATE)
    public Predicate<HttpRequest> getConditionSatisfiedPredicate() {
        return new UriContainsStringPredicate(CONDITION_SATISFIED_URL);
    }

    @Provides
    @Named(CONDITION_NOT_SATISFIED_PREDICATE)
    public Predicate<HttpRequest> getConditionNotSatisfiedPredicate() {
        return new UriContainsStringPredicate(CONDITION_NOT_SATISFIED_URL);
    }

    @Provides
    public List<ConditionsUpdater> getConditionsUpdaters(@Named(CONDITION_SATISFIED_PREDICATE) Predicate<HttpRequest> conditionSatisfiedPredicate, @Named(CONDITION_NOT_SATISFIED_PREDICATE) Predicate<HttpRequest> conditionNotSatisfiedPredicate, @Named(SUBSreplacedUTION_REGISTRATION_PREDICATE) Predicate<HttpRequest> subsreplacedutionRegistrationPredicate) {
        List<ConditionsUpdater> conditionsUpdaters = new ArrayList<>();
        conditionsUpdaters.add(new ConditionsUpdater(conditionSatisfiedPredicate, new SignalizingStateConditionsUpdater()));
        conditionsUpdaters.add(new ConditionsUpdater(conditionNotSatisfiedPredicate, ReplayingState::setConditionNotSatisfied));
        conditionsUpdaters.add(new ConditionsUpdater(subsreplacedutionRegistrationPredicate, new SubsreplacedutionRegistrationUpdater()));
        return conditionsUpdaters;
    }

    @CheckedProvides(IOProvider.clreplaced)
    public RequestFilter getRequestFilter(@Named(COMMAND) String command, IOProvider<List<EventDetector>> eventDetectorListProvider, Provider<RecordingState> recordingStateProvider, Provider<ReplayingState> replayingStateProvider, Provider<List<ConditionsUpdater>> conditionsUpdaters) throws IOException {
        switch(command) {
            case RECORD:
                return new RecordRequestFilter(recordingStateProvider.get(), eventDetectorListProvider.get());
            case REPLAY:
                return new ReplayRequestFilter(replayingStateProvider.get(), conditionsUpdaters.get());
            default:
                throw new NoSuchCommandException();
        }
    }

    @CheckedProvides(IOProvider.clreplaced)
    public ResponseFilter getResponseFilter(@Named(COMMAND) String command, ReplayingState replayingState, @Named(SHOULD_INJECT_JS_PREDICATE) Predicate<HttpRequest> httpRequestPredicate, @Named(RECORDING_JAVASCRIPT_CODE) IOProvider<String> recordingJavascriptCodeProvider, @Named(REPLAYING_JAVASCRIPT_CODE) IOProvider<String> replayingJavascriptCodeProvider) throws IOException {
        switch(command) {
            case RECORD:
                return new RecordResponseFilter(recordingJavascriptCodeProvider.get(), httpRequestPredicate);
            case REPLAY:
                return new ReplayResponseFilter(replayingJavascriptCodeProvider.get(), replayingState, httpRequestPredicate);
            default:
                throw new NoSuchCommandException();
        }
    }

    @CheckedProvides(IOProvider.clreplaced)
    public ApplicationActionFactory getApplicationActionFactory(IOProvider<ApplicationConfiguration> applicationConfigurationIOProvider, TestCaseStepToApplicationActionConverter testCaseStepToApplicationActionConverter) throws IOException {
        ApplicationConfiguration applicationConfiguration = applicationConfigurationIOProvider.get();
        return new DefaultApplicationActionFactory(applicationConfiguration, testCaseStepToApplicationActionConverter);
    }

    @CheckedProvides(IOProvider.clreplaced)
    public TestScenarioFactory getTestScenarioFactory(IOProvider<ApplicationActionFactory> applicationActionFactoryIOProvider, IOProvider<StepsReader> stepsReaderIOProvider) throws IOException {
        ApplicationActionFactory applicationActionFactory = applicationActionFactoryIOProvider.get();
        return new TestScenarioFactory(applicationActionFactory, stepsReaderIOProvider.get());
    }

    @Provides
    @Named(TEST_CASE_FILE)
    public File getTestCaseFile(ParsedOptions parsedOptions) {
        return new File(parsedOptions.getPathToTestCase());
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(TEST_CASE_INPUT_STREAM)
    public InputStream getTestCaseInputStream(@Named(TEST_CASE_FILE) File file) throws FileNotFoundException {
        return new FileInputStream(file);
    }

    @CheckedProvides(IOProvider.clreplaced)
    public TestScenarioSteps getTestCaseSteps(IOProvider<StepsReader> stepsReaderIOProvider, @Named(TEST_CASE_INPUT_STREAM) IOProvider<InputStream> testCaseInputStreamProvider) throws IOException {
        return stepsReaderIOProvider.get().readSteps(testCaseInputStreamProvider.get());
    }

    @CheckedProvides(IOProvider.clreplaced)
    public StepsAndConfiguration getStepsAndConfiguration(IOProvider<TestScenarioSteps> stepsProvider, IOProvider<ApplicationConfiguration> applicationConfigurationIOProvider) throws IOException {
        TestScenarioSteps testCaseSteps = stepsProvider.get();
        ApplicationConfiguration applicationConfiguration = applicationConfigurationIOProvider.get();
        return new StepsAndConfiguration(testCaseSteps, applicationConfiguration);
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(BASE_REPLAYING_TEMPLATE)
    public String getBaseReplayingTemplate(@Named(REPLAY_TEMPLATE_RESOURCE) String templateResource) throws IOException {
        return IOUtils.toString(getClreplaced().getResourcereplacedtream(templateResource));
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(BASE_RECORDING_TEMPLATE)
    public String getBaseRecordingTemplate(@Named(RECORD_TEMPLATE_RESOURCE) String templateResource) throws IOException {
        return IOUtils.toString(getClreplaced().getResourcereplacedtream(templateResource));
    }

    @Provides
    @Named(SCREEN_NUMBER)
    public Integer getScreenNumber(ParsedOptions parsedOptions) {
        return parsedOptions.getScreenNumber();
    }

    @Provides
    @Named(SCREEN)
    public String getScreenreplacedcreen(@Named(SCREEN_NUMBER) Integer screenNumber, VirtualScreenProcessCreator virtualScreenProcessCreator) {
        return virtualScreenProcessCreator.getScreen(screenNumber);
    }

    @Provides
    public BaseReplayFunctionFactory getBaseReplayFunctionFactory(ReplayFunctionProvider replayFunctionProvider, Action.Actions actions) {
        return new PredefinedReplayFunctionFactory(replayFunctionProvider, getJsFunctionNames(actions));
    }

    @Provides
    public ReplayFunctionRegistry getReplayFunctionRegistry(BaseReplayFunctionFactory baseReplayFunctionFactory) {
        return new ReplayFunctionRegistry(baseReplayFunctionFactory);
    }

    @Provides
    public JavascriptGenerator<StepAndWebDriverActionConfiguration> getIncludeInvokeGeneratorByStepAndWebDriverActionConfiguration(ReplayFunctionRegistry replayFunctionRegistry) {
        return new IncludeInvokeGenerator<>(replayFunctionRegistry);
    }

    @Provides
    public JavascriptGenerator<StepAndActionConfiguration> getReplayGeneratorByStepAndActionConfiguration(JavascriptGenerator<StepAndWebDriverActionConfiguration> generator, StepAndWebDriverActionConfigurationSupplier supplier) {
        return new ReplayGeneratorByStepAndActionConfiguration(generator, supplier);
    }

    @CheckedProvides(IOProvider.clreplaced)
    public ReplayingJavascriptGenerator getReplayingJavascriptGenerator(@Named(BASE_REPLAYING_TEMPLATE) IOProvider<String> baseTemplateProvider, JavascriptGenerator<StepAndActionConfiguration> generatorByStepAndActionConfiguration, StepAndActionConfigurationSupplier stepAndActionConfigurationSupplier) throws IOException {
        return new ReplayingJavascriptGenerator(baseTemplateProvider.get(), generatorByStepAndActionConfiguration, stepAndActionConfigurationSupplier);
    }

    @CheckedProvides(IOProvider.clreplaced)
    public RecordingJavascriptGenerator getRecordingJavascriptGenerator(@Named(BASE_RECORDING_TEMPLATE) IOProvider<String> baseTemplateProvider, JavascriptGenerator<ApplicationActionConfiguration> applicationActionJavascriptGenerator, RecordContextBuildersGenerator recordContextBuildersGenerator) throws IOException {
        return new RecordingJavascriptGenerator(baseTemplateProvider.get(), applicationActionJavascriptGenerator, recordContextBuildersGenerator);
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(GENERATED_REPLAY_JAVASCRIPT)
    public String getGeneratedReplayJavascript(IOProvider<ReplayingJavascriptGenerator> replayingJavascriptGeneratorProvider, IOProvider<StepsAndConfiguration> stepsAndConfigurationIOProvider) throws IOException {
        StepsAndConfiguration stepsAndConfiguration = stepsAndConfigurationIOProvider.get();
        ReplayingJavascriptGenerator replayingJavascriptGenerator = replayingJavascriptGeneratorProvider.get();
        String result = replayingJavascriptGenerator.generate(stepsAndConfiguration);
        logger.info(result);
        return result;
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(GENERATED_RECORD_JAVASCRIPT)
    public String getGeneratedRecordJavascript(IOProvider<RecordingJavascriptGenerator> recordingJavascriptGeneratorIOProvider, IOProvider<ApplicationConfiguration> configurationIOProvider) throws IOException {
        ApplicationConfiguration configuration = configurationIOProvider.get();
        RecordingJavascriptGenerator recordingJavascriptGenerator = recordingJavascriptGeneratorIOProvider.get();
        String result = recordingJavascriptGenerator.generate(configuration);
        logger.info(result);
        return result;
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(REPLAYING_JAVASCRIPT_INJECTOR)
    public JavascriptInjectionPreparator getReplayingJavascriptInjector(@Named(GENERATED_REPLAY_JAVASCRIPT) IOProvider<String> generatedReplayJavascript) throws IOException {
        String generatedCode = generatedReplayJavascript.get();
        return new JavascriptInjectionPreparator(new StringReader(generatedCode));
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(RECORDING_JAVASCRIPT_INJECTOR)
    public JavascriptInjectionPreparator getRecordingJavascriptInjector(@Named(GENERATED_RECORD_JAVASCRIPT) IOProvider<String> generatedRecordJavascript) throws IOException {
        String generatedCode = generatedRecordJavascript.get();
        return new JavascriptInjectionPreparator(new StringReader(generatedCode));
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(REPLAYING_JAVASCRIPT_CODE)
    public String getReplayingJavascriptCode(@Named(REPLAYING_JAVASCRIPT_INJECTOR) IOProvider<JavascriptInjectionPreparator> javascriptInjectorIOProvider) throws IOException {
        String javascriptCode = javascriptInjectorIOProvider.get().getInjectionCode();
        logger.debug(javascriptCode);
        return javascriptCode;
    }

    @CheckedProvides(IOProvider.clreplaced)
    @Named(RECORDING_JAVASCRIPT_CODE)
    public String getRecordingJavascriptCode(@Named(RECORDING_JAVASCRIPT_INJECTOR) IOProvider<JavascriptInjectionPreparator> javascriptInjectorIOProvider) throws IOException {
        String generatedJavascriptCode = javascriptInjectorIOProvider.get().getInjectionCode();
        logger.debug(generatedJavascriptCode);
        return generatedJavascriptCode;
    }

    @CheckedProvides(IOURIProvider.clreplaced)
    public ExecutorDependencies getExecutorBuilder(ExecutorDependencies executorDependencies, @Named(TIMEOUT) int timeout, @Named(BASE_URL) String baseUrl, @Named(REPLAYING_JAVASCRIPT_CODE) IOProvider<String> replayingJavascriptCodeProvider, @Named(SCREEN) String screen, @Named(SCREEN_NUMBER) int screenNumber, @Named(PATH_TO_DRIVER) String pathToDriver, @Named(MEASUREMENTS_PRECISION_MILLI) int measurementsPrecisionMilli, EventSynchronizer eventSynchronizer, ReplayingState replayingState, IOURIProvider<DriverOperations> driverOperationsIOURIProvider) throws IOException, URISyntaxException {
        return executorDependencies.pathToDriverExecutable(pathToDriver).baseURL(baseUrl).timeoutInSeconds(timeout).measurementsPrecisionInMilliseconds(measurementsPrecisionMilli).javascriptInjectionCode(replayingJavascriptCodeProvider.get()).screenNumber(screenNumber).screenToUse(screen).replayingState(replayingState).eventSynchronizer(eventSynchronizer).driverOperations(driverOperationsIOURIProvider.get());
    }

    @CheckedProvides(IOURIProvider.clreplaced)
    public RecordBrowser getRecordBrowser(@Named(BASE_URL) String baseUrl, IOURIProvider<DriverOperations> driverOperationsIOURIProvider, RecordingState recordingState) throws IOException, URISyntaxException {
        return new RecordBrowser(baseUrl, driverOperationsIOURIProvider.get(), recordingState::getTestScenarioSteps);
    }

    @CheckedProvides(IOURIProvider.clreplaced)
    public WebDriverActionExecutor getWebDriverActionExecution(IOURIProvider<ExecutorDependencies> executorBuilderIOProvider) throws IOException, URISyntaxException {
        return new ActionExecutor(executorBuilderIOProvider.get());
    }

    @CheckedProvides(IOURIProvider.clreplaced)
    public ReplayBrowser getReplayBrowser(IOProvider<TestScenarioFactory> testScenarioFactoryIOProvider, IOURIProvider<WebDriverActionExecutor> execution) throws IOException, URISyntaxException {
        return new ReplayBrowser(testScenarioFactoryIOProvider.get(), execution.get());
    }

    @Named(BASE_URI)
    @Provides
    public URI getBaseUri(@Named(BASE_URL) String baseUrl) {
        return URI.create(baseUrl);
    }

    @CheckedProvides(IOURIProvider.clreplaced)
    public ProxyDriverIntegrator getProxyDriverIntegrator(IOProvider<RequestFilter> requestFilterIOProvider, IOProvider<ResponseFilter> responseFilterIOURIProvider, WebDriverSupplier webDriverSupplier, DriverServiceSupplier driverServiceSupplier, @Named(PATH_TO_DRIVER) String pathToDriverExecutable, @Named(SCREEN) String screen, @Named(TIMEOUT) int timeout) throws IOException, URISyntaxException {
        return getProxyDriverIntegrator(requestFilterIOProvider.get(), webDriverSupplier, driverServiceSupplier, pathToDriverExecutable, screen, timeout, responseFilterIOURIProvider.get());
    }

    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);
    }

    @Provides
    public WebDriverSupplier getInvisibleWebDriverSupplier(@Named(BROWSER_TYPE) String browserType) {
        switch(browserType) {
            case CHROME:
                return new ChromeDriverSupplier();
            default:
                throw new BrowserTypeNotSupportedException();
        }
    }

    @Provides
    public DriverServiceSupplier getDriverServiceSupplier(@Named(BROWSER_TYPE) String browserType) {
        switch(browserType) {
            case CHROME:
                return new ChromeDriverServiceSupplier();
            default:
                throw new BrowserTypeNotSupportedException();
        }
    }

    @CheckedProvides(IOURIProvider.clreplaced)
    public DriverOperations getDriverOperations(IOURIProvider<ProxyDriverIntegrator> proxyDriverIntegratorIOURIProvider) throws IOException, URISyntaxException {
        return new DriverOperations(proxyDriverIntegratorIOURIProvider.get());
    }

    public BrowserMobProxy createBrowserMobProxy(int timeout, RequestFilter requestFilter, ResponseFilter responseFilter) {
        BrowserMobProxyServer proxy = new BrowserMobProxyServer();
        proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
        proxy.newHar("measurements");
        proxy.addRequestFilter(requestFilter);
        proxy.addResponseFilter(responseFilter);
        proxy.setIdleConnectionTimeout(timeout, TimeUnit.SECONDS);
        proxy.setRequestTimeout(timeout, TimeUnit.SECONDS);
        return proxy;
    }

    public Proxy createSeleniumProxy(BrowserMobProxy proxy) {
        return ClientUtil.createSeleniumProxy(proxy);
    }

    public DesiredCapabilities createDesiredCapabilities(Proxy proxy) {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.PROXY, proxy);
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--test-type");
        options.addArguments("--start-maximized");
        options.addArguments("--disable-web-security");
        options.addArguments("--allow-file-access-from-files");
        options.addArguments("--allow-running-insecure-content");
        options.addArguments("--allow-cross-origin-auth-prompt");
        options.addArguments("--allow-file-access");
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        return capabilities;
    }

    @Provides
    @Singleton
    public EventSynchronizer getEventSynchronizer(@Named(TIMEOUT) Integer timeout) {
        return new SignalizationBasedEventSynchronizer(timeout);
    }

    @CheckedProvides(IOProvider.clreplaced)
    public ActionsFilter getActionsFilter(IOProvider<ApplicationConfiguration> applicationConfigurationIOProvider) throws IOException {
        return new ActionsFilter(applicationConfigurationIOProvider.get().getApplicationActionConfigurationList());
    }

    @CheckedProvides(IOProvider.clreplaced)
    public RequestToPageLoadingEventConverter getHttpRequestToTestCaseStepConverter(@Named(BASE_URL) String baseUrl, IOProvider<ActionsFilter> actionsFilterIOProvider) throws IOException {
        return new RequestToPageLoadingEventConverter(baseUrl, actionsFilterIOProvider.get());
    }

    @Provides
    @Named(SUBSreplacedUTION_REGISTRATION_PREDICATE)
    public Predicate<HttpRequest> getSubsreplacedutionRegistrationPredicate() {
        return new UriContainsStringPredicate(REGISTER_SUBSreplacedUTION_URL);
    }
}

See More Examples