uima-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Alex Chaphiv <achap...@gmail.com>
Subject Re: Approach to dependency injection in a non-distributed scenario (was: Dependency Injection support?)
Date Wed, 30 Mar 2011 06:14:51 GMT
Hi,

I've been playing with your example, and it seems to break my existing code, so
I came up with this solution that uses ExternalResourceDescriptions and avoids
reflection:

-- start code --

public static void main(String[] args) throws Exception {
    AnotherResourceManager arm = new AnotherResourceManager();
    ExternalResourceDescription erd = arm.register(7);

    AnalysisEngineDescription aed = createPrimitiveDescription(FooAE.class);
    bindExternalResource(aed, FooAE.RES_INJECTED_POJO, erd);

    AnalysisEngine ae = produceAnalysisEngine(aed, arm, null);

    ae.process(ae.newJCas());
}

public final class AnotherResourceManager extends ResourceManager_impl {
    private static final String KEY = "SOME_UNIQUE_KEY";
    private int counter;

    public ExternalResourceDescription register(Object instance) {
        String key = nextUniqueKey();
        ExternalResourceDescription erd = createExternalResourceDescription(key,
            ExternalResourceFromResourceManager.class,
            ExternalResourceFromResourceManager.PARAM_RESOURCE_KEY,
            key);
        mResourceMap.put(key, instance);
        return erd;
    }

    private String nextUniqueKey() {
        return KEY + counter++;
    }

    public static final class ExternalResourceFromResourceManager extends
            Resource_ImplBase implements ExternalResourceLocator {
        public static final String PARAM_RESOURCE_KEY = "RESOURCE_KEY";

        private Object resource;

        @Override
        public Object getResource() {
            return resource;
        }

        @Override
        public boolean initialize(
                ResourceSpecifier aSpecifier,
                Map<String, Object> aAdditionalParams)
                throws ResourceInitializationException {
            if (super.initialize(aSpecifier, aAdditionalParams)
                && aSpecifier instanceof CustomResourceSpecifier) {
                CustomResourceSpecifier crs = (CustomResourceSpecifier) aSpecifier;

                for (Parameter p : crs.getParameters()) {
                    if (p.getName().equals(PARAM_RESOURCE_KEY)) {
                        String key = p.getValue();
                        try {
                            resource = getResourceManager().getResource(key);
                        } catch (ResourceAccessException e) {
                            throw new ResourceInitializationException(e);
                        }
                    }
                }
            }

            return resource != null;
        }
    }
}

-- end code --


Mime
View raw message