Example usage for javax.naming InitialContext lookup

List of usage examples for javax.naming InitialContext lookup

Introduction

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

Prototype

public Object lookup(Name name) throws NamingException 

Source Link

Usage

From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java

public ValidationReportVO validateItem(PubItemVO item) throws NamingException {
    InitialContext initialContext = new InitialContext();
    ItemValidating itemValidating = (ItemValidating) initialContext
            .lookup("java:global/pubman_ear/validation/ItemValidatingBean");

    // To set the validation point
    this.getMethod(item);

    ValidationReportVO report = new ValidationReportVO();

    try {//from   w w w  .  ja  v a 2s . co m
        report = itemValidating.validateItemObject(item, this.getValidationPoint());
    } catch (Exception e) {
        this.logger.error("Validation error", e);
    }
    return report;
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testAddConnection_BindsToJndiWhenStarted() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());/*from w w w  .jav  a 2 s.c om*/
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        start(adapter);
        stop(adapter);
        adapter.getSharedComponents().addConnection(new NullConnection(getName()));
        start(adapter);
        NullConnection lookedup = (NullConnection) initialContext.lookup("adapter:comp/env/" + getName());
        assertNotNull(lookedup);
        assertEquals(getName(), lookedup.getUniqueId());
    } finally {
        stop(adapter);
    }
}

From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java

public ValidationReportVO validateItem(PubItemVO item) throws NamingException {
    InitialContext initialContext = new InitialContext();
    ItemValidating itemValidating = (ItemValidating) initialContext
            .lookup("java:global/pubman_ear/validation/ItemValidatingBean");

    //To set the validation point
    this.getMethod(item);

    ValidationReportVO report = new ValidationReportVO();

    try {/*ww w .  j  a  va 2  s  .c om*/
        report = itemValidating.validateItemObject(item, this.getValidationPoint());
    } catch (Exception e) {
        this.logger.error("Validation error", e);
    }
    return report;
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testBindJNDI() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());/*from  w  ww  .  j a  va 2  s.  c om*/
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        start(adapter);
        adapter.getSharedComponents().addConnection(new NullConnection(getName()));
        adapter.getSharedComponents().bindJNDI(getName());
        NullConnection lookedup = (NullConnection) initialContext.lookup("adapter:comp/env/" + getName());
        assertNotNull(lookedup);
        assertEquals(getName(), lookedup.getUniqueId());
        adapter.getSharedComponents().bindJNDI("ShouldGetIgnored");
    } finally {
        stop(adapter);
    }
}

From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java

/**
 * @param user/*from ww w .  j  av  a 2 s  .  co m*/
 * @param item
 * @return Saved pubItem
 * @throws NamingException
 * @throws AuthorizationException
 * @throws SecurityException
 * @throws TechnicalException
 * @throws URISyntaxException
 * @throws NamingException
 * @throws ItemInvalidException
 * @throws PubManException
 * @throws DepositingException
 */
public PubItemVO doDeposit(AccountUserVO user, PubItemVO item)
        throws ItemInvalidException, PubItemStatusInvalidException, Exception {
    PubItemVO depositedItem = null;
    InitialContext initialContext = new InitialContext();
    PubItemDepositing depositBean = (PubItemDepositing) initialContext
            .lookup("java:global/pubman_ear/pubman_logic/PubItemDepositingBean");
    String method = this.getMethod(item);

    if (method == null) {
        throw new PubItemStatusInvalidException(null, null);
    }
    if (method.equals("SAVE")) {
        depositedItem = depositBean.savePubItem(item, user);
    }
    if (method.equals("SAVE_SUBMIT") || method.equals("SUBMIT")) {
        depositedItem = depositBean.savePubItem(item, user);
        depositedItem = depositBean.submitPubItem(depositedItem, "", user);
    }
    if (method.equals("RELEASE")) {
        depositedItem = depositBean.savePubItem(item, user);
        depositedItem = depositBean.submitAndReleasePubItem(depositedItem, "", user);
    }

    return depositedItem;
}

From source file:org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule.java

