Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

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

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:com.duroty.application.files.manager.SearchManager.java

/**
 * @throws NamingException //from  w ww. ja  v  a2 s  . com
 *
 */
public SearchManager(HashMap mail)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, NamingException {
    super();

    String luceneAnalyzer = (String) mail.get(Constants.MAIL_LUCENE_ANALYZER);

    if ((luceneAnalyzer != null) && !luceneAnalyzer.trim().equals("")) {
        Class clazz = null;
        clazz = Class.forName(luceneAnalyzer.trim());
        this.analyzer = (Analyzer) clazz.newInstance();
    }

    this.defaultLucenePath = (String) mail.get(Constants.MAIL_LUCENE_PATH);

    this.folderAll = (String) mail.get(Constants.MAIL_FOLDER_ALL);
    this.folderInbox = (String) mail.get(Constants.MAIL_FOLDER_INBOX);
    this.folderSent = (String) mail.get(Constants.MAIL_FOLDER_SENT);
    this.folderTrash = (String) mail.get(Constants.MAIL_FOLDER_TRASH);
    this.folderBlog = (String) mail.get(Constants.MAIL_FOLDER_BLOG);
    this.folderDraft = (String) mail.get(Constants.MAIL_FOLDER_DRAFT);
    this.folderSpam = (String) mail.get(Constants.MAIL_FOLDER_SPAM);

    //this.folderImportant = (String) mail.get(Constants.MAIL_FOLDER_IMPORTANT);
    this.folderHidden = (String) mail.get(Constants.MAIL_FOLDER_HIDDEN);
    this.folderFiles = (String) mail.get(Constants.MAIL_FOLDER_FILES);

    //this.folderChat = (String) mail.get(Constants.MAIL_FOLDER_CHAT);

    Map options = ApplicationConstants.options;

    Context ctx = new InitialContext();

    this.extensions = (HashMap) ctx.lookup((String) options.get(Constants.EXTENSION_CONFIG));
}

From source file:edu.harvard.iq.dvn.ingest.dsb.DSBWrapper.java

