Example usage for javax.naming StringRefAddr StringRefAddr

List of usage examples for javax.naming StringRefAddr StringRefAddr

Introduction

In this page you can find the example usage for javax.naming StringRefAddr StringRefAddr.

Prototype

public StringRefAddr(String addrType, String addr) 

Source Link

Document

Constructs a new instance of StringRefAddr using its address type and contents.

Usage

From source file:org.exoplatform.services.jcr.impl.storage.JDBCWDCTest.java

@Override
protected void setUp() throws Exception {

    RepositoryEntry repositoryEntry = new RepositoryEntry();
    config = new WorkspaceEntry();
    config.setName("test");
    ContainerEntry containerEntry = new ContainerEntry();
    List params = new ArrayList();
    params.add(new SimpleParameterEntry("sourceName", sourceName));
    params.add(new SimpleParameterEntry("db-structure-type", "multi"));
    containerEntry.setParameters(params);
    config.setContainer(containerEntry);

    // Construct BasicDataSource reference
    Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
            null);/*from   w  ww.j  a  v a  2s.c  o m*/

    // Reference ref = new Reference("org.hsqldb.jdbc.jdbcDataSource",
    // "org.hsqldb.jdbc.jdbcDataSourceFactory", null);

    ref.add(new StringRefAddr("driverClassName", "org.hsqldb.jdbcDriver"));

    ref.add(new StringRefAddr("url", "jdbc:hsqldb:file:target/data/test"));
    // ref.add(new StringRefAddr("url", "jdbc:hsqldb:mem:aname"));

    ref.add(new StringRefAddr("username", "sa"));
    ref.add(new StringRefAddr("password", ""));

    FileCleanerHolder cleanerHolder = new FileCleanerHolder();

    container = new JDBCWorkspaceDataContainer(config, repositoryEntry, null,
            new StandaloneStoragePluginProvider(config, cleanerHolder), null, cleanerHolder);

    Properties logProps = new Properties();
    logProps.put("org.apache.commons.logging.simplelog.defaultlog", "debug");

    new LogConfigurationInitializer("org.exoplatform.services.log.impl.BufferedSimpleLog",
            "org.exoplatform.services.log.impl.SimpleLogConfigurator", logProps);

}

From source file:org.jahia.services.content.JCRStoreProvider.java

protected Repository getRepositoryByRMI() {
    Repository instance = null;// w  ww  .ja va 2s.co  m
    try {
        Class<? extends ObjectFactory> factoryClass = Class.forName(factory).asSubclass(ObjectFactory.class);
        ObjectFactory factory = (ObjectFactory) factoryClass.newInstance();
        instance = (Repository) factory.getObjectInstance(
                new Reference(Repository.class.getName(), new StringRefAddr("url", url)), null, null, null);
        logger.info("Repository {} acquired via RMI", getKey());
    } catch (Exception e) {
        logger.error("Cannot get by RMI", e);
    }
    return instance;
}

From source file:org.jresearch.gossip.listeners.ContextListener.java