public void configure(QName pid, String extVarId, Element config) throws ExternalVariableModuleException {
    EVarId evarId = new EVarId(pid, extVarId);
    DataSource ds = null;/*from   w ww.j  a v a2  s. c o m*/

    Element jndiDs = DOMUtils.findChildByName(config, new QName(JDBC_NS, "datasource-jndi"));
    Element jndiRef = DOMUtils.findChildByName(config, new QName(JDBC_NS, "datasource-ref"));
    Element initMode = DOMUtils.findChildByName(config, new QName(JDBC_NS, "init-mode"));
    if (jndiRef != null) {
        String refname = jndiRef.getTextContent().trim();
        ds = _dataSources.get(refname);
        if (ds == null)
            throw new ExternalVariableModuleException(
                    "Data source reference \"" + refname + "\" not found for external variable " + evarId
                            + "; make sure to register the data source with the engine!");
    } else if (jndiDs != null) {
        String name = jndiDs.getTextContent().trim();
        Object dsCandidate;
        InitialContext ctx;
        try {
            ctx = new InitialContext();
        } catch (Exception ex) {
            throw new ExternalVariableModuleException(
                    "Unable to access JNDI context for external variable " + evarId, ex);
        }

        try {
            dsCandidate = ctx.lookup(name);
        } catch (Exception ex) {
            throw new ExternalVariableModuleException("Lookup of data source for " + evarId + "  failed.", ex);
        } finally {
            try {
                ctx.close();
            } catch (NamingException e) {
                /* ignore */ }
        }

        if (dsCandidate == null)
            throw new ExternalVariableModuleException("Data source \"" + name + "\" not found in JNDI!");

        if (!(dsCandidate instanceof DataSource))
            throw new ExternalVariableModuleException(
                    "JNDI object \"" + name + "\" does not implement javax.sql.DataSource");

        ds = (DataSource) dsCandidate;
    }

    if (ds == null) {
        throw new ExternalVariableModuleException(
                "No valid data source configuration for JDBC external varible " + evarId);
    }

    Connection conn = null;
    DatabaseMetaData metaData;
    try {
        conn = ds.getConnection();
        metaData = conn.getMetaData();
    } catch (Exception ex) {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            // ignore
        }
        throw new ExternalVariableModuleException(
                "Unable to open database connection for external variable " + evarId, ex);
    }

    try {
        DbExternalVariable dbev = new DbExternalVariable(evarId, ds);
        if (initMode != null)
            try {
                dbev._initType = InitType.valueOf(initMode.getTextContent().trim());
            } catch (Exception ex) {
                throw new ExternalVariableModuleException(
                        "Invalid <init-mode> value: " + initMode.getTextContent().trim());
            }

        Element tableName = DOMUtils.findChildByName(config, new QName(JDBC_NS, "table"));
        if (tableName == null || tableName.getTextContent().trim().equals(""))
            throw new ExternalVariableModuleException("Must specify <table> for external variable " + evarId);
        String table = tableName.getTextContent().trim();
        String schema = null;
        if (table.indexOf('.') != -1) {
            schema = table.substring(0, table.indexOf('.'));
            table = table.substring(table.indexOf('.') + 1);
        }

        if (metaData.storesLowerCaseIdentifiers()) {
            table = table.toLowerCase();
            if (schema != null)
                schema = table.toLowerCase();
        } else if (metaData.storesUpperCaseIdentifiers()) {
            table = table.toUpperCase();
            if (schema != null)
                schema = schema.toUpperCase();
        }

        dbev.generatedKeys = metaData.supportsGetGeneratedKeys();
        ResultSet tables = metaData.getTables(null, schema, table, null);
        if (tables.next()) {
            dbev.table = tables.getString("TABLE_NAME");
            dbev.schema = tables.getString("TABLE_SCHEM");
        } else
            throw new ExternalVariableModuleException("Table \"" + table + "\" not found in database.");

        tables.close();

        List<Element> columns = DOMUtils.findChildrenByName(config, new QName(JDBC_NS, "column"));

        for (Element col : columns) {
            String name = col.getAttribute("name");
            String colname = col.getAttribute("column-name");
            String key = col.getAttribute("key");
            String gentype = col.getAttribute("generator");
            String expression = col.getAttribute("expression");

            if (key == null || "".equals(key))
                key = "no";
            if (gentype == null || "".equals(gentype))
                gentype = GenType.none.toString();
            if (colname == null || "".equals(colname))
                colname = name;

            if (name == null || "".equals(name))
                throw new ExternalVariableModuleException(
                        "External variable " + evarId + " <column> element must have \"name\" attribute. ");

            if (metaData.storesLowerCaseIdentifiers())
                colname = colname.toLowerCase();
            else if (metaData.storesUpperCaseIdentifiers())
                colname = colname.toUpperCase();

            GenType gtype;
            try {
                gtype = GenType.valueOf(gentype);
            } catch (Exception ex) {
                throw new ExternalVariableModuleException("External variable " + evarId + " column \"" + name
                        + "\" generator type \"" + gentype + "\" is unknown.");

            }

            if (gtype == GenType.expression && (expression == null || "".equals(expression)))
                throw new ExternalVariableModuleException("External variable " + evarId + " column \"" + name
                        + "\" used \"expression\" generator, but did not specify an expression");

            Column c = dbev.new Column(name, colname, key.equalsIgnoreCase("yes"), gtype, expression);
            ResultSet cmd = metaData.getColumns(null, dbev.schema, dbev.table, colname);
            try {
                if (cmd.next()) {
                    c.dataType = cmd.getInt("DATA_TYPE");
                    c.nullok = cmd.getInt("NULLABLE") != 0;
                } else
                    throw new ExternalVariableModuleException("External variable " + evarId + " referenced "
                            + "non-existant column \"" + colname + "\"!");
            } finally {
                cmd.close();
            }

            dbev.addColumn(c);
        }

        if (dbev.numColumns() == 0)
            throw new ExternalVariableModuleException(
                    "External variable " + evarId + " did not have any <column> elements!");

        _vars.put(evarId, dbev);
    } catch (SQLException se) {
        throw new ExternalVariableModuleException("SQL Error", se);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
        }
    }
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testBindJNDITransactionManager() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());//from w  ww  . ja  va 2s. c  o  m
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        start(adapter);
        adapter.getSharedComponents().setTransactionManager(new DummyTransactionManager(getName(), null));
        adapter.getSharedComponents().bindJNDI(getName());
        TransactionManager lookedup = (TransactionManager) initialContext
                .lookup("adapter:comp/env/" + getName());
        assertNotNull(lookedup);
        assertEquals(getName(), lookedup.getUniqueId());
        adapter.getSharedComponents().bindJNDI("ShouldGetIgnored");
    } finally {
        stop(adapter);
    }
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testBindJNDIService() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());//ww  w.  j  a  v a2s. c o m
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        start(adapter);

        MockService mockService = new MockService();
        adapter.getSharedComponents().addService(mockService);
        adapter.getSharedComponents().bindJNDI(mockService.getUniqueId());
        Service lookedup = (Service) initialContext.lookup("adapter:comp/env/" + mockService.getUniqueId());
        assertNotNull(lookedup);
        assertEquals(mockService.getUniqueId(), lookedup.getUniqueId());
        adapter.getSharedComponents().bindJNDI("ShouldGetIgnored");
    } finally {
        stop(adapter);
    }
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testClose_UnbindsFromJNDI() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());//from  ww  w. j  a v  a  2  s . c om
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        adapter.getSharedComponents().addConnection(new NullConnection(getName()));
        adapter.getSharedComponents().addConnection(new NullConnection(getName() + "_2"));
        start(adapter);
        NullConnection lookedup = (NullConnection) initialContext.lookup("adapter:comp/env/" + getName());
        assertEquals(getName(), lookedup.getUniqueId());
        stop(adapter);
        try {
            initialContext.lookup("adapter:comp/env/" + getName());
            fail();
        } catch (NamingException expected) {

        }
        // Now a start request should rebind to JNDI.
        start(adapter);
        initialContext.lookup("adapter:comp/env/" + getName());
        initialContext.lookup("adapter:comp/env/" + getName() + "_2");
    } finally {
        stop(adapter);
    }
}

