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.jaspersoft.jasperserver.war.action.ReportDataSourceAction.java

public Event testJndiDataSource(RequestContext context) throws Exception {
    ReportDataSourceWrapper wrapper = (ReportDataSourceWrapper) getFormObject(context);
    JndiJdbcReportDataSource ds = (JndiJdbcReportDataSource) wrapper.getReportDataSource();
    Connection conn = null;//from   w  w w .j a v  a2  s .  c  o m
    try {
        Context ctx = new InitialContext();

        if (log.isDebugEnabled()) {
            log.debug(
                    "com.jaspersoft.jasperserver.war.action.ReportDataSourceAction.testJndiDataSource  About to look up DataSource at JNDI location: 'java:comp/env/"
                            + ds.getJndiName() + "' \n");
        }
        DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/" + ds.getJndiName());

        if (log.isDebugEnabled()) {
            log.debug(
                    "com.jaspersoft.jasperserver.war.action.ReportDataSourceAction.testJndiDataSource  look up success: DataSource at JNDI location: 'java:comp/env/"
                            + ds.getJndiName() + "' \n" + " About to do:  DataSource.getConnection \n");
        }
        conn = TibcoDriverManagerImpl.getInstance().unlockConnection(dataSource);
        if (log.isDebugEnabled()) {
            log.debug(
                    "com.jaspersoft.jasperserver.war.action.ReportDataSourceAction.testJndiDataSource  DataSource.getConnection success. \n");
        }

        context.getRequestScope().put("connection.test", Boolean.valueOf(conn != null));
    } catch (Exception e) {
        context.getRequestScope().put("connection.test", Boolean.FALSE);
    } finally {
        if (conn != null)
            conn.close();
    }

    return success();
}

From source file:ch.zhaw.ficore.p2abc.services.user.UserServiceGUI.java

/**
 * This is the second step for the User to obtain a credential from an
 * issuer. This method will display the Identity Selection and direct the
 * User to obtainCredential3/*from  w ww. j  av a 2  s .  co  m*/
 * 
 * @param username
 *            Username (authInfo)
 * @param password
 *            Password (authInfo)
 * @param issuerUrl
 *            URL of the issuance service
 * @param credSpecUid
 *            UID of the CredentialSpecification of the Credential to obtain
 * @return Response
 */
@POST
@Path("/obtainCredential2")
public Response obtainCredential2(@FormParam("un") final String username,
        @FormParam("pw") final String password, @FormParam("is") final String issuerUrl,
        @FormParam("cs") final String credSpecUid, @FormParam("oauth") final String oauth) {
    try {
        // Make an IssuanceRequest
        IssuanceRequest ir = new IssuanceRequest();
        ir.credentialSpecificationUid = credSpecUid;

        if (oauth == null || !oauth.equals("yes")) { // No OAuth.
            AuthInfoSimple authSimple = new AuthInfoSimple();
            authSimple.password = password;
            authSimple.username = username;

            ir.authRequest = new AuthenticationRequest(authSimple);
        } else { // Use OAuth.
            log.info("Using keyrock!");

            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:/comp/env");

            String clientId = (String) envCtx.lookup("cfg/keyrock/clientId");
            String clientSecret = (String) envCtx.lookup("cfg/keyrock/clientSecret");

            String url = "https://account.lab.fiware.org/";

            try {
                String cfgUrl = (String) envCtx.lookup("cfg/keyrock/baseURL");
                if (cfgUrl != null) {
                    url = cfgUrl;
                }
            } catch (RuntimeException e) {

            } catch (Exception e) {

            }

            url += "oauth2/token";

            MultivaluedMap<String, String> params = new MultivaluedMapImpl();
            params.add("grant_type", "password");
            params.add("password", password);
            params.add("username", username);

            String json = RESTHelper.postRequest(url, params, clientId, clientSecret);
            JSONObject obj = (JSONObject) JSONValue.parse(json);

            String token = (String) obj.get("access_token");

            ir.authRequest = new AuthenticationRequest(new AuthInfoKeyrock(token));
        }

        log.warn("issuerUrl: " + issuerUrl);
        log.info("authReq is " + ir.authRequest.authInfo.getClass().getCanonicalName());

        IssuanceMessageAndBoolean issuanceMessageAndBoolean = (IssuanceMessageAndBoolean) RESTHelper
                .postRequest(issuerUrl + "/issuanceRequest", RESTHelper.toXML(IssuanceRequest.class, ir),
                        IssuanceMessageAndBoolean.class);

        IssuanceMessage firstIssuanceMessage = issuanceMessageAndBoolean.getIssuanceMessage();

        IssuanceReturn issuanceReturn = (IssuanceReturn) RESTHelper.postRequest(
                ServicesConfiguration.getUserServiceURL() + "issuanceProtocolStep",
                RESTHelper.toXML(IssuanceMessage.class, of.createIssuanceMessage(firstIssuanceMessage)),
                IssuanceReturn.class);

        putURL(issuanceReturn.uia.uiContext.toString(), issuerUrl);

        return issuanceArguments(ObjectFactoryReturnTypes.wrap(issuanceReturn));
    } catch (RuntimeException e) {
        log.catching(e);
        return log.exit(Response.status(Response.Status.BAD_REQUEST)
                .entity(UserGUI.errorPage(ExceptionDumper.dumpExceptionStr(e, log), request).write()).build());
    }

    catch (Exception e) {
        log.catching(e);
        return log.exit(Response.status(Response.Status.BAD_REQUEST)
                .entity(UserGUI.errorPage(ExceptionDumper.dumpExceptionStr(e, log), request).write()).build());
    }
}

