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:gov.nih.nci.cagrid.protexpress.service.globus.resource.ProtExpressGridServiceResourceBase.java

public ProtExpressGridServiceResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }//www.j  av  a2s .co  m
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/ProtExpressGridService";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (ProtExpressGridServiceResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:com.autentia.tnt.util.ConfigurationUtil.java

/**
 * Constructor/*from ww  w . j a v  a  2s  .co m*/
 * 
 * @param jndiPathVar
 *            JNDI variable in which configuration directory is stored
 * @param file
 *            path to configuration file
 */
public ConfigurationUtil(String jndiPathVar, String file) throws ConfigurationException, NamingException {
    Context ctx = new InitialContext();
    configDir = ctx.lookup(jndiPathVar).toString();
    if (!configDir.endsWith("/") && !configDir.endsWith("\\")) {
        configDir = configDir.trim() + "/";
    }
    config = new PropertiesConfiguration(configDir + file);
}

From source file:de.zib.gndms.dspace.slice.service.globus.resource.SliceResourceBase.java

public SliceResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }//from  ww  w  .  j  a  v  a  2  s.  com
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/Slice";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (SliceResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:gov.ymp.slts.doSWTransaction.java

private String processRequest(HttpServletRequest request, HttpServletResponse response) {
    String command = request.getParameter("command");
    String idS = request.getParameter("id");
    int id = Integer.parseInt(idS);
    String prodIDS = request.getParameter("prodid");
    int prodID = Integer.parseInt(prodIDS);
    String transIDS = request.getParameter("transid");
    int transID = Integer.parseInt(transIDS);
    //System.out.println("doSWTransaction - Got Here 1" +"- command: " + command + ", Timestamp: " + Utils.genDateID());

    String outLine = "";
    String nextScript = request.getParameter("nextscript");
    OutputStream toClient;//from w  w w  . j a  va  2 s.  c o m
    HttpSession session = request.getSession();
    boolean success = false;
    String userIDs = (String) session.getAttribute("user.id");
    userIDs = ((userIDs != null) ? userIDs : "0");
    long userID = Long.parseLong(userIDs);

    command = (command != null && command.compareTo(" ") > 0) ? command : "new";
    nextScript = (nextScript != null && nextScript.compareTo(" ") > 0) ? nextScript : "swBrowse.jsp";

    DbConn myConn = null;
    try {

        Context initCtx = new InitialContext();
        String ProductionStatus = (String) initCtx.lookup("java:comp/env/ProductionStatus");
        //String csiSchema = (String) initCtx.lookup("java:comp/env/csi-schema-path");
        String acronym = (String) initCtx.lookup("java:comp/env/SystemAcronym");
        myConn = new DbConn();
        String csiSchema = myConn.getSchemaPath();
        SWProduct sw = new SWProduct(prodID, myConn);
        SWTransactions trn = null;
        if (command.equals("new") || command.equals("update")) {
            //if (command.equals("update")) {
            //System.out.println("doSWTransaction - Got Here 2");
            // process transaction
            if (command.equals("new")) {
                trn = new SWTransactions();
                trn.setProductID(prodID);
            } else {
                trn = new SWTransactions(prodID, transID, myConn);
            }

            String tag = request.getParameter("tag");
            trn.setTag(((tag != null) ? tag : null));
            String serialnumber = request.getParameter("serialnumber");
            trn.setSerialNumber(((serialnumber != null) ? serialnumber : null));
            String purchaseorder = request.getParameter("purchaseorder");
            trn.setPurchaseOrder(((purchaseorder != null) ? purchaseorder : null));
            String dateverified = request.getParameter("dateverified");
            trn.setDateVerified(((dateverified != null) ? Utils.toDate(dateverified) : null));
            String datereceived = request.getParameter("datereceived");
            trn.setDateReceived(((datereceived != null) ? Utils.toDate(datereceived) : null));
            String dateexpires = request.getParameter("dateexpires");
            trn.setDateExpires(((dateexpires != null) ? Utils.toDate(dateexpires) : null));
            String location = request.getParameter("location");
            trn.setLocation(((location != null) ? location : null));
            String licensetype = request.getParameter("licensetype");
            trn.setLicenseType(((licensetype != null) ? licensetype : null));
            String licensecountS = request.getParameter("licensecount");
            if (licensecountS != null && licensecountS.compareTo("       ") > 0) {
                int licensecount = Integer.parseInt(licensecountS);
                trn.setLicenseCount(licensecount);
            }
            String transactiontype = request.getParameter("transactiontype");
            trn.setTransactionType(((transactiontype != null) ? transactiontype : null));
            String relatedtransactionS = request.getParameter("relatedtransaction");
            if (relatedtransactionS != null && relatedtransactionS.compareTo("       ") > 0) {
                int relatedtransaction = Integer.parseInt(relatedtransactionS);
                trn.setRelatedTransaction(relatedtransaction);
            }
            String documentation = request.getParameter("documentation");
            trn.setDocumentation(((documentation != null) ? documentation : null));
            trn.save(myConn);
            transID = trn.getID();
            //System.out.println("doSWTransaction - Got Here 2.5");
            String comments = request.getParameter("comments");
            // process comments
            if (comments != null && comments.compareTo("                            ") > 0) {
                Comments comm = new Comments(prodID, transID, userID, comments, myConn);
            }
            //System.out.println("doSWTransaction - Got Here 3");
            //Process attachments
            String attachCountS = request.getParameter("attachcount");
            int attachCount = Integer.parseInt(attachCountS);
            for (int i = 1; i <= attachCount; i++) {
                Object fileObject = request.getAttribute("attachment" + i);
                if (fileObject != null && !(fileObject instanceof FileUploadException)) {
                    String aTypeS = request.getParameter("attachmenttype" + i);
                    int aType = Integer.parseInt(aTypeS);
                    String aDesc = request.getParameter("attachmentdesc" + i);
                    FileItem fileItem = (FileItem) fileObject;
                    String fileName = fileItem.getName();
                    aDesc = ((aDesc != null && aDesc.compareTo("                                ") > 0) ? aDesc
                            : fileName);
                    fileName = trimFilePath(fileName);
                    InputStream inStream = fileItem.getInputStream();
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                    int myByte = inStream.read();
                    while (myByte >= 0) {
                        outStream.write(myByte);
                        myByte = inStream.read();
                    }
                    Attachment at = new Attachment(prodID, transID, fileName, aType, aDesc, myConn);
                    at.setImage(myConn, outStream);
                }
            }
            //System.out.println("doSWTransaction - Got Here 4");

            success = true;
            outLine = "";
            ALog.logActivity(userID, "slts", 2, "Transaction updated.");

        } else if (command.equals("drop")) {

            //success = true;
            //outLine = "Transaction " + temp + " Removed";
            //ALog.logActivity(userID, "slts", 3, outLine);
        } else if (command.equals("test")) {
            outLine = "test";
        }

    }

    catch (IllegalArgumentException e) {
        outLine = outLine + "IllegalArgumentException caught: " + e.getMessage();
        ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
        //log(outLine);
    }

    catch (NullPointerException e) {
        outLine = outLine + "NullPointerException caught: " + e.getMessage();
        ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
        //log(outLine);
    }

    //catch (IOException e) {
    //    outLine = outLine + "IOException caught: " + e.getMessage();
    //    ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
    //    //log(outLine);
    //}

    //catch (MessagingException e) {
    //    outLine = outLine + "Messaging Exception caught: " + e.getMessage();
    //    ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
    //    //log(outLine);
    //}
    catch (Exception e) {
        outLine = outLine + "Exception caught: " + e.getMessage();
        ALog.logError(userID, "slts", 0, "doSWTransaction error: '" + outLine + "'");
        //log(outLine);
    } finally {
        try {
            generateResponse(outLine, command, nextScript, success, response);
        } catch (Exception i) {
        }

        myConn.release();
        //log("Test log message\n");
    }

    return outLine;

}