private void ingestFileLevelMetadata(Map<String, Set<String>> fileLevelMetadata, StudyFile studyFile,
        FileMetadata fileMetadata, String fileFormatName) {
    // First, add the "metadata summary" generated by the file reader/ingester
    // to the fileMetadata object, as the "description":

    Set<String> metadataSummarySet = fileLevelMetadata.get(METADATA_SUMMARY);
    if (metadataSummarySet != null && metadataSummarySet.size() > 0) {
        String metadataSummary = "";
        for (String s : metadataSummarySet) {
            metadataSummary = metadataSummary.concat(s);
        }//w  w  w  .  j a  v  a 2s  . co m
        if (!metadataSummary.equals("")) {
            // The AddFiles page allows a user to enter file description 
            // on ingest. We don't want to overwrite whatever they may 
            // have entered. Rather, we'll append our metadata summary 
            // to the existing value. 
            String userEnteredFileDescription = fileMetadata.getDescription();
            if (userEnteredFileDescription != null && !(userEnteredFileDescription.equals(""))) {

                metadataSummary = userEnteredFileDescription.concat("\n" + metadataSummary);
            }
            fileMetadata.setDescription(metadataSummary);
        }

        fileLevelMetadata.remove(METADATA_SUMMARY);
    }

    // And now we can go through the remaining key/value pairs in the 
    // metadata maps and process the metadata elements found in the 
    // file: 

    for (String mKey : fileLevelMetadata.keySet()) {

        Set<String> mValues = fileLevelMetadata.get(mKey);

        // Check if the field doesn't exist yet:

        try {
            Context ctx = new InitialContext();
            studyFieldService = (StudyFieldServiceLocal) ctx.lookup("java:comp/env/studyField");
        } catch (Exception ex) {
            dbgLog.info("Caught an exception looking up StudyField Service; " + ex.getMessage());
        }
        if (studyFieldService == null) {
            dbgLog.warning("No StudyField Service; exiting file-level metadata ingest.");
            return;
        }

        dbgLog.fine("Looking up file meta field " + mKey + ", file format " + fileFormatName);
        FileMetadataField fileMetaField = studyFieldService.findFileMetadataFieldByNameAndFormat(mKey,
                fileFormatName);

        if (fileMetaField == null) {
            //fileMetaField = studyFieldService.createFileMetadataField(mKey, fileFormatName); 
            fileMetaField = new FileMetadataField();

            if (fileMetaField == null) {
                dbgLog.warning("Failed to create a new File Metadata Field; skipping.");
                continue;
            }

            fileMetaField.setName(mKey);
            fileMetaField.setFileFormatName(fileFormatName);
            // TODO: provide meaningful descriptions and labels:
            fileMetaField.setDescription(mKey);
            fileMetaField.setTitle(mKey);

            try {
                studyFieldService.saveFileMetadataField(fileMetaField);
            } catch (Exception ex) {
                dbgLog.warning("Failed to save new file metadata field (" + mKey + "); skipping values.");
                continue;
            }

            dbgLog.fine("Created file meta field " + mKey);
        }

        String fieldValueText = null;

        if (mValues != null) {
            for (String mValue : mValues) {
                if (mValue != null) {
                    if (fieldValueText == null) {
                        fieldValueText = mValue;
                    } else {
                        fieldValueText = fieldValueText.concat(" ".concat(mValue));
                    }
                }
            }
        }

        FileMetadataFieldValue fileMetaFieldValue = null;

        if (!"".equals(fieldValueText)) {
            dbgLog.fine("Attempting to create a file meta value for study file " + studyFile.getId()
                    + ", value " + fieldValueText);
            if (studyFile != null) {
                fileMetaFieldValue = new FileMetadataFieldValue(fileMetaField, studyFile, fieldValueText);
            }
        }
        if (fileMetaFieldValue == null) {
            dbgLog.warning("Failed to create a new File Metadata Field value; skipping");
            continue;
        } else {
            if (studyFile.getFileMetadataFieldValues() == null) {
                studyFile.setFileMetadataFieldValues(new ArrayList<FileMetadataFieldValue>());
            }
            studyFile.getFileMetadataFieldValues().add(fileMetaFieldValue);
        }
    }
}

From source file:org.apache.wiki.auth.user.JDBCUserDatabase.java

/**
 * @see org.apache.wiki.auth.user.UserDatabase#initialize(org.apache.wiki.WikiEngine,
 *      java.util.Properties)/*from   www  .j av  a 2 s  .co  m*/
 */