public void contextInitialized(ServletContextEvent evt) {
    boolean useDatasource = Boolean.valueOf(evt.getServletContext().getInitParameter("useDatasource"))
            .booleanValue();// w w w .  j a  va2s  . c  o  m
    String datasourceName = evt.getServletContext().getInitParameter("datasourceName");

    InitialContext ic;
    try {
        ic = new InitialContext();
        if (useDatasource) {
            if (datasourceName == null)
                throw new RuntimeException(
                        "Using datasource is enabled but datasourceName parameter is not specified.");

            DataSource dataSource = (DataSource) PortableRemoteObject.narrow(ic.lookup(datasourceName),
                    javax.sql.DataSource.class);
            ic.rebind("jgossip_db", dataSource);

        } else {
            Properties dbconf = new Properties();
            dbconf.load(evt.getServletContext()
                    .getResourceAsStream("/WEB-INF/classes/org/jresearch/gossip/resources/db.properties"));
            // Construct BasicDataSource reference
            Reference ref = new Reference("javax.sql.DataSource",
                    "org.apache.commons.dbcp.BasicDataSourceFactory", null);
            ref.add(new StringRefAddr("driverClassName", dbconf.getProperty("driverClassName")));
            ref.add(new StringRefAddr("url", dbconf.getProperty("url")));
            ref.add(new StringRefAddr("password", dbconf.getProperty("password")));
            ref.add(new StringRefAddr("username", dbconf.getProperty("username")));
            ref.add(new StringRefAddr("maxActive", dbconf.getProperty("maxActive")));
            ref.add(new StringRefAddr("maxWait", dbconf.getProperty("maxWait")));
            ref.add(new StringRefAddr("initialSize", dbconf.getProperty("initialSize")));
            ref.add(new StringRefAddr("defaultAutoCommit", dbconf.getProperty("defaultAutoCommit")));
            ref.add(new StringRefAddr("defaultReadOnly", dbconf.getProperty("defaultReadOnly")));
            ref.add(new StringRefAddr("poolPreparedStatements", dbconf.getProperty("poolPreparedStatements")));
            ref.add(new StringRefAddr("maxOpenPreparedStatements",
                    dbconf.getProperty("maxOpenPreparedStatements")));

            ic.rebind("jgossip_db", ref);
        }

    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.runtime.datasource.DataSourceDescriptor.java

public void bindSelf(Context naming) throws NamingException {
    if (xaDataSource != null) {
        String xaName = DataSourceHelper.relativize(getName() + "-xa");
        poolReference = new Reference(XADataSource.class.getName(), PoolFactory.class.getName(), null);
        poolReference.add(new StringRefAddr("dataSourceJNDI", xaName));
        xaReference = new Reference(Framework.expandVars(xaDataSource),
                GenericNamingResourcesFactory.class.getName(), null);
        for (Entry<String, String> e : properties.entrySet()) {
            String key = e.getKey();
            String value = Framework.expandVars(e.getValue());
            StringRefAddr addr = new StringRefAddr(key, value);
            xaReference.add(addr);/*from  w ww  .  ja  va  2s.c o m*/
        }
        naming.bind(DataSourceHelper.getDataSourceJNDIName(xaName), xaReference);
    } else if (dataSource != null) {
        poolReference = new Reference(DataSource.class.getName(), PoolFactory.class.getName(), null);
        final String name = Framework.expandVars(dataSource);
        poolReference.add(new StringRefAddr("dataSourceJNDI", DataSourceHelper.getDataSourceJNDIName(name)));
    } else if (driverClasssName != null) {
        poolReference = new Reference(DataSource.class.getName(), PoolFactory.class.getName(), null);
    } else {
        throw new RuntimeException(
                "Datasource " + getName() + " should have xaDataSource or driverClassName attribute");
    }

    for (Entry<String, String> e : properties.entrySet()) {
        String key = e.getKey();
        String value = Framework.expandVars(e.getValue());
        StringRefAddr addr = new StringRefAddr(key, value);
        poolReference.add(addr);
    }

    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);
        String attrName = attr.getNodeName();
        String value = Framework.expandVars(attr.getNodeValue());
        StringRefAddr addr = new StringRefAddr(attrName, value);
        poolReference.add(addr);
    }

    LogFactory.getLog(DataSourceDescriptor.class).info("binding " + getName());
    String jndiName = DataSourceHelper.getDataSourceJNDIName(getName());
    naming.bind(jndiName, poolReference);
    // create pooled
    naming.lookup(jndiName);
}

From source file:org.nuxeo.runtime.datasource.DataSourceFactory.java

