kandi background
Explore Kits

guice | Google Guice Extensions

 by   mycila Java Version: Current License: No License

 by   mycila Java Version: Current License: No License

Download this library from

kandi X-RAY | guice Summary

guice is a Java library. guice has no bugs, it has no vulnerabilities, it has build file available and it has high support. You can download it from GitHub, Maven.
This project contains a set of Google Guice Extensions useful in every-days development with Google Guice.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • guice has a highly active ecosystem.
  • It has 41 star(s) with 7 fork(s). There are 2 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 3 open issues and 8 have been closed. On average issues are closed in 16 days. There are no pull requests.
  • It has a positive sentiment in the developer community.
  • The latest version of guice is current.
guice Support
Best in #Java
Average in #Java
guice Support
Best in #Java
Average in #Java

quality kandi Quality

  • guice has 0 bugs and 0 code smells.
guice Quality
Best in #Java
Average in #Java
guice Quality
Best in #Java
Average in #Java

securitySecurity

  • guice has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • guice code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
guice Security
Best in #Java
Average in #Java
guice Security
Best in #Java
Average in #Java

license License

  • guice does not have a standard license declared.
  • Check the repository for any license declaration and review the terms closely.
  • Without a license, all rights are reserved, and you cannot use the library in your applications.
guice License
Best in #Java
Average in #Java
guice License
Best in #Java
Average in #Java

buildReuse

  • guice releases are not available. You will need to build from source code and install.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • It has 4591 lines of code, 454 functions and 106 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
guice Reuse
Best in #Java
Average in #Java
guice Reuse
Best in #Java
Average in #Java
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

guice Key Features

OSGi Compliant:

Build status:

Issues: https://github.com/mycila/license-maven-plugin/issues

License: Apache License 2.0

@mgoellnitz

@keeganwitt

3.6.ga (2015-01-23) - see issues and pull requests

Releases: http://repo1.maven.org/maven2/com/mycila/guice/extensions/

Snapshots: https://oss.sonatype.org/content/repositories/snapshots/com/mycila/guice/extensions/

guice Examples and Code Snippets

See all related Code Snippets

1. Customizes injection annotations

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice.extensions</groupId>
    <artifactId>mycila-guice-injection</artifactId>
    <version>X.Y.ga</version>
</dependency>

2. Closeable Injector

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice.extensions</groupId>
    <artifactId>mycila-guice-closeable</artifactId>
    <version>X.Y.ga</version>
</dependency>

3. JSR-250

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice.extensions</groupId>
    <artifactId>mycila-guice-jsr250</artifactId>
    <version>X.Y.ga</version>
</dependency>

4. Legacy and Factory Binder

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice.extensions</groupId>
    <artifactId>mycila-guice-legacy</artifactId>
    <version>X.Y.ga</version>
</dependency>

5. Service and Module discovery

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice.extensions</groupId>
    <artifactId>mycila-guice-service</artifactId>
    <version>X.Y.ga</version>
</dependency>

6. Web Extensions

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice.extensions</groupId>
    <artifactId>mycila-guice-web</artifactId>
    <version>X.Y.ga</version>
</dependency>

7. Groovy Extensions

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice.extensions</groupId>
    <artifactId>mycila-guice-groovy</artifactId>
    <version>X.Y.ga</version>
</dependency>

8. Servlet Extension

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice</groupId>
    <artifactId>guice-servlet</artifactId>
    <version>X.Y.ga</version>
</dependency>

Get everything in one package

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.mycila.guice</groupId>
    <artifactId>mycila-guice-all</artifactId>
    <version>X.Y.ga</version>
</dependency>

Create MessageDigest with Guice

