001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.automation.server.jaxrs;
013
014import java.util.HashSet;
015import java.util.Set;
016
017import javax.ws.rs.ext.MessageBodyReader;
018import javax.ws.rs.ext.MessageBodyWriter;
019
020import org.apache.commons.logging.Log;
021import org.apache.commons.logging.LogFactory;
022import org.nuxeo.ecm.automation.jaxrs.JsonFactoryProvider;
023import org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartFormRequestReader;
024import org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartRequestReader;
025import org.nuxeo.ecm.automation.server.AutomationServer;
026import org.nuxeo.ecm.webengine.app.WebEngineModule;
027import org.nuxeo.runtime.api.Framework;
028
029/**
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032public class AutomationModule extends WebEngineModule {
033
034    protected static final Log log = LogFactory.getLog(AutomationModule.class);
035
036    @Override
037    public Set<Class<?>> getClasses() {
038
039        Set<Class<?>> result = super.getClasses();
040        // need to be stateless since it needs the request member to be
041        // injected
042        result.add(MultiPartRequestReader.class);
043        result.add(MultiPartFormRequestReader.class);
044        return result;
045    }
046
047    protected static Set<Object> setupSingletons() {
048
049        Set<Object> result = new HashSet<Object>();
050
051        AutomationServer as = Framework.getLocalService(AutomationServer.class);
052
053        for (Class<? extends MessageBodyReader<?>> readerKlass : as.getReaders()) {
054            try {
055                result.add(readerKlass.newInstance());
056            } catch (InstantiationException | IllegalAccessException e) {
057                log.error("Unable to instanciate MessageBodyReader : " + readerKlass, e);
058            }
059        }
060
061        for (Class<? extends MessageBodyWriter<?>> writerKlass : as.getWriters()) {
062            try {
063                result.add(writerKlass.newInstance());
064            } catch (InstantiationException | IllegalAccessException e) {
065                log.error("Unable to instanciate MessageBodyWriter : " + writerKlass, e);
066            }
067        }
068
069        result.add(new JsonFactoryProvider());
070        return result;
071    }
072
073    @Override
074    public Set<Object> getSingletons() {
075        return setupSingletons();
076    }
077
078}