@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> env) throws Exception {
    Reference ref = (Reference) obj;
    if (!DataSource.class.getName().equals(ref.getClassName())) {
        return null;
    }//from  ww w .j  a  v a 2 s.co m

    TransactionManager transactionManager;
    try {
        transactionManager = TransactionHelper.lookupTransactionManager();
    } catch (NamingException e) {
        transactionManager = null;
    }

    boolean xa = ref.get(BasicManagedDataSourceFactory.PROP_XADATASOURCE) != null;
    log.info(String.format("Creating pooled %s datasource: %s/%s", xa ? "XA" : "non-XA",
            nameCtx.getNameInNamespace(), name));

    if (xa && transactionManager == null) {
        throw new RuntimeException(
                "Cannot configure XA datasource " + name + " without an available transaction manager");
    }

    // extract properties from Reference
    Map<String, String> properties = new HashMap<String, String>();
    Enumeration<RefAddr> refAddrs = ref.getAll();
    while (refAddrs.hasMoreElements()) {
        RefAddr ra = refAddrs.nextElement();
        String key = ra.getType();
        String value = ra.getContent().toString();
        if (key.startsWith(DataSourceDescriptor.PROP_PREFIX)) {
            key = key.substring(DataSourceDescriptor.PROP_PREFIX.length());
            properties.put(key, value);
        }
    }

    DataSource ds;
    if (!xa) {
        // fetch url from properties
        for (Entry<String, String> en : properties.entrySet()) {
            // often misspelled, thus the ignore case
            if (URL_LOWER.equalsIgnoreCase(en.getKey())) {
                ref.add(new StringRefAddr(URL_LOWER, en.getValue()));
            }
        }
        ObjectFactory factory = new BasicDataSourceFactory();
        ds = (DataSource) factory.getObjectInstance(ref, name, nameCtx, env);
        BasicDataSource bds = (BasicDataSource) ds;

        // set properties
        for (Entry<String, String> en : properties.entrySet()) {
            String key = en.getKey();
            if (URL_LOWER.equalsIgnoreCase(key)) {
                continue;
            }
            bds.addConnectionProperty(key, en.getValue());
        }
    } else {
        ObjectFactory factory = new BasicManagedDataSourceFactory();
        ds = (DataSource) factory.getObjectInstance(obj, name, nameCtx, env);
        if (ds == null) {
            return null;
        }
        BasicManagedDataSource bmds = (BasicManagedDataSource) ds;

        // set transaction manager
        bmds.setTransactionManager(transactionManager);

        // set properties
        XADataSource xaDataSource = bmds.getXaDataSourceInstance();
        if (xaDataSource == null) {
            return null;
        }
        for (Entry<String, String> en : properties.entrySet()) {
            String key = en.getKey();
            // proper JavaBean convention for initial cap
            if (Character.isLowerCase(key.charAt(1))) {
                key = Character.toLowerCase(key.charAt(0)) + key.substring(1);
            }
            String value = en.getValue();
            boolean ok = false;
            try {
                BeanUtils.setProperty(xaDataSource, key, value);
                ok = true;
            } catch (Exception e) {
                if (URL_LOWER.equals(key)) {
                    // commonly misspelled
                    try {
                        BeanUtils.setProperty(xaDataSource, URL_UPPER, value);
                        ok = true;
                    } catch (Exception ee) {
                        // log error below
                    }
                }
            }
            if (!ok) {
                log.error(String.format("Cannot set %s = %s on %s", key, value,
                        xaDataSource.getClass().getName()));
            }
        }
    }
    return ds;
}

From source file:org.pepstock.jem.ant.tasks.StepJava.java

/**
 * Prepares the files required by ANT file using the data description, locks
 * them, and prepares the right file name for GDG. Afterwards calls the java
 * main class defined in the task./* ww w.  java 2s .c o  m*/
 * 
 * @throws BuildException occurs if an error occurs
 */
@Override
public void execute() throws BuildException {
    int returnCode = Result.SUCCESS;
    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;

    AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);

    // object serializer and deserializer into XML
    XStream xstream = new XStream();

    List<DataDescriptionImpl> ddList = null;
    InitialContext ic = null;
    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(this);
        // new intial context for JNDI
        ic = ContextUtils.getContext();

        // LOADS DataPaths Container
        Reference referencePaths = new DataPathsReference();
        // loads dataPaths on static name
        String xmlPaths = xstream.toXML(DataPathsContainer.getInstance());
        // adds the String into a data stream reference
        referencePaths.add(new StringRefAddr(StringRefAddrKeys.DATAPATHS_KEY, xmlPaths));
        // re-bind the object inside the JNDI context
        ic.rebind(AntKeys.ANT_DATAPATHS_BIND_NAME, referencePaths);

        // scans all datasource passed
        for (DataSource source : sources) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new BuildException(AntMessage.JEMA027E.toMessage().getFormattedMessage());
            } else if (source.getName() == null) {
                // if name is missing, it uses the same string 
                // used to define the resource
                source.setName(source.getResource());
            }

            // gets the RMi object to get resources
            CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
            // lookups by RMI for the database 
            Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
            if (!batchSM.checkResource(res)) {
                throw new BuildException(AntMessage.JEMA028E.toMessage().getFormattedMessage(res.toString()));
            }

            // all properties create all StringRefAddrs necessary  
            Map<String, ResourceProperty> properties = res.getProperties();

            // scans all properteis set by JCL
            for (Property property : source.getProperties()) {
                if (property.isCustom()) {
                    if (res.getCustomProperties() == null) {
                        res.setCustomProperties(new HashMap<String, String>());
                    }
                    if (!res.getCustomProperties().containsKey(property.getName())) {
                        res.getCustomProperties().put(property.getName(), property.getText().toString());
                    } else {
                        throw new BuildException(
                                AntMessage.JEMA028E.toMessage().getFormattedMessage(property.getName(), res));
                    }
                } else {
                    // if a key is defined FINAL, throw an exception
                    for (ResourceProperty resProperty : properties.values()) {
                        if (resProperty.getName().equalsIgnoreCase(property.getName())
                                && !resProperty.isOverride()) {
                            throw new BuildException(AntMessage.JEMA028E.toMessage()
                                    .getFormattedMessage(property.getName(), res));
                        }
                    }
                    ResourcePropertiesUtil.addProperty(res, property.getName(), property.getText().toString());
                }
            }

            // creates a JNDI reference
            Reference ref = getReference(resourcer, res, source, ddList);

            // loads all properties into RefAddr
            for (ResourceProperty property : properties.values()) {
                ref.add(new StringRefAddr(property.getName(), replaceProperties(property.getValue())));
            }

            // loads custom properties in a string format
            if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
                // loads all entries and substitute variables
                for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                    String value = replaceProperties(entry.getValue());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with [name]
            log(AntMessage.JEMA035I.toMessage().getFormattedMessage(res));
            ic.rebind(source.getName(), ref);
        }

        // if list of data description is empty, go to execute java main
        // class
        if (!ddList.isEmpty()) {

            // after locking, checks for GDG
            // is sure here the root (is a properties file) of GDG is locked
            // (doesn't matter if in READ or WRITE)
            // so can read a consistent data from root and gets the right
            // generation
            // starting from relative position
            for (DataDescriptionImpl ddImpl : ddList) {
                // creates a reference, accessible by name. Is data stream
                // reference because
                // contains a stream of data which represents a object
                Reference reference = new DataStreamReference();
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);

                log(AntMessage.JEMA034I.toMessage().getFormattedMessage(ddImpl));
                // serialize data descriptor object into xml string
                // in this way is easier pass to object across different
                // classloader, by JNDI.
                // This xml, by reference, will be used by DataStreamFactory
                // when
                // java main class requests a resource by a JNDI call
                String xml = xstream.toXML(ddImpl);
                // adds the String into a data stream reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));
                // re-bind the object inside the JNDI context
                ic.rebind(ddImpl.getName(), reference);
            }

        }
        // sets fork to false
        // in this way java main class runs inside the same process
        // this is mandatory if wants to JNDI without any network
        // connection, like RMI
        super.setFork(false);

        // changes the main class to apply the annotations of JEM
        setCustomMainClass();

        batchSM.setInternalAction(false);
        // executes the java main class defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        // tried to set fields where
        // annotations are used
        super.execute();
    } catch (BuildException e) {
        returnCode = Result.ERROR;
        throw e;
    } catch (RemoteException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (IOException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (NamingException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } finally {
        batchSM.setInternalAction(true);
        String rcObject = System.getProperty(RESULT_KEY);
        if (rcObject != null) {
            returnCode = Parser.parseInt(rcObject, Result.SUCCESS);
        }
        ReturnCodesContainer.getInstance().setReturnCode(getProject(), this, returnCode);
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : ddList) {
                try {
                    // consolidates the GDG situation
                    // changing the root (is a properties file)
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    if (exceptions.length() == 0) {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA037E.toMessage().getFormattedMessage(e.getMessage()));
                }
            }
            for (DataSource source : sources) {
                if (source.getName() != null) {
                    // unbinds all resources
                    try {
                        ic.unbind(source.getName());
                    } catch (NamingException e) {
                        // ignore
                        LogAppl.getInstance().ignore(e.getMessage(), e);
                        log(AntMessage.JEMA037E.toMessage().getFormattedMessage(e.getMessage()));
                    }
                }
            }
            // checks if has exception using the stringbuffer
            // used to collect exception string. 
            // Stringbuffer is not empty, throws an exception
            if (exceptions.length() > 0) {
                log(StringUtils.center("ATTENTION", 40, "-"));
                log(exceptions.toString());
            }
            batchSM.setInternalAction(false);
        }
    }
}