copy iconCopydownload iconDownload
final MessageDigestModule extends AbstractModule {
  @Provide
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
  @Provide
  @Md5
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
  @Provide
  @Sha256
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("SHA-256");
  }
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
final MessageDigestModule extends AbstractModule {
  @Provide
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
  @Provide
  @Md5
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
  @Provide
  @Sha256
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("SHA-256");
  }
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
final MessageDigestModule extends AbstractModule {
  @Provide
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
  @Provide
  @Md5
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
  @Provide
  @Sha256
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("SHA-256");
  }
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
final MessageDigestModule extends AbstractModule {
  @Provide
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}
final MessageDigestModule extends AbstractModule {
  @Provide
  @Md5
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
  @Provide
  @Sha256
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("SHA-256");
  }
}
@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;
@Provides
MessageDigest provideMD5() throws NoSuchAlgorithmException {
  return MessageDigest.getInstance("MD5");
}
@Inject
Provider<MessageDigest> md5Provider;

...

// Later in the class
MessageDigest md5 = md5Provider.get();
@Provides
MessageDigest provideMD5() throws NoSuchAlgorithmException {
  return MessageDigest.getInstance("MD5");
}
@Inject
Provider<MessageDigest> md5Provider;

...

// Later in the class
MessageDigest md5 = md5Provider.get();

Spring Boot Logging to a File

copy iconCopydownload iconDownload
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.formatter = org.springframework.boot.logging.java.SimpleFormatter
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.ConsoleHandler.formatter = org.springframework.boot.logging.java.SimpleFormatter

Java : io.protostuff.compiler.parser.ParserException: Can not load proto

copy iconCopydownload iconDownload
/some/directory/imports$ tree -d -L 2
.
├── envoyproxy
│   └── protoc-gen-validate
└── google
    ├── api
    ├── protobuf
    └── rpc
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.protostuff.compiler.ParserModule;
import io.protostuff.compiler.model.Message;
import io.protostuff.compiler.model.Proto;
import io.protostuff.compiler.parser.FileReader;
import io.protostuff.compiler.parser.FileReaderFactory;
import io.protostuff.compiler.parser.Importer;
import io.protostuff.compiler.parser.ProtoContext;
import java.nio.file.Path;
import java.util.List;

