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:eu.uqasar.web.dashboard.widget.uqasardatavisualization.UqasarDataVisualizationSettingsPanel.java

public UqasarDataVisualizationSettingsPanel(String id, IModel<UqasarDataVisualizationWidget> model) {
    super(id, model);

    setOutputMarkupPlaceholderTag(true);

    //Form and WMCs
    final Form<Widget> form = new Form<>("form");
    wmcGeneral = newWebMarkupContainer("wmcGeneral");
    form.add(wmcGeneral);/*from ww  w.  j a  va 2s .  co m*/

    // Get the project from the settings
    projectName = getModelObject().getSettings().get("project");

    // DropDown select for Projects
    TreeNodeService treeNodeService = null;
    try {
        InitialContext ic = new InitialContext();
        treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");
        projects = treeNodeService.getAllProjectsOfLoggedInUser();
        if (projects != null && projects.size() != 0) {
            if (projectName == null || projectName.isEmpty()) {
                projectName = projects.get(0).getName();
            }
            project = treeNodeService.getProjectByName(projectName);
            recreateAllProjectTreeChildrenForProject(project);
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    //project
    List<String> joinedQualityParameters = ListUtils.union(ListUtils.union(OBJS, INDIS), MTRX);
    qualityParameterChoice = new DropDownChoice<String>("qualityParams",
            new PropertyModel<String>(this, "qualityParams"), joinedQualityParameters) {
        @Override
        protected void appendOptionHtml(AppendingStringBuffer buffer, String choice, int index,
                String selected) {
            super.appendOptionHtml(buffer, choice, index, selected);

            if (UqasarDataVisualizationWidget.ALL.get(0).equals(choice)) {
                buffer.append("<optgroup label='Quality Objectives'></optgroup>");
            }

            int noOfObjs = OBJS.size();
            int noOfIndis = INDIS.size();

            if (index + 1 == noOfObjs && noOfObjs > 0) {
                buffer.append("<optgroup label='Quality Indicators'></optgroup>");
            }
            if (index + 1 == (noOfObjs + noOfIndis) && noOfIndis > 0) {
                buffer.append("<optgroup label='Metrics'></optgroup>");
            }

        }
    };
    qualityParameterChoice.setOutputMarkupId(true);
    wmcGeneral.add(qualityParameterChoice);

    // project
    projectChoice = new DropDownChoice<>("projects", new PropertyModel<Project>(this, "project"), projects);
    if (project != null) {
        projectChoice.add(new AjaxFormComponentUpdatingBehavior("onChange") {
            private static final long serialVersionUID = 1L;

            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                System.out.println(project);
                recreateAllProjectTreeChildrenForProject(project);
                qualityParameterChoice.setChoices(ListUtils.union(ListUtils.union(OBJS, INDIS), MTRX));
                target.add(qualityParameterChoice);
                target.add(wmcGeneral);

                target.add(form);
            }
        });

    }

    wmcGeneral.setOutputMarkupId(true);
    wmcGeneral.add(projectChoice);

    form.add(new AjaxSubmitLink("submit") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

            if (project != null) {
                getModelObject().getSettings().put("qualityParams", qualityParams);
                getModelObject().getSettings().put("project", project.getName());

                Dashboard dashboard = findParent(DashboardPanel.class).getDashboard();
                DbDashboard dbdb = (DbDashboard) dashboard;

                WidgetPanel widgetPanel = findParent(WidgetPanel.class);
                UqasarDataVisualizationWidgetView widgetView = (UqasarDataVisualizationWidgetView) widgetPanel
                        .getWidgetView();
                target.add(widgetPanel);
                hideSettingPanel(target);

                // Do not save the default dashboard
                if (dbdb.getId() != null && dbdb.getId() != 0) {
                    dashboardContext.getDashboardPersiter().save(dashboard);
                    PageParameters params = new PageParameters();
                    params.add("id", dbdb.getId());
                    setResponsePage(DashboardViewPage.class, params);
                }
            }
        }
    });
    form.add(new AjaxLink<Void>("cancel") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            hideSettingPanel(target);
        }
    });

    add(form);
}

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