From source file:com.caricah.iotracah.datastore.ignitecache.internal.AbstractHandler.java

public void initiate(Class<T> t, Ignite ignite) {

    try {/*from ww  w .  j  av  a  2  s .co  m*/
        Context ic = new InitialContext();

        DataSource dataSource;
        if (isPersistanceEnabled())
            dataSource = (DataSource) ic.lookup("jdbc_commonpool");
        else
            dataSource = null;

        CacheConfiguration<K, T> clCfg = getCacheConfiguration(isPersistanceEnabled(), dataSource);

        clCfg = extraCacheSettingsConfigure(clCfg);

        ignite.createCache(clCfg);
        IgniteCache<K, T> clientIgniteCache = ignite.cache(getCacheName());

        clientIgniteCache.loadCache(null);

        setDatastoreCache(clientIgniteCache);

        classType = t;

        String nameOfSequence = getCacheName() + "-sequence";
        initializeSequence(nameOfSequence, ignite);

    } catch (NamingException e) {
        log.error(" getFactory : problems obtaining appropriate jdbc context");
        throw new UnRetriableException(e);
    }

}

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizFac(Context ctx, Object obj) throws Exception {

    ConnectionFactory f = (ConnectionFactory) obj;
    final JmsIO me = this;
    Connection conn;//from  w w  w .j  ava  2  s . c o m
    Object c = ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createConnection();
    }

    _conn = conn;

    if (c instanceof Destination) {
        //TODO ? ack always ?
        Session s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer u = s.createConsumer((Destination) c);
        u.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                me.onMessage(msg);
            }
        });
    } else {
        throw new Exception("JmsIO: Object not of Destination type");
    }
}