public final class Program {
    public static void main(final String[] args) {
        final Injector injector = Guice.createInjector(new ParserModule());

        final FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
        final List<Path> includePaths = List.of(
            Path.of("/some/directory/imports")
        );
        final FileReader fileReader = fileReaderFactory.create(includePaths);

        final Importer importer = injector.getInstance(Importer.class);
        final ProtoContext protoContext = importer.importFile(
            fileReader,
            "/some/other/directory/test.proto"
        );

        final Proto proto = protoContext.getProto();

        final List<Message> messages = proto.getMessages();
        System.out.println(String.format("Messages: %s", messages));
    }
}
Messages: [Message{name=SendRequest, fullyQualifiedName=.grpc.SendRequest, fields=[Field{name=data, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=document, typeName=bytes, tag=2, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}, Message{name=SendResponse, fullyQualifiedName=.grpc.SendResponse, fields=[Field{name=Status, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=Message, typeName=string, tag=2, options=DynamicMessage{fields={}}}, Field{name=DocumentList, modifier=repeated, typeName=string, tag=3, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}]
/some/directory/imports$ tree -d -L 2
.
├── envoyproxy
│   └── protoc-gen-validate
└── google
    ├── api
    ├── protobuf
    └── rpc
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.protostuff.compiler.ParserModule;
import io.protostuff.compiler.model.Message;
import io.protostuff.compiler.model.Proto;
import io.protostuff.compiler.parser.FileReader;
import io.protostuff.compiler.parser.FileReaderFactory;
import io.protostuff.compiler.parser.Importer;
import io.protostuff.compiler.parser.ProtoContext;
import java.nio.file.Path;
import java.util.List;

public final class Program {
    public static void main(final String[] args) {
        final Injector injector = Guice.createInjector(new ParserModule());

        final FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
        final List<Path> includePaths = List.of(
            Path.of("/some/directory/imports")
        );
        final FileReader fileReader = fileReaderFactory.create(includePaths);

        final Importer importer = injector.getInstance(Importer.class);
        final ProtoContext protoContext = importer.importFile(
            fileReader,
            "/some/other/directory/test.proto"
        );

        final Proto proto = protoContext.getProto();

        final List<Message> messages = proto.getMessages();
        System.out.println(String.format("Messages: %s", messages));
    }
}
Messages: [Message{name=SendRequest, fullyQualifiedName=.grpc.SendRequest, fields=[Field{name=data, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=document, typeName=bytes, tag=2, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}, Message{name=SendResponse, fullyQualifiedName=.grpc.SendResponse, fields=[Field{name=Status, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=Message, typeName=string, tag=2, options=DynamicMessage{fields={}}}, Field{name=DocumentList, modifier=repeated, typeName=string, tag=3, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}]
/some/directory/imports$ tree -d -L 2
.
├── envoyproxy
│   └── protoc-gen-validate
└── google
    ├── api
    ├── protobuf
    └── rpc
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.protostuff.compiler.ParserModule;
import io.protostuff.compiler.model.Message;
import io.protostuff.compiler.model.Proto;
import io.protostuff.compiler.parser.FileReader;
import io.protostuff.compiler.parser.FileReaderFactory;
import io.protostuff.compiler.parser.Importer;
import io.protostuff.compiler.parser.ProtoContext;
import java.nio.file.Path;
import java.util.List;

public final class Program {
    public static void main(final String[] args) {
        final Injector injector = Guice.createInjector(new ParserModule());

        final FileReaderFactory fileReaderFactory = injector.getInstance(FileReaderFactory.class);
        final List<Path> includePaths = List.of(
            Path.of("/some/directory/imports")
        );
        final FileReader fileReader = fileReaderFactory.create(includePaths);

        final Importer importer = injector.getInstance(Importer.class);
        final ProtoContext protoContext = importer.importFile(
            fileReader,
            "/some/other/directory/test.proto"
        );

        final Proto proto = protoContext.getProto();

        final List<Message> messages = proto.getMessages();
        System.out.println(String.format("Messages: %s", messages));
    }
}
Messages: [Message{name=SendRequest, fullyQualifiedName=.grpc.SendRequest, fields=[Field{name=data, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=document, typeName=bytes, tag=2, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}, Message{name=SendResponse, fullyQualifiedName=.grpc.SendResponse, fields=[Field{name=Status, typeName=string, tag=1, options=DynamicMessage{fields={}}}, Field{name=Message, typeName=string, tag=2, options=DynamicMessage{fields={}}}, Field{name=DocumentList, modifier=repeated, typeName=string, tag=3, options=DynamicMessage{fields={}}}], options=DynamicMessage{fields={}}}]

AroundInvoke: Curious name?

copy iconCopydownload iconDownload
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception { ... }
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
   log.info("We're about to do the thing!");
   Object result = ctx.proceed();
   log.info("We did the thing!");
   return result;
}
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception { ... }
@AroundInvoke
public Object intercept(InvocationContext ctx) throws Exception {
   log.info("We're about to do the thing!");
   Object result = ctx.proceed();
   log.info("We did the thing!");
   return result;
}

Guice generic type injection

copy iconCopydownload iconDownload
public class Base<T extends Stoppable> {

  protected final Injector injector;
  protected T stoppable;

  public Base(Class<T> type, Module... module) {
    injector = Guice.createInjector(module);
    var key = Key.get(com.google.inject.util.Types.setOf(type));
    stoppable = injector.getInstance(key);
  }
}

How to Manage JNDI Context In JUnit Tests?

copy iconCopydownload iconDownload
private static Context context;
    
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";

//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
    if( context == null)
    {
        context = new InitialContext();  
        context.createSubcontext("java:comp/env");
        context.createSubcontext("java:comp/env/jdbc");
    }
    return context;
}

@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
    
    BasicDataSource ds = null;  
    ds = new BasicDataSource();
    ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
                
    Context context = getContext(); 
    context.rebind(NAV_DS, ds);                             
            
    return ds;
}
public class TestContextFactory implements InitialContextFactory {

    private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
    
    @Override
    public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
        return currentContext.get();
    }

    public static void setCurrentContext(Context context) {
        currentContext.set(context);
    }

    public static void clearCurrentContext() {
        currentContext.remove();
    }

}
public class MockInitialContextRule implements TestRule {

    private final Context context;

    public MockInitialContextRule(Context context) {
        this.context = context;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
                TestContextFactory.setCurrentContext(context);
                try {
                    base.evaluate();
                } finally {
                    System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
                    TestContextFactory.clearCurrentContext();
                }
            }
        };
    }

}
@Inject
private Context context;

@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);

@Test
public void testFoo()
{
    Object foo = context.lookup("jdbc/NavDS");
    assertNotNull(foo);
}
private static Context context;
    
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";

//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
    if( context == null)
    {
        context = new InitialContext();  
        context.createSubcontext("java:comp/env");
        context.createSubcontext("java:comp/env/jdbc");
    }
    return context;
}

@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
    
    BasicDataSource ds = null;  
    ds = new BasicDataSource();
    ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
                
    Context context = getContext(); 
    context.rebind(NAV_DS, ds);                             
            
    return ds;
}
public class TestContextFactory implements InitialContextFactory {

    private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
    
    @Override
    public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
        return currentContext.get();
    }

    public static void setCurrentContext(Context context) {
        currentContext.set(context);
    }

    public static void clearCurrentContext() {
        currentContext.remove();
    }

}
public class MockInitialContextRule implements TestRule {

