Example usage for javax.naming InitialContext unbind

List of usage examples for javax.naming InitialContext unbind

Introduction

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

Prototype

public void unbind(Name name) throws NamingException 

Source Link

Usage

From source file:org.exoplatform.services.naming.InitialContextTest.java

public void testCompositeNameUsing() throws Exception {
    Name name = new CompositeName("java:comp/env/jdbc/jcr");
    Enumeration en = name.getAll();
    while (en.hasMoreElements()) {
        en.nextElement();//from www .  ja  v  a2 s  .  c  om
    }
    InitialContext ctx = new InitialContext();
    ctx.bind(name, "foo");
    assertEquals("foo", ctx.lookup(name));
    try {
        ctx.bind(name, "foo2");
        fail("A NameAlreadyBoundException is expected here");
    } catch (NameAlreadyBoundException e) {
        // expected exception
    }
    assertEquals("foo", ctx.lookup(name));
    assertEquals("foo", ctx.lookup("java:comp/env/jdbc/jcr"));
    ctx.unbind(name);
    try {
        ctx.lookup(name);
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
}

From source file:org.exoplatform.services.naming.InitialContextTest.java

public void testGetContext() throws Exception {
    assertNotNull(System.getProperty(Context.INITIAL_CONTEXT_FACTORY));
    InitialContext ctx = new InitialContext();
    assertNotNull(ctx);//from w  w  w . j  a va 2  s .  c  o  m
    ctx.bind("test", "test");
    assertEquals("test", ctx.lookup("test"));
    try {
        ctx.bind("test", "test2");
        fail("A NameAlreadyBoundException is expected here");
    } catch (NameAlreadyBoundException e) {
        // expected exception
    }
    assertEquals("test", ctx.lookup("test"));
    ctx.rebind("test", "test2");
    assertEquals("test2", ctx.lookup("test"));

    initializer.getInitialContext().bind("test", "test3");
    assertEquals("test3", ctx.lookup("test"));
    ctx.rebind("test", "test4");
    assertEquals("test3", ctx.lookup("test"));
    initializer.getInitialContext().rebind("test", "test5");
    assertEquals("test5", ctx.lookup("test"));
    initializer.getInitialContext().unbind("test");
    try {
        initializer.getInitialContext().lookup("test");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    assertEquals("test4", ctx.lookup("test"));
    ctx.unbind("test");
    try {
        ctx.lookup("test");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    try {
        initializer.getInitialContext().unbind("test2");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    initializer.getInitialContext().bind("foo", "foo");
    assertEquals("foo", ctx.lookup("foo"));
    initializer.getInitialContext().bind("foo2", "foo2");
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().rename("foo", "foo2");
        fail("A NameAlreadyBoundException is expected here");
    } catch (NameAlreadyBoundException e) {
        // expected exception
    }
    assertEquals("foo", ctx.lookup("foo"));
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().rename("foo3", "foo4");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    initializer.getInitialContext().rename("foo", "foo3");
    assertEquals("foo", ctx.lookup("foo3"));
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().lookup("foo");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }

    // check same instance
    initializer.getInitialContext().bind("bla", "bla");
    Object obj1 = initializer.getInitialContext().lookup("bla");
    Object obj2 = initializer.getInitialContext().lookup("bla");
    assertTrue(obj1 == obj2);
}

From source file:org.nuxeo.runtime.binding.ServiceBindings.java

public static void removeAlias(InitialContext context, String aliasName) throws NamingException {
    context.unbind(aliasName);
}

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  w  ww. j a v a2s.  c om
 * 
 * @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 www . j a va 2s  .co  m
 * @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

/**
 * Clears all JDNI defintions/*from  ww  w . j  av  a2 s.  c o  m*/
 * @param context JNDI context to clear
 * @param dataSourceList list of datasources to unbind
 */
static void clearJNDIContext(InitialContext context, List<DataSource> dataSourceList) {
    for (DataSource source : dataSourceList) {
        // unbinds all resources
        try {
            context.unbind(source.getName());
        } catch (NamingException e) {
            // ignore
            LogAppl.getInstance().ignore(e.getMessage(), e);
        }
    }
}

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./*from w ww. java2 s.com*/
 * 
 * @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.wso2.carbon.appfactory.ext.datasource.ApplicationAwareDataSourceRepository.java

private void unregisterJNDI(DataSourceMetaInfo dsmInfo, String applicationID) {
    String initialApplicationName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getApplicationName();
    try {//from  w w w.j  a v  a  2  s. c  o  m
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.getTenantId());
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setApplicationName(applicationID + AF_DUMMY_VERSION);
        JNDIConfig jndiConfig = dsmInfo.getJndiConfig();
        if (jndiConfig == null) {
            return;
        }
        try {
            InitialContext context = new InitialContext(jndiConfig.extractHashtableEnv());
            context.unbind(jndiConfig.getName());
        } catch (NamingException e) {
            log.error("Error in unregistering JNDI 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 unregisterJNDI(DataSourceMetaInfo dsmInfo) {
    try {//from  w ww  . ja  v  a 2s.co  m
        /*PrivilegedCarbonContext.startTenantFlow();
           PrivilegedCarbonContext.getCurrentContext().setTenantId(this.getTenantId());*/
        JNDIConfig jndiConfig = dsmInfo.getJndiConfig();
        if (jndiConfig == null) {
            return;
        }
        try {
            InitialContext context = new InitialContext(jndiConfig.extractHashtableEnv());
            context.unbind(jndiConfig.getName());
        } catch (NamingException e) {
            log.error("Error in unregistering JNDI name: " + jndiConfig.getName() + " - " + e.getMessage(), e);
        }
    } finally {
        /*PrivilegedCarbonContext.endTenantFlow();*/
    }
}

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

private void unregisterJNDI(DataSourceMetaInfo dsmInfo) {
    try {/*from w w w .j av a  2s  .  c  om*/
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.getTenantId());
        JNDIConfig jndiConfig = dsmInfo.getJndiConfig();
        if (jndiConfig == null) {
            return;
        }
        try {
            InitialContext context = new InitialContext(jndiConfig.extractHashtableEnv());
            context.unbind(jndiConfig.getName());
        } catch (NamingException e) {
            log.error("Error in unregistering JNDI name: " + jndiConfig.getName() + " - " + e.getMessage(), e);
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}