From source file:ch.zhaw.ficore.p2abc.services.user.UserServiceGUI.java

/**
 * This is the entry point for the User to obtain a credential from an
 * issuer. This method will display a webpage asking for the required data
 * and will direct the User to obtainCredential2
 * /*from   ww w  .  j  a v a 2  s .com*/
 * @return Response
 */
@GET
@Path("/obtainCredential/")
public Response obtainCredential() {
    try {
        Html html = UserGUI.getHtmlPramble("Obtain Credential [1]", request);
        Div mainDiv = new Div().setCSSClass("mainDiv");
        html.appendChild(UserGUI.getBody(mainDiv));
        mainDiv.appendChild(new H2().appendChild(new Text("Obtain Credential")));
        mainDiv.appendChild(new P().setCSSClass("info")
                .appendChild(new Text("Please enter the information required to obtain the credential. "
                        + "If the the Issuer field is blank please add an alias for an URL first via the Profile page.")));
        Form f = new Form("./obtainCredential2");
        f.setMethod("post");

        Table tbl = new Table();
        Tr row = null;
        f.appendChild(tbl);

        row = new Tr();
        row.appendChild(new Td().appendChild(new Label().appendChild(new Text("Username:"))));
        row.appendChild(new Td().appendChild(new Input().setType("text").setName("un")));
        tbl.appendChild(row);

        row = new Tr();
        row.appendChild(new Td().appendChild(new Label().appendChild(new Text("Password:"))));
        row.appendChild(new Td().appendChild(new Input().setType("password").setName("pw")));
        tbl.appendChild(row);

        row = new Tr();
        row.appendChild(new Td().appendChild(new Label().appendChild(new Text("Issuer:"))));
        // row.appendChild(new Td().appendChild(new Input().setType("text")
        // .setName("is")));
        Select s = new Select().setName("is");

        row.appendChild(new Td().appendChild(s));
        // .setName("is")));

        List<String> keys = urlStorage.keysAsStrings();
        List<byte[]> values = urlStorage.values();
        List<String> urls = new ArrayList<String>();

        for (byte[] b : values) {
            urls.add((String) SerializationUtils.deserialize(b));
        }

        for (int i = 0; i < keys.size(); i++) {
            Option o = new Option().appendChild(new Text(keys.get(i))).setValue(urls.get(i));
            s.appendChild(o);
        }

        tbl.appendChild(row);

        row = new Tr();
        row.appendChild(new Td().appendChild(new Label().appendChild(new Text("Credential specification:"))));
        Select sel = new Select().setName("cs");
        row.appendChild(new Td().appendChild(sel));
        tbl.appendChild(row);

        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:/comp/env");

        boolean enabled = (Boolean) envCtx.lookup("cfg/userGui/keyrockEnabled");

        String enableString = enabled ? "yes" : "no";
        f.appendChild(new Input().setType("hidden").setName("oauth").setValue(enableString));

        f.appendChild(new Input().setType("submit").setValue("Obtain"));

        mainDiv.appendChild(f);

        Settings settings = (Settings) RESTHelper
                .getRequest(ServicesConfiguration.getUserServiceURL() + "getSettings/", Settings.class);

        List<CredentialSpecification> credSpecs = settings.credentialSpecifications;

        for (CredentialSpecification credSpec : credSpecs) {
            URI uri = credSpec.getSpecificationUID();
            sel.appendChild(new Option().appendChild(new Text(uri.toString())));
        }

        return Response.ok(html.write()).build();
    } catch (Exception e) {
        log.catching(e);
        return log.exit(Response.status(Response.Status.BAD_REQUEST)
                .entity(UserGUI.errorPage(ExceptionDumper.dumpExceptionStr(e, log), request).write()).build());
    }
}