    private final Context context;

    public MockInitialContextRule(Context context) {
        this.context = context;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
                TestContextFactory.setCurrentContext(context);
                try {
                    base.evaluate();
                } finally {
                    System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
                    TestContextFactory.clearCurrentContext();
                }
            }
        };
    }

}
@Inject
private Context context;

@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);

@Test
public void testFoo()
{
    Object foo = context.lookup("jdbc/NavDS");
    assertNotNull(foo);
}
private static Context context;
    
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";

//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
    if( context == null)
    {
        context = new InitialContext();  
        context.createSubcontext("java:comp/env");
        context.createSubcontext("java:comp/env/jdbc");
    }
    return context;
}

@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
    
    BasicDataSource ds = null;  
    ds = new BasicDataSource();
    ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
                
    Context context = getContext(); 
    context.rebind(NAV_DS, ds);                             
            
    return ds;
}
public class TestContextFactory implements InitialContextFactory {

    private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
    
    @Override
    public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
        return currentContext.get();
    }

    public static void setCurrentContext(Context context) {
        currentContext.set(context);
    }

    public static void clearCurrentContext() {
        currentContext.remove();
    }

}
public class MockInitialContextRule implements TestRule {

    private final Context context;

    public MockInitialContextRule(Context context) {
        this.context = context;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
                TestContextFactory.setCurrentContext(context);
                try {
                    base.evaluate();
                } finally {
                    System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
                    TestContextFactory.clearCurrentContext();
                }
            }
        };
    }

}
@Inject
private Context context;

@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);

@Test
public void testFoo()
{
    Object foo = context.lookup("jdbc/NavDS");
    assertNotNull(foo);
}
private static Context context;
    
private static final String NAV_DS = "java:comp/env/jdbc/NavDS";

//using a provider method here so we can inject the context into the test
@Provides
public Context getContext() throws NamingException
{
    if( context == null)
    {
        context = new InitialContext();  
        context.createSubcontext("java:comp/env");
        context.createSubcontext("java:comp/env/jdbc");
    }
    return context;
}

@Provides
@Singleton
public DataSource getNavDS() throws NamingException {
    
    BasicDataSource ds = null;  
    ds = new BasicDataSource();
    ds.setUrl("jdbc:h2:mem:myDB;create=true;MODE=MSSQLServer;DATABASE_TO_UPPER=FALSE;");
                
    Context context = getContext(); 
    context.rebind(NAV_DS, ds);                             
            
    return ds;
}
public class TestContextFactory implements InitialContextFactory {

    private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();
    