From source file:org.meveo.service.job.JobInstanceService.java

public void manualExecute(JobInstance entity) throws BusinessException {
    log.info("Manual execute a job {} of type {}", entity.getCode(), entity.getJobTemplate());
    try {//from w  w  w  .j a va2  s.  com
        // Retrieve a timer entity from registered job timers, so if job is launched manually and automatically at the same time, only one will run
        if (jobTimers.containsKey(entity.getId())) {
            entity = (JobInstance) jobTimers.get(entity.getId()).getInfo();
        }

        InitialContext ic = new InitialContext();
        User currentUser = userService
                .attach(entity.getAuditable().getUpdater() != null ? entity.getAuditable().getUpdater()
                        : entity.getAuditable().getCreator());
        if (!currentUser.doesProviderMatch(getCurrentProvider())) {
            throw new BusinessException("Not authorized to execute this job");
        }

        if (jobEntries.containsKey(entity.getJobCategoryEnum())) {
            HashMap<String, String> jobs = jobEntries.get(entity.getJobCategoryEnum());
            if (jobs.containsKey(entity.getJobTemplate())) {
                Job job = (Job) ic.lookup(jobs.get(entity.getJobTemplate()));
                job.execute(entity, getCurrentUser());
            }
        } else {
            throw new BusinessException("Cannot find job category " + entity.getJobCategoryEnum());
        }
    } catch (NamingException e) {
        log.error("failed to manually execute ", e);

    } catch (Exception e) {
        log.error("Failed to manually execute a job {} of type {}", entity.getCode(), entity.getJobTemplate(),
                e);
        throw e;
    }
}