From source file:m.dekmak.Database.java

public String getContextValue(String param) throws NamingException {
    // Get the base naming context
    Context env = (Context) new InitialContext().lookup("java:comp/env");
    // Get a single value
    String dbhost = (String) env.lookup(param);
    return dbhost;
}

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

@Transactional(propagation = Propagation.REQUIRED)
public Util.PropertyList getMondrianConnectProperties(ExecutionContext context, MondrianConnection conn,
        ReportDataSource dataSource) {//from w w w  . ja v  a2  s. c o m

    // assemble a mondrian connection PropertyList
    if (dataSource == null) {
        dataSource = (ReportDataSource) dereference(context, conn.getDataSource());
        if (dataSource == null) {
            throw new JSException(
                    "null data source on dereference of mondrian connection " + conn.getURIString() + " for "
                            + (conn.getDataSource().isLocal()
                                    ? "local: " + conn.getDataSource().getLocalResource().getURIString()
                                    : conn.getDataSource().getReferenceURI()));
        }
    }

    Util.PropertyList connectProps = new Util.PropertyList();

    connectProps.put(RolapConnectionProperties.Provider.toString(), "mondrian");
    connectProps.put(OLAP4J_DRIVER, "mondrian.olap4j.MondrianOlap4jDriver");
    connectProps.put(OLAP4J_URL_PREFIX, "jdbc:mondrian:");
    connectProps.put(RolapConnectionProperties.Locale.toString(), LocaleContextHolder.getLocale().toString());

    /*
     * The URI here has to be an "internal" representation (in multi-tenancy terms)
     * so that the Mondrian schema cache has the right key to flush.
     */
    String transformedUri = repositoryCatalogLocator.locate(transformUri(conn.getSchema().getReferenceURI()));

    transformedUri = connectProps.put(RolapConnectionProperties.Catalog.toString(), transformedUri);

    // writing a DynamicSchemaProcessor looks like the way to update schema
    // on the fly
    //  connectProps.put(RolapConnectionProperties.DynamicSchemaProcessor
    //      .toString(), "NONE");

    // To cope with changes in the underlying schema
    connectProps.put(RolapConnectionProperties.UseContentChecksum.toString(), useContentChecksum);

    if (dataSource instanceof JdbcReportDataSource) {
        JdbcReportDataSource jdbcDataSource = (JdbcReportDataSource) dataSource;
        connectProps.put(RolapConnectionProperties.Jdbc.toString(), jdbcDataSource.getConnectionUrl());
        String driverClassName = jdbcDataSource.getDriverClass();
        connectProps.put(RolapConnectionProperties.JdbcDrivers.toString(), driverClassName);

        try {
            // load the driver- may not have been done, mondrian expects it
            log.info("Loading jdbc driver: " + driverClassName);
            jdbcDriverService.register(driverClassName);
        } catch (ClassNotFoundException cnfe) {
            log.error("CANNOT LOAD DRIVER: " + driverClassName);
            throw new JSException(cnfe);
        } catch (Exception e) {
            throw new JSException(e);
        }

        if (jdbcDataSource.getUsername() != null && jdbcDataSource.getUsername().trim().length() > 0) {
            connectProps.put(RolapConnectionProperties.JdbcUser.toString(), jdbcDataSource.getUsername());
        }

        if (jdbcDataSource.getPassword() != null && jdbcDataSource.getPassword().trim().length() > 0) {
            connectProps.put(RolapConnectionProperties.JdbcPassword.toString(), jdbcDataSource.getPassword());
        }

    } else {
        // We have a JNDI data source
        JndiJdbcReportDataSource jndiDataSource = (JndiJdbcReportDataSource) dataSource;

        String jndiURI = "";

        if (jndiDataSource.getJndiName() != null && !jndiDataSource.getJndiName().startsWith("java:")) {
            try {
                Context ctx = new InitialContext();
                ctx.lookup("java:comp/env/" + jndiDataSource.getJndiName());
                jndiURI = "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(jndiDataSource.getJndiName());
                    jndiURI = "";

                } catch (NamingException ex) {

                }
            }
        }
        jndiURI = jndiURI + jndiDataSource.getJndiName();

        connectProps.put(RolapConnectionProperties.DataSource.toString(), jndiURI);
    }

    if (log.isDebugEnabled()) {
        log.debug("connection properties prepared: " + connectProps);
    }

    // TODO get from web context and metadata
    // + "RoleXX='California manager';";
    return connectProps;
}