    @Override
    public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
        return currentContext.get();
    }

    public static void setCurrentContext(Context context) {
        currentContext.set(context);
    }

    public static void clearCurrentContext() {
        currentContext.remove();
    }

}
public class MockInitialContextRule implements TestRule {

    private final Context context;

    public MockInitialContextRule(Context context) {
        this.context = context;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestContextFactory.class.getName());
                TestContextFactory.setCurrentContext(context);
                try {
                    base.evaluate();
                } finally {
                    System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
                    TestContextFactory.clearCurrentContext();
                }
            }
        };
    }

}
@Inject
private Context context;

@Rule
public MockInitialContextRule mockInitialContextRule = new MockInitialContextRule(context);

@Test
public void testFoo()
{
    Object foo = context.lookup("jdbc/NavDS");
    assertNotNull(foo);
}

Wire collection of objects dynamically in Guice

copy iconCopydownload iconDownload
class ThingyModuleTest {

    static class Thingy<T>{
        private final T value;
        Thingy(final T value) {this.value = value;}
        @Override public boolean equals(final Object o) {
            if (this == o) { return true; }
            if (o == null || getClass() != o.getClass()) { return false; }
            final Thingy<?> thingy = (Thingy<?>) o; return Objects.equals(value, thingy.value); }
        @Override public int hashCode() { return Objects.hash(value); }
    }

    @Singleton
    static class ThingyService{
        final Set<Thingy<?>> thingies;
        @SuppressWarnings({"unchecked", "rawtypes"}) @Inject
        ThingyService(Set<Thingy> thingies) {
            this.thingies = ImmutableSet.copyOf((Set)thingies);
        }
        public Set<Thingy<?>> getThingies() { return thingies; }
    }

    abstract static class ThingyModule extends AbstractModule {
        private final Set<Class<?>> classesToScan;
        public ThingyModule(Class<?>... classes) {
            this.classesToScan = ImmutableSet.copyOf(classes);
        }

        private Set<Thingy<?>> scanForThingies(){
                return classesToScan.stream()
                         .flatMap(c-> Arrays.stream(c.getDeclaredFields()))
                         .filter(f->f.getType().isAssignableFrom(Thingy.class))
                         .filter(f-> Modifier.isStatic(f.getModifiers())&&Modifier.isFinal(f.getModifiers()))
                         .map(this::readThingy)
                         .filter(Optional::isPresent)
                         .map(Optional::get)
                         .collect(Collectors.toSet());
        }

        @SuppressWarnings("unchecked")
        private Optional<Thingy<?>> readThingy(final Field field) {
            try{
                field.setAccessible(true);
                return Optional.ofNullable(field.get(null))
                    .filter(Thingy.class::isInstance)
                    .map(Thingy.class::cast);
            } catch (IllegalAccessException e) { return Optional.empty(); }
        }

        @Override protected void configure() {
            bind(ThingyService.class);
            @SuppressWarnings("rawtypes") Multibinder<Thingy> multibinder = Multibinder.newSetBinder(binder(), Thingy.class);
            scanForThingies().forEach(thingy -> multibinder.addBinding().toInstance(thingy));
        }
    }

    static class ThingyModule1 extends ThingyModule {
        public ThingyModule1() { super(Thingies1.class); }
        static class Thingies1{
            static final Thingy<Boolean> BooleanThingy = new Thingy<>(true);
            static final Thingy<Integer> IntThingy = new Thingy<>(123);
        }
    }

    static class ThingyModule2 extends ThingyModule {
        public ThingyModule2() { super(Thingies2.class); }
        static class Thingies2{
            static final Thingy<String> StringThingy = new Thingy<>("hello");
            static final Thingy<Long> LongThingy = new Thingy<>(123L);
        }
    }

    @Test void validateThingyService() {
        ThingyService thingyService = Guice.createInjector(new ThingyModule1(), new ThingyModule2())
                                           .getProvider(ThingyService.class)
                                           .get();
        assertThat(thingyService).isNotNull()
                                 .extracting(ts -> ImmutableList.copyOf(ts.getThingies()))
                                 .asList()
                                 .containsExactlyInAnyOrder(BooleanThingy, IntThingy, StringThingy, LongThingy);
    }
}