From source file:org.pepstock.jem.jbpm.tasks.JemWorkItemHandler.java

/**
 * Executes the work item, creating all JEM features and therefore reachable by JNDI.
 * // ww w.  j a  v  a 2  s . c om
 * @param task current JBPM task
 * @param item sub workitem to execute
 * @param parms list of parameters, created by JBPM for this work item
 * @return return code of work item execution
 * @throws JemException if any error occurs
 */
private int execute(Task task, JemWorkItem item, Map<String, Object> parms) throws JemException {
    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;

    JBpmBatchSecurityManager batchSM = (JBpmBatchSecurityManager) System.getSecurityManager();

    // object serializer and deserializer into XML
    XStream xstream = new XStream();

    List<DataDescriptionImpl> ddList = null;
    InitialContext ic = null;

    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(task);
        // new intial context for JNDI
        ic = ContextUtils.getContext();

        // LOADS DataPaths Container
        Reference referencePaths = new DataPathsReference();
        // loads dataPaths on static name
        String xmlPaths = xstream.toXML(DataPathsContainer.getInstance());
        // adds the String into a data stream reference
        referencePaths.add(new StringRefAddr(StringRefAddrKeys.DATAPATHS_KEY, xmlPaths));
        // re-bind the object inside the JNDI context
        ic.rebind(JBpmKeys.JBPM_DATAPATHS_BIND_NAME, referencePaths);

        // scans all datasource passed
        for (DataSource source : task.getDataSources()) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new MessageException(JBpmMessage.JEMM027E);
            } else if (source.getName() == null) {
                // if name is missing, it uses the same string 
                // used to define the resource
                source.setName(source.getResource());
            }

            // gets the RMi object to get resources
            CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
            // lookups by RMI for the database 
            Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
            if (!batchSM.checkResource(res)) {
                throw new MessageException(JBpmMessage.JEMM028E, res.toString());
            }

            // all properties create all StringRefAddrs necessary  
            Map<String, ResourceProperty> properties = res.getProperties();
            // scans all properteis set by JCL
            for (Property property : source.getProperties()) {
                if (property.isCustom()) {
                    if (res.getCustomProperties() == null) {
                        res.setCustomProperties(new HashMap<String, String>());
                    }
                    if (!res.getCustomProperties().containsKey(property.getName())) {
                        res.getCustomProperties().put(property.getName(), property.getText().toString());
                    } else {
                        throw new MessageException(JBpmMessage.JEMM028E, property.getName(), res);
                    }
                } else {
                    // if a key is defined FINAL, throw an exception
                    for (ResourceProperty resProperty : properties.values()) {
                        if (resProperty.getName().equalsIgnoreCase(property.getName())
                                && !resProperty.isOverride()) {
                            throw new MessageException(JBpmMessage.JEMM028E, property.getName(), res);
                        }
                    }
                    ResourcePropertiesUtil.addProperty(res, property.getName(), property.getText().toString());
                }
            }

            // creates a JNDI reference
            Reference ref = getReference(resourcer, res, source, ddList);

            // loads all properties into RefAddr
            for (ResourceProperty property : properties.values()) {
                ref.add(new StringRefAddr(property.getName(),
                        replaceProperties(property.getValue(), JobsProperties.getInstance().getProperties())));
            }

            // loads custom properties in a string format
            if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
                // loads all entries and substitute variables
                for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                    String value = replaceProperties(entry.getValue(),
                            JobsProperties.getInstance().getProperties());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with format [type]/[name]
            LogAppl.getInstance().emit(JBpmMessage.JEMM035I, res);
            ic.rebind(source.getName(), ref);
        }

        // if list of data description is empty, go to execute java main
        // class
        if (!ddList.isEmpty()) {

            // after locking, checks for GDG
            // is sure here the root (is a properties file) of GDG is locked
            // (doesn't matter if in READ or WRITE)
            // so can read a consistent data from root and gets the right
            // generation
            // starting from relative position
            for (DataDescriptionImpl ddImpl : ddList) {
                // creates a reference, accessible by name. Is data stream
                // reference because
                // contains a stream of data which represents a object
                Reference reference = new DataStreamReference();
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);

                LogAppl.getInstance().emit(JBpmMessage.JEMM034I, ddImpl);
                // serialize data descriptor object into xml string
                // in this way is easier pass to object across different
                // classloader, by JNDI.
                // This xml, by reference, will be used by DataStreamFactory
                // when
                // java main class requests a resource by a JNDI call
                String xml = xstream.toXML(ddImpl);
                // adds the String into a data stream reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));
                // re-bind the object inside the JNDI context
                ic.rebind(ddImpl.getName(), reference);
            }

        }
        batchSM.setInternalAction(false);
        // executes the java main class defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        return item.execute(parms);
    } catch (RemoteException e) {
        throw new JemException(e);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new JemException(e);
    } finally {
        batchSM.setInternalAction(true);
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : ddList) {
                try {
                    // consolidates the GDG situation
                    // changing the root (is a properties file)
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(JBpmMessage.JEMM036E, e.getMessage());
                    if (exceptions.length() == 0) {
                        exceptions.append(JBpmMessage.JEMM036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(JBpmMessage.JEMM036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(JBpmMessage.JEMM037E, e.getMessage());
                }
            }
            // checks if has exception using the stringbuffer
            // used to collect exception string. 
            // Stringbuffer is not empty, throws an exception
            if (exceptions.length() > 0) {
                LogAppl.getInstance().emit(JBpmMessage.JEMM055E, exceptions.toString());
            }
        }
        for (DataSource source : task.getDataSources()) {
            if (source.getName() != null) {
                // unbinds all resources
                try {
                    ic.unbind(source.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(JBpmMessage.JEMM037E, e.getMessage());
                }
            }
        }
        batchSM.setInternalAction(false);
    }
}

From source file:org.pepstock.jem.node.resources.impl.jdbc.JdbcFactory.java

@Override
public Object getObjectInstance(Object object, Name name, Context ctx,
        @SuppressWarnings("rawtypes") Hashtable env) throws Exception {
    // reads the reference
    Reference ref = (Reference) object;

    // get the resource custom properties
    // if exits, adds to CONNECTION properties,
    // which is usd by Apache DB pool to set connection properties
    RefAddr ra = ref.get(CommonKeys.RESOURCE_CUSTOM_PROPERTIES);
    if (ra != null) {
        String propertyValue = ra.getContent().toString();
        ref.add(new StringRefAddr(JdbcResourceKeys.PROP_CONNECTIONPROPERTIES, propertyValue));
    }/*from w  w w .  j  av  a  2 s . c  o m*/
    // DBPool want USERNAME instead of USERID
    RefAddr raUser = ref.get(CommonKeys.USERID);
    if (raUser != null) {
        String propertyValue = raUser.getContent().toString();
        ref.add(new StringRefAddr(JdbcResourceKeys.PROP_USERNAME, propertyValue));
    }
    // call super
    return super.getObjectInstance(ref, name, ctx, env);
}

From source file:org.pepstock.jem.springbatch.tasks.ChunkDataSourcesManager.java

/**
 * Loads a JNDI context with all resources defined for chunk and usable inside of ItemReader, ItemProcessor and ItemWriter.
 * @param ic JNDI context, already created
 * @param dataSourceList list of data sources definitions
 * @throws SpringBatchException if any excetpion occurs
 * @throws NamingException if any excetpion occurs
 * @throws UnknownHostException if any excetpion occurs
 * @throws RemoteException if any excetpion occurs
 *//*w  w w.j  ava  2  s  .  c  om*/
static void loadJNDIContext(InitialContext ic, List<DataSource> dataSourceList)
        throws SpringBatchException, NamingException, RemoteException, UnknownHostException {
    SpringBatchSecurityManager batchSM = (SpringBatchSecurityManager) System.getSecurityManager();
    // scans all datasource passed
    for (DataSource source : dataSourceList) {
        // checks if datasource is well defined
        if (source.getResource() == null) {
            throw new SpringBatchException(SpringBatchMessage.JEMS016E);
        } else if (source.getName() == null) {
            // if name is missing, it uses the same string 
            // used to define the resource
            source.setName(source.getResource());
        }

        // gets the RMi object to get resources
        CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
        // lookups by RMI for the database
        Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
        if (!batchSM.checkResource(res)) {
            throw new SpringBatchException(SpringBatchMessage.JEMS017E, res.toString());
        }

        // all properties create all StringRefAddrs necessary
        Map<String, ResourceProperty> properties = res.getProperties();

        // scans all properteis set by JCL
        for (Property property : source.getProperties()) {
            if (property.isCustom()) {
                if (res.getCustomProperties() == null) {
                    res.setCustomProperties(new HashMap<String, String>());
                }
                if (!res.getCustomProperties().containsKey(property.getName())) {
                    res.getCustomProperties().put(property.getName(), property.getValue());
                } else {
                    throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(), res);
                }
            } else {
                // if a key is defined FINAL, throw an exception
                for (ResourceProperty resProperty : properties.values()) {
                    if (resProperty.getName().equalsIgnoreCase(property.getName())
                            && !resProperty.isOverride()) {
                        throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(), res);
                    }
                }
                ResourcePropertiesUtil.addProperty(res, property.getName(), property.getValue());
            }
        }
        // creates a JNDI reference
        Reference ref = null;
        try {
            ref = resourcer.lookupReference(JobId.VALUE, res.getType());
            if (ref == null) {
                throw new SpringBatchException(SpringBatchMessage.JEMS019E, res.getName(), res.getType());
            }
        } catch (Exception e) {
            throw new SpringBatchException(SpringBatchMessage.JEMS019E, e, res.getName(), res.getType());
        }

        // loads all properties into RefAddr
        for (ResourceProperty property : properties.values()) {
            ref.add(new StringRefAddr(property.getName(), replaceProperties(property.getValue())));
        }

        // loads custom properties in a string format
        if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
            // loads all entries and substitute variables
            for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                String value = replaceProperties(entry.getValue());
                entry.setValue(value);
            }
            // adds to reference
            ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES, res.getCustomPropertiesString()));
        }

        // binds the object with format {type]/[name]
        LogAppl.getInstance().emit(SpringBatchMessage.JEMS024I, res);
        ic.rebind(source.getName(), ref);
    }
}