From source file:com.heliumv.api.cc.ClevercureApi.java

private void receiveCCDataOsd(String companyCode, String token, String ccdata)
        throws NamingException, RemoteException {
    Context env = (Context) new InitialContext().lookup("java:comp/env");
    String hvUser = (String) env.lookup("heliumv.credentials.user");
    String hvPassword = (String) env.lookup("heliumv.credentials.password");
    String hvWebshop = (String) env.lookup("heliumv.credentials.webshop");
    Boolean hvStoreReceivedData = (Boolean) env.lookup("heliumv.cc.data.storebefore");

    System.out.println("Received osd data");

    if (hvStoreReceivedData) {
        persistOsdData(ccdata);/* w w w  .  jav  a 2s .  c o m*/
    }

    WebshopAuthHeader authHeader = new WebshopAuthHeader();
    authHeader.setUser(hvUser);
    authHeader.setPassword(hvPassword);
    //      authHeader.setIsoCountry("AT") ;
    //      authHeader.setIsoLanguage("de") ;
    authHeader.setShopName(hvWebshop);
    authHeader.setToken(token);

    try {
        CreateOrderResult result = auftragRestCall.createOrder(authHeader, ccdata);
        if (Helper.isOneOf(result.getRc(),
                new int[] { CreateOrderResult.ERROR_EMPTY_ORDER, CreateOrderResult.ERROR_JAXB_EXCEPTION,
                        CreateOrderResult.ERROR_SAX_EXCEPTION, CreateOrderResult.ERROR_UNMARSHALLING })) {
            persistOsdData(ccdata, "error");
            respondBadRequest(result.getRc());
            return;
        }
        if (result.getRc() == CreateOrderResult.ERROR_AUTHENTIFICATION) {
            respondForbidden();
            persistOsdData(ccdata, "error_auth_.xml");
            return;
        }
        if (result.getRc() == CreateOrderResult.ERROR_CUSTOMER_NOT_FOUND) {
            respondNotFound();
            persistOsdData(ccdata, "error_customer_.xml");
            return;
        }

        if (result.getRc() >= CreateOrderResult.ERROR_EJB_EXCEPTION) {
            respondBadRequest(result.getRc());
            persistOsdData(ccdata, "error_ejb_.xml");
            return;
        }

        if (result.getRc() == BaseRequestResult.OKAY) {
            respondOkay();
            persistOsdData(ccdata, "200_.xml");
        } else {
            respondExpectationFailed(result.getRc());
        }
    } catch (EJBExceptionLP e) {
        respondBadRequest(e);

        persistOsdData(ccdata, "error_.xml");
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.olap.service.impl.OlapManagementServiceImpl.java

private MondrianConnectionSchemaParameters getConnectionParameters(MondrianConnection monConn,
        boolean transform) {
    MondrianConnectionSchemaParameters parameters = null;

    String monConnUri = transform ? transformUri(monConn.getURIString()) : monConn.getURIString();

    String dsUri = null;//from   w  w  w.j  a v  a 2 s .  c o m
    ReportDataSource dataSource = null;

    ResourceReference ref = monConn.getDataSource();
    if (ref.isLocal()) {
        dataSource = (ReportDataSource) ref.getLocalResource();
    } else {
        dsUri = transform ? transformUri(ref.getReferenceURI()) : ref.getReferenceURI();
        dataSource = (ReportDataSource) getRepositoryService().getResource(runtimeContext, dsUri);
    }

    if (dataSource == null) {
        throw new JSException("null data source on dereference of mondrian connection " + monConnUri + " for "
                + (monConn.getDataSource().isLocal() ? "local: " + ref.getLocalResource().getURIString()
                        : dsUri));
    }

    // Define values for schema cache key
    // This uri will be transformed as part of the CatalogLocator
    String catalogUrl = monConn.getSchema().getReferenceURI();

    if (transform) {
        catalogUrl = transformUri(catalogUrl);
    }

    catalogUrl = repositoryCatalogLocator.locate(catalogUrl);

    log.debug("catalogUrl: " + catalogUrl + ", original URI: " + monConn.getSchema().getReferenceURI()
            + ", transform: " + transform);

    if (dataSource instanceof JdbcReportDataSource) {
        JdbcReportDataSource jdbcDs = (JdbcReportDataSource) dataSource;
        String jdbcConnectString = jdbcDs.getConnectionUrl();
        String jdbcUser = jdbcDs.getUsername();
        parameters = new MondrianConnectionSchemaParameters(monConnUri, catalogUrl, jdbcConnectString,
                jdbcUser);
    } else {
        JndiJdbcReportDataSource jndiDs = (JndiJdbcReportDataSource) dataSource;

        String strDataSource = "";

        if ((jndiDs.getJndiName() != null && !jndiDs.getJndiName().startsWith("java:"))) {
            try {
                Context ctx = new InitialContext();
                ctx.lookup("java:comp/env/" + jndiDs.getJndiName());
                strDataSource = "java:comp/env/";
            } catch (NamingException e) {
                //Added as short time solution due of http://bugzilla.jaspersoft.com/show_bug.cgi?id=26570.
                //The main problem - this code executes in separate tread (non http).
                //Jboss 7 support team recommend that you use the non-component environment namespace for such situations.
                try {
                    Context ctx = new InitialContext();
                    ctx.lookup(jndiDs.getJndiName());
                    strDataSource = "";
                } catch (NamingException ex) {

                }
            }
        }

        strDataSource = strDataSource + jndiDs.getJndiName();
        parameters = new MondrianConnectionSchemaParameters(monConnUri, catalogUrl, strDataSource);
    }

    return parameters;
}

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizQueue(Context ctx, Object obj) throws Exception {

    QueueConnectionFactory f = (QueueConnectionFactory) obj;
    final JmsIO me = this;
    QueueConnection conn;//from ww  w.  j  av  a  2 s  .  c om
    Queue q = (Queue) ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createQueueConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createQueueConnection();
    }

    _conn = conn;

    QueueSession s = conn.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
    QueueReceiver r;

    r = s.createReceiver(q);
    r.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            me.onMessage(msg);
        }
    });
}

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizTopic(Context ctx, Object obj) throws Exception {

    TopicConnectionFactory f = (TopicConnectionFactory) obj;
    final JmsIO me = this;
    TopicConnection conn;/* w  w w  .j  a  va 2 s.  c  om*/
    Topic t = (Topic) ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createTopicConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createTopicConnection();
    }

    _conn = conn;

    TopicSession s = conn.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
    TopicSubscriber b;

    if (_durable) {
        b = s.createDurableSubscriber(t, GUID.generate());
    } else {
        b = s.createSubscriber(t);
    }

    b.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            me.onMessage(msg);
        }
    });
}