How to add Walkmod plugin to eclipse?

copy iconCopydownload iconDownload
<plugin>
  <groupId>org.walkmod.maven.plugins</groupId>
  <artifactId>walkmod-maven-plugin</artifactId>
  <version>2.0.1</version>
  <executions>
    <execution>
      <goals>
        <goal>apply</goal>
      </goals>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>org.apache.ivy</groupId>
      <artifactId>ivy</artifactId>
      <version>2.5.0</version>
    </dependency>
  </dependencies>
</plugin>

Guice load properties from System Properties

copy iconCopydownload iconDownload
@Override protected void configure() {
  Names.bindProperties(binder(), System.getProperties());
}

Runtime value injection in Dagger vs. Guice

copy iconCopydownload iconDownload
@AssistedFactory
public interface InterfaceXFactory{

  ClassX getClassX(
      @Assisted("a") String a,
      @Assisted("b") Integer b);

}
  @AssistedInject
  ClassX(
      final @Assisted("a") String a,
      final @Assisted("b") Integer b) {
    /*...*/
  }
@AssistedFactory
public interface InterfaceXFactory{

  ClassX getClassX(
      @Assisted("a") String a,
      @Assisted("b") Integer b);

}
  @AssistedInject
  ClassX(
      final @Assisted("a") String a,
      final @Assisted("b") Integer b) {
    /*...*/
  }

See all related Code Snippets

Community Discussions

Trending Discussions on guice
  • Create MessageDigest with Guice
  • Spring Boot Logging to a File
  • Java : io.protostuff.compiler.parser.ParserException: Can not load proto
  • OWL API NoSuchMethodError in saveOntology() call
  • Gerrit fails to start the service
  • AroundInvoke: Curious name?
  • Guice generic type injection
  • How to Manage JNDI Context In JUnit Tests?
  • Save HAR file without browsermodproxy
  • Wire collection of objects dynamically in Guice
Trending Discussions on guice

QUESTION

Create MessageDigest with Guice

Asked 2022-Mar-25 at 18:00

I'm trying to find a way to initialize MessageDigest with Guice. Currently I have this:

public class MyClass {

    MessageDigest md;
    
    public MyClass() {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
....
}

I'm trying to see if it can written as:

@Inject
MessageDigest md;

But how do I make Guice call MessageDigest.getInstance("MD5") ?

ANSWER

Answered 2022-Mar-25 at 18:00

Edit

I did not know MessageDigest is a single use class. You showed an injection of that class, which by definition cannot provide multiple instances. So the question is flawed.

You must fix the problem by binding a factory function that creates an MD rather than the MD itself. E.g. a Supplier:

final MessageDigestModule extends AbstractModule {
  @Provide
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
}

Then when creating the injector, install new MessageDigestModule(). You will use @Inject Supplier<MessageDigest> md5DigestSupplier;. At the places where you need one, you'll say md5DigestSupplier.get().

If you'll need more than one kind of MessageDigest, then you should declare annotations and use them to separate the bindings.

@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Md5 {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface Sha256 {}

and then

final MessageDigestModule extends AbstractModule {
  @Provide
  @Md5
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("MD5");
  }
  @Provide
  @Sha256
  Supplier<MessageDigest> provideMd5Digest() {
    return () -> MessageDigest.getInstance("SHA-256");
  }
}

And then finally:

@Inject
@Sha256
Supplier<MessageDigest> sha128DigestSupplier;

Source https://stackoverflow.com/questions/71611712

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install guice

You can download it from GitHub, Maven.
You can use guice like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the guice component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Share this Page

share link
Consider Popular Java Libraries
Try Top Libraries by mycila
Compare Java Libraries with Highest Support
Compare Java Libraries with Highest Quality
Compare Java Libraries with Highest Security
Compare Java Libraries with Permissive License
Compare Java Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.