Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.dateprop;
- import javax.inject.Inject;
- import javax.inject.Named;
- import com.google.inject.*;
- import com.google.inject.matcher.*;
- import com.google.inject.name.*;
- import com.google.inject.spi.*;
- import java.text.*;
- import java.util.*;
- import org.junit.*;
- import static org.junit.Assert.*;
- public class DatePropTest {
- /** The name of the property we want to bind as a constant Date. */
- static final String DATE_PROP_KEY = "date.prop.key";
- @Test public void writeDateAndBindConstant() throws ParseException {
- // The DateFormat we will use for converting Dates to and from strings:
- final DateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
- // Matches java.util.Date only:
- final Matcher<TypeLiteral<?>> dateMatcher = new AbstractMatcher<TypeLiteral<?>>() {
- public boolean matches(TypeLiteral<?> type) {
- return type.getRawType().equals(Date.class);
- }
- };
- // Parses strings as dates using the given DateFormat:
- final TypeConverter dateConverter = new TypeConverter() {
- public Object convert(String stringValue, TypeLiteral<?> toType) {
- try {
- return fmt.parse(stringValue);
- } catch (ParseException ex) {
- throw new ProvisionException("can't parse date", ex);
- }
- }
- };
- // Create our test date.
- final Date date = fmt.parse("03-11-2012 13:05:23");
- // Store it in a Properties as a string using the given DateFormat.
- final Properties props = new Properties();
- props.setProperty(DATE_PROP_KEY, fmt.format(date));
- // Bind the properties using the date converter on date constants,
- // and inject an object that uses the named constant date.
- Dated dated = Guice.createInjector(new AbstractModule() {
- protected void configure() {
- Names.bindProperties(binder(), props);
- convertToTypes(dateMatcher, dateConverter);
- }
- }).getInstance(Dated.class);
- // Assert that the injected date constant is the same as the
- // one we put in the properties.
- assertEquals(date, dated.date);
- }
- public static class Dated {
- @Inject Dated(@Named(DATE_PROP_KEY) Date date) {
- this.date = date;
- }
- final Date date;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement