Example usage for javax.naming InitialContext rebind

List of usage examples for javax.naming InitialContext rebind

Introduction

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

Prototype

public void rebind(Name name, Object obj) throws NamingException 

Source Link

Usage

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

public void contextInitialized(ServletContextEvent evt) {
    boolean useDatasource = Boolean.valueOf(evt.getServletContext().getInitParameter("useDatasource"))
            .booleanValue();//from   w  w  w .  j a  va  2s.  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.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./*from   ww  w  . j  a v a  2 s.  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.
 * //from  ww  w.ja v  a2 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.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
 *///from   w w  w  . ja  va 2  s  .  com
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.JemTasklet.java

/**
 * Is called by SpringBatch framework to execute business logic.<br>
 * Prepares datasets (and the files and resources) which could be used from
 * implementation of this class.<br>
 * Loads JNDI context so all resources could be used by their name, defined
 * in JCL.//www.  j av a  2  s  .c o  m
 * 
 * @param stepContribution step contribution, passed by SpringBatch core
 * @param chunkContext chunk context, passed by SpringBatch core
 * @return always the status returned by abstract method
 *         <code>executeByJem</code>
 * @throws SpringBatchException if a error occurs
 */
@Override
public final RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext)
        throws SpringBatchException {
    LogAppl.getInstance();

    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;
    boolean isAbended = false;

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

    RepeatStatus status = null;

    // extract stepContext because the step name is necessary
    StepContext stepContext = chunkContext.getStepContext();

    List<DataDescriptionImpl> dataDescriptionImplList = ImplementationsContainer.getInstance()
            .getDataDescriptionsByItem(stepContext.getStepName());

    // new initial context for JNDI
    InitialContext ic = null;

    try {
        ic = ContextUtils.getContext();
        // 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 = getReference(resourcer, res, source, dataDescriptionImplList);

            // 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);
        }

        // check if I have resources which must be locked
        if (!dataDescriptionImplList.isEmpty()) {

            // binds all data description impl to JNDI context
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {

                // create reference for JNDI access
                Reference reference = new DataStreamReference();

                // load GDG information, solving the real name of relative
                // position
                GDGManager.load(ddImpl);
                // serialize data description object in XML format
                XStream xstream = new XStream();
                String xml = xstream.toXML(ddImpl);
                // add string xml reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));

                LogAppl.getInstance().emit(SpringBatchMessage.JEMS023I, ddImpl);
                // bind resource using data description name
                ic.rebind(ddImpl.getName(), reference);
            }
        }
        // execute business logic
        // executes the java class defined in JCL
        // setting the boolean to TRUE
        SetFields.applyByAnnotation(this);
        isExecutionStarted = true;
        batchSM.setInternalAction(false);
        status = this.run(stepContribution, chunkContext);
    } catch (NamingException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS043E, e);
    } catch (RemoteException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } catch (IOException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS044E, e, e.getMessage());
    } catch (Exception e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } finally {
        batchSM.setInternalAction(true);
        if (!dataDescriptionImplList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {
                try {
                    // commit the GDG index in the root
                    // if an exception, write on standard output of job
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);

                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, e.getMessage());
                    if (exceptions.length() == 0) {
                        exceptions.append(e.getMessage());
                    } else {
                        exceptions.append(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(SpringBatchMessage.JEMS047E, e.getMessage());
                }
                if (exceptions.length() > 0 && !isAbended) {
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E,
                            StringUtils.center("ATTENTION", 40, "-"));
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, exceptions.toString());
                }

            }
        }
        for (DataSource source : dataSourceList) {
            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(SpringBatchMessage.JEMS047E, e.getMessage());
                }
            }
        }
        batchSM.setInternalAction(false);
    }
    return status;
}

From source file:org.settings4j.connector.JNDIConnector.java

/**
 * @param key the JNDI-Key (will NOT be normalized).
 * @param value the JNDI-Value./*w  ww .j a  v  a2  s  .  c  o  m*/
 * @return Constants.SETTING_NOT_POSSIBLE if the JNDI Context ist readonly.
 */