public void initialize(WikiEngine engine, Properties props)
        throws NoRequiredPropertyException, WikiSecurityException {
    String userTable;
    String role;
    String roleTable;

    String jndiName = props.getProperty(PROP_DB_DATASOURCE, DEFAULT_DB_JNDI_NAME);
    try {
        Context initCtx = new InitialContext();
        Context ctx = (Context) initCtx.lookup("java:comp/env");
        m_ds = (DataSource) ctx.lookup(jndiName);

        // Prepare the SQL selectors
        userTable = props.getProperty(PROP_DB_TABLE, DEFAULT_DB_TABLE);
        m_email = props.getProperty(PROP_DB_EMAIL, DEFAULT_DB_EMAIL);
        m_fullName = props.getProperty(PROP_DB_FULL_NAME, DEFAULT_DB_FULL_NAME);
        m_lockExpiry = props.getProperty(PROP_DB_LOCK_EXPIRY, DEFAULT_DB_LOCK_EXPIRY);
        m_loginName = props.getProperty(PROP_DB_LOGIN_NAME, DEFAULT_DB_LOGIN_NAME);
        m_password = props.getProperty(PROP_DB_PASSWORD, DEFAULT_DB_PASSWORD);
        m_uid = props.getProperty(PROP_DB_UID, DEFAULT_DB_UID);
        m_wikiName = props.getProperty(PROP_DB_WIKI_NAME, DEFAULT_DB_WIKI_NAME);
        m_created = props.getProperty(PROP_DB_CREATED, DEFAULT_DB_CREATED);
        m_modified = props.getProperty(PROP_DB_MODIFIED, DEFAULT_DB_MODIFIED);
        m_attributes = props.getProperty(PROP_DB_ATTRIBUTES, DEFAULT_DB_ATTRIBUTES);

        m_findAll = "SELECT * FROM " + userTable;
        m_findByEmail = "SELECT * FROM " + userTable + " WHERE " + m_email + "=?";
        m_findByFullName = "SELECT * FROM " + userTable + " WHERE " + m_fullName + "=?";
        m_findByLoginName = "SELECT * FROM " + userTable + " WHERE " + m_loginName + "=?";
        m_findByUid = "SELECT * FROM " + userTable + " WHERE " + m_uid + "=?";
        m_findByWikiName = "SELECT * FROM " + userTable + " WHERE " + m_wikiName + "=?";

        // The user insert SQL prepared statement
        m_insertProfile = "INSERT INTO " + userTable + " (" + m_uid + "," + m_email + "," + m_fullName + ","
                + m_password + "," + m_wikiName + "," + m_modified + "," + m_loginName + "," + m_attributes
                + "," + m_created + ") VALUES (?,?,?,?,?,?,?,?,?)";

        // The user update SQL prepared statement
        m_updateProfile = "UPDATE " + userTable + " SET " + m_uid + "=?," + m_email + "=?," + m_fullName + "=?,"
                + m_password + "=?," + m_wikiName + "=?," + m_modified + "=?," + m_loginName + "=?,"
                + m_attributes + "=?," + m_lockExpiry + "=? " + "WHERE " + m_loginName + "=?";

        // Prepare the role insert SQL
        roleTable = props.getProperty(PROP_DB_ROLE_TABLE, DEFAULT_DB_ROLE_TABLE);
        role = props.getProperty(PROP_DB_ROLE, DEFAULT_DB_ROLE);
        m_insertRole = "INSERT INTO " + roleTable + " (" + m_loginName + "," + role + ") VALUES (?,?)";
        m_findRoles = "SELECT * FROM " + roleTable + " WHERE " + m_loginName + "=?";

        // Prepare the user delete SQL
        m_deleteUserByLoginName = "DELETE FROM " + userTable + " WHERE " + m_loginName + "=?";

        // Prepare the role delete SQL
        m_deleteRoleByLoginName = "DELETE FROM " + roleTable + " WHERE " + m_loginName + "=?";

        // Prepare the rename user/roles SQL
        m_renameProfile = "UPDATE " + userTable + " SET " + m_loginName + "=?," + m_modified + "=? WHERE "
                + m_loginName + "=?";
        m_renameRoles = "UPDATE " + roleTable + " SET " + m_loginName + "=? WHERE " + m_loginName + "=?";
    } catch (NamingException e) {
        log.error("JDBCUserDatabase initialization error: " + e.getMessage());
        throw new NoRequiredPropertyException(PROP_DB_DATASOURCE,
                "JDBCUserDatabase initialization error: " + e.getMessage());
    }

    // Test connection by doing a quickie select
    Connection conn = null;
    try {
        conn = m_ds.getConnection();
        PreparedStatement ps = conn.prepareStatement(m_findAll);
        ps.close();
    } catch (SQLException e) {
        log.error("DB connectivity error: " + e.getMessage());
        throw new WikiSecurityException("DB connectivity error: " + e.getMessage(), e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    log.info("JDBCUserDatabase initialized from JNDI DataSource: " + jndiName);

    // Determine if the datasource supports commits
    try {
        conn = m_ds.getConnection();
        DatabaseMetaData dmd = conn.getMetaData();
        if (dmd.supportsTransactions()) {
            m_supportsCommits = true;
            conn.setAutoCommit(false);
            log.info("JDBCUserDatabase supports transactions. Good; we will use them.");
        }
    } catch (SQLException e) {
        log.warn("JDBCUserDatabase warning: user database doesn't seem to support transactions. Reason: "
                + e.getMessage());
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.apache.juddi.subscription.notify.AMQPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {
    Connection connection = null;
    Context context = null;
    boolean success = false;
    String err = null;/*w w  w.jav a 2  s. c om*/
    try {
        if (destination != null && exchangeType != null && exchangeName != null) {
            log.info("Sending notification AMQP to " + destination);
            Properties properties = new Properties();

            properties.put("java.naming.factory.initial",
                    "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
            properties.put("connectionfactory.qpidConnectionfactory", destination);
            properties.put("destination." + exchangeName, exchangeType);

            context = new InitialContext(properties);

            ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory");
            connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destinationLocal = (Destination) context.lookup(exchangeName);

            MessageProducer messageProducer = session.createProducer(destinationLocal);

            String subscriptionResultXML = JAXBMarshaller.marshallToString(body,
                    JAXBMarshaller.PACKAGE_SUBSCR_RES);
            TextMessage message = session.createTextMessage(subscriptionResultXML);
            messageProducer.send(message);
            success = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Error deliverying AMQP subscription " + e.getMessage());
        log.debug("Error deliverying AMQP subscription " + e.getMessage(), e);
        err = e.getMessage();

    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException ex) {
            log.error(null, ex);
        }
        try {
            if (context != null) {
                context.close();
            }
        } catch (NamingException ex) {
            log.error(null, ex);
        }
    }
    if (!success) {
        throw new DispositionReportFaultMessage(err, null);
    }
    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);

    return dr;
}

From source file:com.intuit.it.billing.data.BillingDAOImpl.java

Connection getConnection() throws NamingException, SQLException {
    Context initContext = null;
    Context envContext = null;// w w  w .j  ava 2s. c o  m
    Connection conn = null;
    DataSource ds = null;

    initContext = new InitialContext();
    envContext = (Context) initContext.lookup("java:/comp/env");
    ds = (DataSource) envContext.lookup("datasources/OracleDS");
    conn = ds.getConnection();

    return conn;
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * Method called to initialize this StoreResource.
 * @param _instance     Instance of the object this StoreResource is wanted
 *                      for//  www . ja  v  a 2 s .c  om
 * @param _store        Store this resource belongs to
 * @throws EFapsException on error
 * @see Resource#initialize(Instance, Map, Compress)
 */
@Override
public void initialize(final Instance _instance, final Store _store) throws EFapsException {
    super.initialize(_instance, _store);

    final StringBuilder fileNameTmp = new StringBuilder();

    final String useTypeIdStr = getStore().getResourceProperties().get(VFSStoreResource.PROPERTY_USE_TYPE);
    if ("true".equalsIgnoreCase(useTypeIdStr)) {
        fileNameTmp.append(getInstance().getType().getId()).append("/");
    }

    final String numberSubDirsStr = getStore().getResourceProperties()
            .get(VFSStoreResource.PROPERTY_NUMBER_SUBDIRS);
    if (numberSubDirsStr != null) {
        final long numberSubDirs = Long.parseLong(numberSubDirsStr);
        final String pathFormat = "%0" + Math.round(Math.log10(numberSubDirs) + 0.5d) + "d";
        fileNameTmp.append(String.format(pathFormat, getInstance().getId() % numberSubDirs)).append("/");
    }
    fileNameTmp.append(getInstance().getType().getId()).append(".").append(getInstance().getId());
    this.storeFileName = fileNameTmp.toString();

    final String numberBackupStr = getStore().getResourceProperties()
            .get(VFSStoreResource.PROPERTY_NUMBER_BACKUP);
    if (numberBackupStr != null) {
        this.numberBackup = Integer.parseInt(numberBackupStr);
    }

    if (this.manager == null) {
        try {
            DefaultFileSystemManager tmpMan = null;
            if (getStore().getResourceProperties().containsKey(Store.PROPERTY_JNDINAME)) {
                final InitialContext initialContext = new InitialContext();
                final Context context = (Context) initialContext.lookup("java:comp/env");
                final NamingEnumeration<NameClassPair> nameEnum = context.list("");
                while (nameEnum.hasMoreElements()) {
                    final NameClassPair namePair = nameEnum.next();
                    if (namePair.getName()
                            .equals(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME))) {
                        tmpMan = (DefaultFileSystemManager) context
                                .lookup(getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME));
                        break;
                    }
                }
            }
            if (tmpMan == null && this.manager == null) {
                this.manager = evaluateFileSystemManager();
            }
        } catch (final NamingException e) {
            throw new EFapsException(VFSStoreResource.class, "initialize.NamingException", e);
        }
    }
}

From source file:com.impetus.kundera.persistence.EntityManagerImpl.java

private void onLookUp(PersistenceUnitTransactionType transactionType) {
    // TODO transaction should not be null;
    if (transactionType != null && transactionType.equals(PersistenceUnitTransactionType.JTA)) {
        if (this.entityTransaction == null) {
            this.entityTransaction = new KunderaEntityTransaction(this);
        }/*from   w w  w . j av a2 s.  c o m*/
        Context ctx;
        try {
            ctx = new InitialContext();

            this.utx = (UserTransaction) ctx.lookup("java:comp/UserTransaction");

            if (this.utx == null) {
                throw new KunderaException(
                        "Lookup for UserTransaction returning null for :{java:comp/UserTransaction}");
            }
            // TODO what is need to check?
            if (!(this.utx instanceof KunderaJTAUserTransaction)) {
                throw new KunderaException("Please bind [" + KunderaJTAUserTransaction.class.getName()
                        + "] for :{java:comp/UserTransaction} lookup" + this.utx.getClass());
            }

            if (!this.entityTransaction.isActive()) {
                this.entityTransaction.begin();
                this.setFlushMode(FlushModeType.COMMIT);
                ((KunderaJTAUserTransaction) this.utx).setImplementor(this);
            }

        } catch (NamingException e) {
            logger.error("Error during initialization of entity manager, Caused by:", e);
            throw new KunderaException(e);
        }

    }
}

From source file:com.jaspersoft.jasperserver.war.action.DataSourceAction.java

public Event testJndiDataSource(RequestContext context) throws Exception {
    String connectionStatusMessageKey = RESOURCE_DATA_SOURCE_CONNECTION_STATE_FAILED;
    ReportDataSourceWrapper wrapper = (ReportDataSourceWrapper) getFormObject(context);
    JndiJdbcReportDataSource ds = (JndiJdbcReportDataSource) wrapper.getReportDataSource();
    Connection conn = null;/*  w ww .  j a v a 2s .  c  o m*/
    try {
        Context ctx = new InitialContext();
        DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/" + ds.getJndiName());
        conn = TibcoDriverManagerImpl.getInstance().unlockConnection(dataSource);
        if (conn != null) {
            connectionStatusMessageKey = RESOURCE_DATA_SOURCE_CONNECTION_STATE_PASSED;
        }
    } catch (Exception e) {
        logger.error("exception testing jndi data source", e);
    } finally {
        if (conn != null)
            conn.close();
    }

    context.getRequestScope().put(AJAX_RESPONSE_MODEL,
            messages.getMessage(connectionStatusMessageKey, null, LocaleContextHolder.getLocale()));
    return success();
}

From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java

private <T> T lookup(Context context, Class<T> clazz, String name) throws NamingException {
    if (context == null) {
        logger.error(nameString() + ". Cannot perform JNDI lookup. Invalid context.");
        return null;
    }/*  w  ww .java2s.  co  m*/
    if (name == null || "".equals(name)) {
        logger.error(nameString() + ". Cannot perform JNDI lookup. Invalid name.");
        return null;
    }
    Object object = context.lookup(name);
    try {
        return clazz.cast(object);
    } catch (ClassCastException e) {
        logger.error(nameString() + ". Cannot perform JNDI lookup for the name [" + name + "].", e);
        return null;
    }
}

From source file:com.intuit.it.billing.data.BillingFileReader.java

Connection getConnection() throws NamingException, SQLException {
    Context initContext = null;
    Context envContext = null;//from  w  w w. j  a  v a 2s . c  om
    Connection conn = null;
    DataSource ds = null;

    initContext = new InitialContext();
    envContext = (Context) initContext.lookup("java:/comp/env");
    ds = (DataSource) envContext.lookup("jdbc/myoracle");
    conn = ds.getConnection();

    return conn;
}