persistence.persistence-example.3.5.1.source-code.Main Maven / Gradle / Ivy
import com.distelli.cred.CredPair;
import com.distelli.persistence.Index;
import com.distelli.persistence.PageIterator;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Module;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import static java.nio.charset.StandardCharsets.UTF_8;
public class Main {
/**
* The "BASE" Index.Factory should be decorated with default
* endpoints and credentials to avoid code duplication.
*/
public static class IndexFactoryProvider implements Provider {
@Inject @Named("BASE")
private Index.Factory _baseIndexFactory;
private URI _endpoint;
private CredPair _creds;
public IndexFactoryProvider(URI defaultEndpoint, CredPair defaultCreds) {
_endpoint = defaultEndpoint;
_creds = defaultCreds;
}
@Override
public Index.Factory get() {
return new Index.Factory() {
@Override
public Index.Builder create(Class type) {
return _baseIndexFactory.create(type)
.withTableNameFormat("prefix-%s")
.withEndpoint(_endpoint)
.withCredProvider(() -> _creds);
}
};
}
}
public static void main(String[] args) throws Exception {
URI endpoint = URI.create(System.getenv("ENDPOINT"));
CredPair creds = new CredPair()
.withKeyId(System.getenv("KEY_ID"))
.withSecret(System.getenv("SECRET"));
Guice.createInjector(
(Module)Class.forName("com.distelli.persistence.impl.PersistenceModule")
.newInstance(),
new AbstractModule() {
@Override
protected void configure() {
bind(Index.Factory.class)
.toProvider(new IndexFactoryProvider(endpoint, creds));
}
})
.getInstance(Main.class)
.run(args);
}
@Inject
private ToyShop _toyShop;
public void run(String[] args) throws Exception {
ObjectMapper om = new ObjectMapper();
om.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
if ( 1 == args.length && "--list".equals(args[0]) ) {
for ( PageIterator it : new PageIterator() ) {
for ( ToyShop.Toy toy : _toyShop.getAllToys(it) ) {
om.writeValue(System.out, toy);
System.out.println();
}
}
} else if ( 1 == args.length && "--put".equals(args[0]) ) {
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in, UTF_8));
String line;
while ( null != (line = in.readLine()) ) {
_toyShop.addToy(om.readValue(line, ToyShop.Toy.class));
}
} else if ( 2 == args.length && "--category".equals(args[0]) ) {
ToyShop.Category category = ToyShop.Category.valueOf(args[1]);
for ( PageIterator it : new PageIterator() ) {
for ( ToyShop.Toy toy : _toyShop.getToysByCategory(category, it) ) {
om.writeValue(System.out, toy);
System.out.println();
}
}
} else {
System.err.println("Usage: java Main [--list] [--put] [--category ]");
System.exit(-1);
}
}
}