From source file:org.jboss.ejb3.locator.client.Ejb3ServiceLocatorImpl.java

/**
 * Fetches the object bound at the specified JNDI Address from the JNDI Host
 * with the specified ID//from   w  w  w.j a v  a  2 s. c om
 * 
 * @param hostId
 * @param jndiName
 * @return
 * @throws NameNotFoundException
 *             If the specified JNDI Address is not a valid binding for the
 *             specified host
 */
public Object getObject(String hostId, String jndiName) throws NameNotFoundException {

    // Initialize
    Context context = null;

    // Obtain context
    context = this.contexts.get(hostId);

    // Obtain JNDI Host
    JndiHost host = null;
    try {
        host = this.getJndiHost(hostId);
    } catch (JndiHostNotFoundException jhnfe) {
        throw new IllegalStateException(jhnfe);
    }

    // Obtain JNP URL for logging
    String jnpUrl = this.constructJnpUrl(host);

    // Ensure defined
    if (context == null) {
        throw new ServiceLocatorException(
                "A JNDI Host with ID \"" + hostId + "\" has not been defined in configuration; cannot lookup \""
                        + jndiName + "\" from " + jnpUrl);
    }

    // Lookup
    try {
        logger.debug("Performing JNDI Lookup of \"" + jndiName + "\" on " + jnpUrl);
        return context.lookup(jndiName);
    } catch (NamingException e) {
        // Wrap as runtime error
        throw new ServiceLocatorException(e);
    }

}

From source file:com.mirth.connect.connectors.jms.JmsDispatcher.java

public Destination getDestination(JmsDispatcherProperties jmsDispatcherProperties, JmsSession jmsSession,
        Context initialContext) throws Exception {
    try {/*from ww  w  .j a v a  2  s.c o  m*/
        String destinationName = jmsDispatcherProperties.getDestinationName();
        if (destinationName.equals(jmsSession.getDestinationName())) {
            /*
             * Only lookup/create a new destination object if the destination name has changed
             * since the last time this method was called.
             */
            return jmsSession.getDestination();
        }

        jmsSession.setDestinationName(destinationName);

        if (jmsDispatcherProperties.isUseJndi()) {
            synchronized (initialContext) {
                jmsSession.setDestination((Destination) initialContext.lookup(destinationName));
            }
        } else if (jmsDispatcherProperties.isTopic()) {
            jmsSession.setDestination(jmsSession.getSession().createTopic(destinationName));
            logger.debug("Connected to topic: " + destinationName);
        } else {
            jmsSession.setDestination(jmsSession.getSession().createQueue(destinationName));
            logger.debug("Connected to queue: " + destinationName);
        }

        return jmsSession.getDestination();
    } catch (Exception e) {
        jmsSession.setDestination(null);
        jmsSession.setDestinationName(null);

        throw e;
    }
}

From source file:jdao.JDAO.java

public static DataSource lookupDataSourceFromJndi(Context ctx, String name) throws Exception {
    return (DataSource) ctx.lookup(name);
}

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

/**
 * Creates a new MailManager object.//  ww  w.  jav  a 2  s  . c o  m
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NamingException
 */
public FilesManager(HashMap mail)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, NamingException {
    super();

    String messageFactory = (String) mail.get(Constants.MESSAGES_FACTORY);

    if ((messageFactory != null) && !messageFactory.trim().equals("")) {
        Class clazz = null;
        clazz = Class.forName(messageFactory.trim());
        this.messageable = (Messageable) clazz.newInstance();
        this.messageable.setProperties(mail);
    }

    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.folderChat = (String) mail.get(Constants.MAIL_FOLDER_CHAT);
    this.folderFiles = (String) mail.get(Constants.MAIL_FOLDER_FILES);
    this.quoteSizeAlert = Integer.valueOf((String) mail.get(Constants.MAIL_QUOTE_SIZE_ALERT)).intValue();

    tidy.setUpperCaseTags(true);
    tidy.setInputEncoding(Charset.defaultCharset().displayName());
    tidy.setOutputEncoding(Charset.defaultCharset().displayName());
    tidy.setMakeBare(true);
    tidy.setMakeClean(true);
    tidy.setShowWarnings(false);
    tidy.setErrout(new PrintWriter(new NullWriter()));
    tidy.setWord2000(true);
    tidy.setDropProprietaryAttributes(true);
    tidy.setFixBackslash(true);
    tidy.setXHTML(true);

    //tidy.setXmlOut(true);
    tidy.setWrapSection(true);
    tidy.setWrapScriptlets(true);
    tidy.setWrapPhp(true);
    tidy.setQuiet(true);
    tidy.setBreakBeforeBR(true);
    tidy.setEscapeCdata(true);
    tidy.setForceOutput(true);
    tidy.setHideComments(false);
    tidy.setPrintBodyOnly(true);
    tidy.setTidyMark(false);

    Map options = ApplicationConstants.options;

    Context ctx = new InitialContext();

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

From source file:blueprint.sdk.experimental.florist.db.ConnectionListener.java

public void contextInitialized(final ServletContextEvent arg0) {
    Properties poolProp = new Properties();
    try {//from  w w w .  ja v  a 2  s .c om
        Context initContext = new InitialContext();

        // load pool properties file (from class path)
        poolProp.load(ConnectionListener.class.getResourceAsStream("/jdbc_pools.properties"));
        StringTokenizer stk = new StringTokenizer(poolProp.getProperty("PROP_LIST"));

        // process all properties files list in pool properties (from class
        // path)
        while (stk.hasMoreTokens()) {
            try {
                String propName = stk.nextToken();
                LOGGER.info(this, "loading jdbc properties - " + propName);

                Properties prop = new Properties();
                prop.load(ConnectionListener.class.getResourceAsStream(propName));

                DataSource dsr;
                if (prop.containsKey("JNDI_NAME")) {
                    // lookup DataSource from JNDI
                    // FIXME JNDI support is not tested yet. SPI or Factory
                    // is needed here.
                    LOGGER.warn(this, "JNDI DataSource support needs more hands on!");
                    dsr = (DataSource) initContext.lookup(prop.getProperty("JNDI_NAME"));
                } else {
                    // create new BasicDataSource
                    BasicDataSource bds = new BasicDataSource();
                    bds.setMaxActive(Integer.parseInt(prop.getProperty("MAX_ACTIVE")));
                    bds.setMaxIdle(Integer.parseInt(prop.getProperty("MAX_IDLE")));
                    bds.setMaxWait(Integer.parseInt(prop.getProperty("MAX_WAIT")));
                    bds.setInitialSize(Integer.parseInt(prop.getProperty("INITIAL")));
                    bds.setDriverClassName(prop.getProperty("CLASS_NAME"));
                    bds.setUrl(prop.getProperty("URL"));
                    bds.setUsername(prop.getProperty("USER"));
                    bds.setPassword(prop.getProperty("PASSWORD"));
                    bds.setValidationQuery(prop.getProperty("VALIDATION"));
                    dsr = bds;
                }
                boundDsrs.put(prop.getProperty("POOL_NAME"), dsr);
                initContext.bind(prop.getProperty("POOL_NAME"), dsr);
            } catch (RuntimeException e) {
                LOGGER.trace(e);
            }
        }
    } catch (IOException | NamingException e) {
        LOGGER.trace(e);
    }
}