private Object lookupInContext(final String key, final boolean withPrefix) {
    if (!isJNDIAvailable()) {
        return null;
    }/* www .j av a2 s .  co  m*/
    final String normalizedKey = normalizeKey(key, withPrefix);
    InitialContext ctx = null;
    Object result = null;
    try {
        ctx = getJNDIContext();
        result = ctx.lookup(normalizedKey);
    } catch (final NoInitialContextException e) {
        logInfoButExceptionDebug(String.format("Maybe no JNDI-Context available. %s", e.getMessage()), e);
    } catch (final NamingException e) {
        LOG.debug("cannot lookup key: {} ({})", key, normalizedKey, e);
        if (withPrefix) {
            result = lookupInContext(key, false);
        }
    } finally {
        closeQuietly(ctx);
    }
    return result;
}

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

public void contextInitialized(ServletContextEvent evt) {
    boolean useDatasource = Boolean.valueOf(evt.getServletContext().getInitParameter("useDatasource"))
            .booleanValue();//from  w  w w. j  a  v a  2s  .c  o m
    String datasourceName = evt.getServletContext().getInitParameter("datasourceName");

    InitialContext ic;
    try {
        ic = new InitialContext();
        if (useDatasource) {
            if (datasourceName == null)
                throw new RuntimeException(
                        "Using datasource is enabled but datasourceName parameter is not specified.");

            DataSource dataSource = (DataSource) PortableRemoteObject.narrow(ic.lookup(datasourceName),
                    javax.sql.DataSource.class);
            ic.rebind("jgossip_db", dataSource);

        } else {
            Properties dbconf = new Properties();
            dbconf.load(evt.getServletContext()
                    .getResourceAsStream("/WEB-INF/classes/org/jresearch/gossip/resources/db.properties"));
            // Construct BasicDataSource reference
            Reference ref = new Reference("javax.sql.DataSource",
                    "org.apache.commons.dbcp.BasicDataSourceFactory", null);
            ref.add(new StringRefAddr("driverClassName", dbconf.getProperty("driverClassName")));
            ref.add(new StringRefAddr("url", dbconf.getProperty("url")));
            ref.add(new StringRefAddr("password", dbconf.getProperty("password")));
            ref.add(new StringRefAddr("username", dbconf.getProperty("username")));
            ref.add(new StringRefAddr("maxActive", dbconf.getProperty("maxActive")));
            ref.add(new StringRefAddr("maxWait", dbconf.getProperty("maxWait")));
            ref.add(new StringRefAddr("initialSize", dbconf.getProperty("initialSize")));
            ref.add(new StringRefAddr("defaultAutoCommit", dbconf.getProperty("defaultAutoCommit")));
            ref.add(new StringRefAddr("defaultReadOnly", dbconf.getProperty("defaultReadOnly")));
            ref.add(new StringRefAddr("poolPreparedStatements", dbconf.getProperty("poolPreparedStatements")));
            ref.add(new StringRefAddr("maxOpenPreparedStatements",
                    dbconf.getProperty("maxOpenPreparedStatements")));

            ic.rebind("jgossip_db", ref);
        }

    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Tests that an authorized user has access to an EJB method.
 *
 * @throws Exception/*w  ww . j a  va  2  s  .c o  m*/
 */
@Test
public void testAuthorizedClient() throws Exception {
    final Properties env = configureEjbClient(CLIENT_AUTHORIZED_NAME);
    InitialContext ctx = new InitialContext(env);
    final Hello helloBean = (Hello) ctx.lookup(HELLOBEAN_LOOKUP_NAME);
    assertEquals(HelloBean.HELLO_WORLD, helloBean.sayHelloWorld());
    ctx.close();
}

From source file:eu.uqasar.util.UQasarUtil.java

/**
 * Write metadata entities from the beans to rdf model
 *//*from  w ww. j av  a2  s .  com*/
private static OntModel writeMetaDataModelEntries() {
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
    try {
        InitialContext ic = new InitialContext();
        for (final Class clazz : MetaData.getAllClasses()) {
            if (ContinuousIntegrationTool.class.isAssignableFrom(clazz)) {
                ContinuousIntegrationToolService cits = (ContinuousIntegrationToolService) ic
                        .lookup("java:module/ContinuousIntegrationToolService");
                List<ContinuousIntegrationTool> continuousIntegrationTools = cits.getAll();
                for (ContinuousIntegrationTool continuousIntegrationTool : continuousIntegrationTools) {
                    writer.save(continuousIntegrationTool);
                }
            } else if (CustomerType.class.isAssignableFrom(clazz)) {
                CustomerTypeService cts = (CustomerTypeService) ic.lookup("java:module/CustomerTypeService");
                List<CustomerType> customerTypes = cts.getAll();
                for (CustomerType customerType : customerTypes) {
                    writer.save(customerType);
                }
            } else if (IssueTrackingTool.class.isAssignableFrom(clazz)) {
                IssueTrackingToolService itts = (IssueTrackingToolService) ic
                        .lookup("java:module/IssueTrackingToolService");
                List<IssueTrackingTool> issueTrackingTools = itts.getAll();
                for (IssueTrackingTool issueTrackingTool : issueTrackingTools) {
                    writer.save(issueTrackingTool);
                }
            } else if (ProgrammingLanguage.class.isAssignableFrom(clazz)) {
                ProgrammingLanguageService pls = (ProgrammingLanguageService) ic
                        .lookup("java:module/ProgrammingLanguageService");
                List<ProgrammingLanguage> programmingLanguages = pls.getAll();
                for (ProgrammingLanguage programmingLanguage : programmingLanguages) {
                    writer.save(programmingLanguage);
                }
            } else if (ProjectType.class.isAssignableFrom(clazz)) {
                ProjectTypeService pts = (ProjectTypeService) ic.lookup("java:module/ProjectTypeService");
                List<ProjectType> projectTypes = pts.getAll();
                for (ProjectType projectType : projectTypes) {
                    writer.save(projectType);
                }
            } else if (SoftwareLicense.class.isAssignableFrom(clazz)) {
                SoftwareLicenseService sls = (SoftwareLicenseService) ic
                        .lookup("java:module/SoftwareLicenseService");
                List<SoftwareLicense> softwareLicenses = sls.getAll();
                for (SoftwareLicense softwareLicense : softwareLicenses) {
                    writer.save(softwareLicense);
                }
            } else if (SoftwareType.class.isAssignableFrom(clazz)) {
                SoftwareTypeService sts = (SoftwareTypeService) ic.lookup("java:module/SoftwareTypeService");
                List<SoftwareType> softwareTypes = sts.getAll();
                for (SoftwareType softwareType : softwareTypes) {
                    writer.save(softwareType);
                }
            } else if (SourceCodeManagementTool.class.isAssignableFrom(clazz)) {
                SourceCodeManagementToolService scmts = (SourceCodeManagementToolService) ic
                        .lookup("java:module/SourceCodeManagementToolService");
                List<SourceCodeManagementTool> sourceCodeManagementTools = scmts.getAll();
                for (SourceCodeManagementTool sourceCodeManagementTool : sourceCodeManagementTools) {
                    writer.save(sourceCodeManagementTool);
                }
            } else if (StaticAnalysisTool.class.isAssignableFrom(clazz)) {
                StaticAnalysisToolService sats = (StaticAnalysisToolService) ic
                        .lookup("java:module/StaticAnalysisToolService");
                List<StaticAnalysisTool> staticAnalysisTools = sats.getAll();
                for (StaticAnalysisTool staticAnalysisTool : staticAnalysisTools) {
                    writer.save(staticAnalysisTool);
                }
            } else if (TestManagementTool.class.isAssignableFrom(clazz)) {
                TestManagementToolService tmts = (TestManagementToolService) ic
                        .lookup("java:module/TestManagementToolService");
                List<TestManagementTool> testManagementTools = tmts.getAll();
                for (TestManagementTool testManagementTool : testManagementTools) {
                    writer.save(testManagementTool);
                }
            } else if (Topic.class.isAssignableFrom(clazz)) {
                TopicService ts = (TopicService) ic.lookup("java:module/TopicService");
                List<Topic> topics = ts.getAll();
                for (Topic topic : topics) {
                    writer.save(topic);
                }
            } else if (SoftwareDevelopmentMethodology.class.isAssignableFrom(clazz)) {
                SoftwareDevelopmentMethodologyService sdms = (SoftwareDevelopmentMethodologyService) ic
                        .lookup("java:module/SoftwareDevelopmentMethodologyService");
                List<SoftwareDevelopmentMethodology> softwareDevelopmentMethodologies = sdms.getAll();
                for (SoftwareDevelopmentMethodology softwareDevelopmentMethodology : softwareDevelopmentMethodologies) {
                    writer.save(softwareDevelopmentMethodology);
                }
            } else if (QModelTagData.class.isAssignableFrom(clazz)) {
                QModelTagDataService qmtds = (QModelTagDataService) ic
                        .lookup("java:module/QModelTagDataService");
                List<QModelTagData> qmodelTagData = qmtds.getAll();
                for (QModelTagData qmtd : qmodelTagData) {
                    writer.save(qmtd);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return model;
}

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Tests if role check is done correctly for authenticated user.
 *
 * @throws Exception//from w  w w  . j a v a2s .  c o  m
 */
@Test
public void testNotAuthorizedClient() throws Exception {
    final Properties env = configureEjbClient(CLIENT_NOT_AUTHORIZED_NAME);
    InitialContext ctx = new InitialContext(env);
    final Hello helloBean = (Hello) ctx.lookup(HELLOBEAN_LOOKUP_NAME);
    try {
        helloBean.sayHelloWorld();
        fail("The EJB call should fail for unauthorized client.");
    } catch (EJBAccessException e) {
        //OK
    }
    ctx.close();
}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.RDBMSDataConnectorBeanDefinitionParser.java

/**
 * Builds a JDBC {@link javax.sql.DataSource} from a ContainerManagedConnection configuration element.
 * //  ww w .j a va  2  s.  com
 * @param pluginId ID of this data connector
 * @param cmc the container managed configuration element
 * 
 * @return the built data source
 */
protected DataSource buildContainerManagedConnection(String pluginId, Element cmc) {
    String jndiResource = cmc.getAttributeNS(null, "resourceName");
    jndiResource = DatatypeHelper.safeTrim(jndiResource);

    Hashtable<String, String> initCtxProps = buildProperties(XMLHelper.getChildElementsByTagNameNS(cmc,
            DataConnectorNamespaceHandler.NAMESPACE, "JNDIConnectionProperty"));
    try {
        InitialContext initCtx = new InitialContext(initCtxProps);
        DataSource dataSource = (DataSource) initCtx.lookup(jndiResource);
        if (dataSource == null) {
            log.error("DataSource " + jndiResource + " did not exist in JNDI directory");
            throw new BeanCreationException("DataSource " + jndiResource + " did not exist in JNDI directory");
        }
        if (log.isDebugEnabled()) {
            log.debug("Retrieved data source for data connector {} from JNDI location {} using properties ",
                    pluginId, initCtxProps);
        }
        return dataSource;
    } catch (NamingException e) {
        log.error("Unable to retrieve data source for data connector " + pluginId + " from JNDI location "
                + jndiResource + " using properties " + initCtxProps, e);
        return null;
    }
}

From source file:org.opentaps.notes.rest.NoteResource.java

/**
 * Handle GET requests./*from   www  . j  ava  2s . co m*/
 * @return JSON representation of the note and http.status SUCCESS_OK
 * @throws NamingException if the service cannot be found
 * @throws ServiceException if an error occur in the service
 */
@Get
public Representation getNote() throws NamingException, ServiceException {
    Messages messages = Messages.getInstance(getRequest());
    String repString = getEmptyJSON();
    String successMessage = "";
    String errorMessage = "";
    String noteId = (String) getRequest().getAttributes().get("noteId");

    JSONUtil.setResponseHttpHeader(getResponse(), "Access-Control-Allow-Origin", "*");

    InitialContext context = new InitialContext();
    if (GenericValidator.isBlankOrNull(noteId)) {
        GetNotesService getNotesService = (GetNotesService) context
                .lookup("osgi:service/org.opentaps.notes.services.GetNotesService");

        if (getNotesService != null) {
            GetNotesServiceInput getNotesServiceInput = new GetNotesServiceInput();
            String fromSeq = (String) getRequest().getAttributes().get("fromSequence");
            String num = (String) getRequest().getAttributes().get("numberOfNotes");
            if (!GenericValidator.isBlankOrNull(fromSeq)) {
                getNotesServiceInput.setFromSequence(Long.valueOf(fromSeq));
            }
            if (!GenericValidator.isBlankOrNull(num)) {
                getNotesServiceInput.setNumberOfNotes(Integer.valueOf(num));
            }
            String order = getQuery().getValues("order");
            if (!GenericValidator.isBlankOrNull(order)) {
                order = order.trim();
                if (order.equalsIgnoreCase("DESC")) {
                    getNotesServiceInput.setOrderDirection(-1);
                }
            }

            List<Note> notes = getNotesService.getNotes(getNotesServiceInput).getNotes();

            if (notes != null) {
                setStatus(Status.SUCCESS_OK);
                repString = getNotesJSON(notes);
            } else {
                errorMessage = messages.getMsg("NoteNotFound");
                setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                Log.logError(errorMessage);
            }

        } else {
            errorMessage = messages.get("GetNoteServiceUnavailable");
            setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
            Log.logError(errorMessage);
        }
    } else {
        GetNoteByIdService getNoteByIdService = (GetNoteByIdService) context
                .lookup("osgi:service/org.opentaps.notes.services.GetNoteByIdService");

        if (getNoteByIdService != null) {
            GetNoteByIdServiceInput getNoteByIdServiceInput = new GetNoteByIdServiceInput();
            getNoteByIdServiceInput.setNoteId(noteId);
            Note note = getNoteByIdService.getNoteById(getNoteByIdServiceInput).getNote();

            if (note != null) {
                setStatus(Status.SUCCESS_OK);
                repString = getNoteJSON(note);
            } else {
                errorMessage = messages.getMsg("NoteNotFound", noteId);
                setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                Log.logError(errorMessage);
            }

        } else {
            errorMessage = messages.get("GetNoteServiceUnavailable");
            setStatus(Status.SERVER_ERROR_SERVICE_UNAVAILABLE);
            Log.logError(errorMessage);
        }
    }

    return new StringRepresentation(JSONUtil.getJSONResult(repString, successMessage, errorMessage),
            MediaType.APPLICATION_JSON);
}

From source file:nl.opengeogroep.dbk.DBKAPI.java

public Connection getConnection() {
    try {/*from  ww w  .j  a va 2 s .  c om*/
        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("Uh oh -- no context!");
        }

        DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/dbk-api");

        if (ds == null) {
            throw new Exception("Data source not found!");
        }
        Connection connection = ds.getConnection();
        return connection;
    } catch (NamingException ex) {
        log.error("naming", ex);
    } catch (Exception ex) {
        log.error("exception", ex);
    }
    return null;
}

From source file:com.flexive.shared.EJBLookup.java

/**
 * Lookup the EJB found under the given Class's name. Uses default flexive naming scheme.
 *
 * @param type        EJB interface class instance
 * @param appName     EJB application name
 * @param environment optional environment for creating the initial context
 * @param <T>         EJB interface type
 * @return a reference to the given EJB/*from  ww w. jav a2 s .  c  o m*/
 */
protected static <T> T getInterface(Class<T> type, String appName, Hashtable<String, String> environment) {
    // Try to obtain interface from the lookup cache
    Object ointerface = ejbCache.get(type.getName());
    if (ointerface != null) {
        return type.cast(ointerface);
    }

    // Cache miss: obtain interface and store it in the cache
    Hashtable<String, String> env;
    synchronized (EJBLookup.class) {
        String name;
        InitialContext ctx = null;
        env = new Hashtable<String, String>(10);
        try {
            if (environment != null)
                env.putAll(environment);
            if (used_strategy == null) {
                appName = discoverStrategy(appName, env, type);
                if (used_strategy != null) {
                    LOG.info("Working lookup strategy: " + used_strategy);
                } else {
                    LOG.error("No working lookup strategy found! Possibly because of pending redeployment.");
                }
            }
            prepareEnvironment(used_strategy, env);
            ctx = new InitialContext(env);
            name = buildName(appName, type);
            ointerface = ctx.lookup(name);
            ejbCache.putIfAbsent(type.getName(), ointerface);

            return type.cast(ointerface);
        } catch (Exception exc) {
            //try one more time with a strategy rediscovery for that bean
            //this can happen if some beans use mapped names and some not
            used_strategy = null;
            try {
                env.clear();
                if (environment != null)
                    env.putAll(environment);
                appName = discoverStrategy(appName, env, type);
                if (used_strategy != null) {
                    prepareEnvironment(used_strategy, env);
                    ctx = new InitialContext(env);
                    name = buildName(appName, type);
                    ointerface = ctx.lookup(name);
                    ejbCache.putIfAbsent(type.getName(), ointerface);
                    return type.cast(ointerface);
                }
            } catch (Exception e) {
                LOG.warn("Attempt to rediscover lookup strategy for " + type + " failed!", e);
            }
            throw new FxLookupException(LOG, exc, "ex.ejb.lookup.failure", type, exc).asRuntimeException();
        } finally {
            if (ctx != null)
                try {
                    ctx.close();
                } catch (NamingException e) {
                    LOG.error("Failed to close context: " + e.getMessage(), e);
                }
        }
    }
}