public int rebindToContext(final String key, final Object value) {
    // don't do a check, but use the result if a check was done.
    if (BooleanUtils.isFalse(this.isJNDIAvailable)) {
        // only if isJNDIAvailable() was called an evaluated to false.
        return Constants.SETTING_NOT_POSSIBLE;
    }

    LOG.debug("Try to rebind Key '{}' with value: {}", key, value);

    InitialContext ctx = null;
    int result = Constants.SETTING_NOT_POSSIBLE;
    try {
        ctx = getJNDIContext();
        createParentContext(ctx, key);
        ctx.rebind(key, value);
        result = Constants.SETTING_SUCCESS;
    } catch (final NoInitialContextException e) {
        logInfoButExceptionDebug(String.format("Maybe no JNDI-Context available. %s", e.getMessage()), e);
    } catch (final NamingException e) {
        // the JNDI-Context from TOMCAT is readonly
        // if you try to write it, The following Exception will be thrown:
        // javax.naming.NamingException: Context is read only
        logInfoButExceptionDebug(String.format("cannot bind key: '%s'. %s", key, e.getMessage()), e);
    } finally {
        closeQuietly(ctx);
    }
    return result;
}

From source file:org.wso2.carbon.appfactory.ext.datasource.ApplicationAwareDataSourceRepository.java

private void registerJNDI(DataSourceMetaInfo dsmInfo, Object dsObject, String applicationID)
        throws DataSourceException {
    String initialApplicationName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getApplicationName();
    try {//from   www .java2 s  . c om
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.getTenantId());
        /*  Have to add dummy version to comply with AF app naming rule */
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setApplicationName(applicationID + AF_DUMMY_VERSION);
        JNDIConfig jndiConfig = dsmInfo.getJndiConfig();
        if (jndiConfig == null) {
            return;
        }
        InitialContext context;
        try {
            context = new InitialContext(jndiConfig.extractHashtableEnv());
        } catch (NamingException e) {
            throw new DataSourceException("Error creating JNDI initial context: " + e.getMessage(), e);
        }
        this.checkAndCreateJNDISubContexts(context, jndiConfig.getName());

        try {
            context.rebind(jndiConfig.getName(), dsObject);
        } catch (NamingException e) {
            throw new DataSourceException(
                    "Error in binding to JNDI with name '" + jndiConfig.getName() + "' - " + e.getMessage(), e);
        }
    } finally {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setApplicationName(initialApplicationName);
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:org.wso2.carbon.datasource.core.DataSourceRepository.java

private void registerJNDI(DataSourceMetaInfo dsmInfo, Object dsObject) throws DataSourceException {
    try {//from  ww  w.j a va2  s  .c  o  m
        /*PrivilegedCarbonContext.startTenantFlow();
           PrivilegedCarbonContext.getCurrentContext().setTenantId(this.getTenantId());*/
        JNDIConfig jndiConfig = dsmInfo.getJndiConfig();
        if (jndiConfig == null) {
            return;
        }
        InitialContext context;
        try {
            context = new InitialContext(jndiConfig.extractHashtableEnv());
        } catch (NamingException e) {
            throw new DataSourceException("Error creating JNDI initial context: " + e.getMessage(), e);
        }
        this.checkAndCreateJNDISubContexts(context, jndiConfig.getName());

        try {
            context.rebind(jndiConfig.getName(), dsObject);
        } catch (NamingException e) {
            throw new DataSourceException(
                    "Error in binding to JNDI with name '" + jndiConfig.getName() + "' - " + e.getMessage(), e);
        }
    } finally {
        /*PrivilegedCarbonContext.endTenantFlow();*/
    }
}

From source file:org.wso2.carbon.ndatasource.core.DataSourceRepository.java

private void registerJNDI(DataSourceMetaInfo dsmInfo, Object dsObject) throws DataSourceException {
    try {//from   w  ww . j  a va  2  s.c o m
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.getTenantId());
        JNDIConfig jndiConfig = dsmInfo.getJndiConfig();
        if (jndiConfig == null) {
            return;
        }
        InitialContext context;
        try {
            context = new InitialContext(jndiConfig.extractHashtableEnv());
        } catch (NamingException e) {
            throw new DataSourceException("Error creating JNDI initial context: " + e.getMessage(), e);
        }
        this.checkAndCreateJNDISubContexts(context, jndiConfig.getName());

        try {
            context.rebind(jndiConfig.getName(), dsObject);
        } catch (NamingException e) {
            throw new DataSourceException(
                    "Error in binding to JNDI with name '" + jndiConfig.getName() + "' - " + e.getMessage(), e);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}