From source file:org.pepstock.jem.springbatch.tasks.DataSource.java

/**
 * Implements the connection to database, using the JNDI reference
 * @return a SQL connection//w  ww .j  a  v a 2 s. co  m
 * @throws SQLException if any error occurs
 */
private Connection getConnectionImpl() throws SQLException {
    try {
        SpringBatchSecurityManager batchSM = (SpringBatchSecurityManager) System.getSecurityManager();
        // checks if datasource is well defined
        if (getResource() == null) {
            throw new SQLException(SpringBatchMessage.JEMS016E.toMessage().getFormattedMessage());
        } else if (getName() == null) {
            // if name is missing, it uses the same string 
            // used to define the resource
            setName(getResource());
        }
        // gets the RMi object to get resources
        CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
        // lookups by RMI for the database 
        Resource res = resourcer.lookup(JobId.VALUE, getResource());
        if (!batchSM.checkResource(res)) {
            throw new SQLException(SpringBatchMessage.JEMS017E.toMessage().getFormattedMessage(res.toString()));
        }
        // all properties create all StringRefAddrs necessary
        Map<String, ResourceProperty> props = res.getProperties();

        // scans all properteis set by JCL
        for (Property property : getProperties()) {
            if (property.isCustom()) {
                if (res.getCustomProperties() == null) {
                    res.setCustomProperties(new HashMap<String, String>());
                }
                if (!res.getCustomProperties().containsKey(property.getName())) {
                    res.getCustomProperties().put(property.getName(), property.getValue());
                } else {
                    throw new SQLException(SpringBatchMessage.JEMS018E.toMessage()
                            .getFormattedMessage(property.getName(), res));
                }
            } else {
                // if a key is defined FINAL, throw an exception
                for (ResourceProperty resProperty : props.values()) {
                    if (resProperty.getName().equalsIgnoreCase(property.getName())
                            && !resProperty.isOverride()) {
                        throw new SQLException(SpringBatchMessage.JEMS018E.toMessage()
                                .getFormattedMessage(property.getName(), res));
                    }
                }
                ResourcePropertiesUtil.addProperty(res, property.getName(), property.getValue());
            }
        }
        // creates a JNDI reference
        Reference ref = getReference(resourcer, res);
        // loads all properties into RefAddr
        for (ResourceProperty property : props.values()) {
            ref.add(new StringRefAddr(property.getName(), replaceProperties(property.getValue())));
        }

        // loads custom properties in a string format
        if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
            // loads all entries and substitute variables
            for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                String value = replaceProperties(entry.getValue());
                entry.setValue(value);
            }
            // adds to reference
            ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES, res.getCustomPropertiesString()));

        }

        // binds the object with format {type]/[name]
        LogAppl.getInstance().emit(SpringBatchMessage.JEMS024I, res);

        JdbcFactory factory = new JdbcFactory();
        javax.sql.DataSource ds = (javax.sql.DataSource) factory.getObjectInstance(ref, null, null, null);
        return ds.getConnection();
    } catch (RemoteException e) {
        throw new SQLException(e.getMessage(), e);
    } catch (UnknownHostException e) {
        throw new SQLException(e.getMessage(), e);
    } catch (Exception e) {
        throw new SQLException(e.getMessage(), e);
    }
}