Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

public InitialContext() throws NamingException 

Source Link

Document

Constructs an initial context.

Usage

From source file:net.fender.sql.ManagedConnectionDataSource.java

/**
 * Sub-classes that implement init() should make sure to call super.init()
 * to ensure JNDI publication./* ww  w  . ja va2 s . c o  m*/
 * 
 * @throws Exception
 */
public void init() throws Exception {
    if (jndiName != null) {
        Context context = null;
        try {
            if (jndiProperties == null) {
                context = new InitialContext();
            } else {
                context = new InitialContext(jndiProperties);
            }
            context.rebind(jndiName, this);
        } finally {
            if (context != null) {
                try {
                    context.close();
                } catch (NamingException ignore) {
                    // ignore
                }
            }
        }
    }
}

From source file:org.mobicents.charging.server.ratingengine.http.HTTPClientSbb.java

public void setSbbContext(SbbContext context) {

    this.sbbContext = (SbbContextExt) context;
    this.tracer = sbbContext.getTracer("CS-RF-HTTP");

    try {/*w  w  w .  j ava  2  s.co  m*/
        Context ctx = (Context) new InitialContext().lookup("java:comp/env");

        httpClientAci = (HttpClientActivityContextInterfaceFactory) ctx
                .lookup("slee/resources/http-client/acifactory");

        raSbbInterface = (HttpClientResourceAdaptorSbbInterface) ctx
                .lookup("slee/resources/http-client/sbbinterface");

        httpURLString = (String) ctx.lookup("HTTPURL");
    } catch (NamingException ne) {
        tracer.severe("Could not set SBB context:", ne);
    }

}

From source file:edu.harvard.iq.dvn.core.web.dataaccess.HttpAccessObject.java

public void open() throws IOException {

    StudyFile file = this.getFile();
    DataAccessRequest req = this.getRequest();

    if (req.getParameter("noVarHeader") != null) {
        this.setNoVarHeader(true);
    }/*  www . jav a  2 s.c o m*/

    try {
        this.studyService = (StudyServiceLocal) new InitialContext().lookup("java:comp/env/studyService");
    } catch (Exception e) {
        throw new IOException("Caught exception trying to look up studyService; " + e.getMessage());
    }

    String remoteFileUrl = file.getFileSystemLocation();

    if (remoteFileUrl != null) {
        remoteFileUrl = remoteFileUrl.replaceAll(" ", "+");
        this.setRemoteUrl(remoteFileUrl);
    }

    Boolean zippedStream = false;

    GetMethod method = null;
    int status = 200;

    try {

        // If it's another DVN from which we are getting
        // the file, we need to pass the "noVarHeader"
        // argument along:

        if (remoteFileUrl.matches(".*FileDownload.*")) {
            if (this.noVarHeader()) {
                remoteFileUrl = remoteFileUrl + "&noVarHeader=1";
            } else {
                // and if we are retreiving this tab file in order
                // to convert it to another format locally, we also
                // have to add the noVarHeader flag, otherwise the
                // header will be treated as a line of data!

                if (req.getParameter("format") != null) {
                    remoteFileUrl = remoteFileUrl + "&noVarHeader=1";
                    // TODO -- ? -- do we need to check if this is
                    // a tab-delimited file?
                }
            }
        }

        // See if remote authentication is required;

        String remoteHost = null;
        String regexRemoteHost = "https*://([^/]*)/";
        Pattern patternRemoteHost = Pattern.compile(regexRemoteHost);
        Matcher hostMatcher = patternRemoteHost.matcher(remoteFileUrl);

        if (hostMatcher.find()) {
            remoteHost = hostMatcher.group(1);
        }

        method = new GetMethod(remoteFileUrl);

        String jsessionid = null;
        String remoteAuthHeader = null;

        String remoteAuthType = remoteAuthRequired(remoteHost);

        if (remoteAuthType != null) {
            if (remoteAuthType.equals("httpbasic")) {
                // get the basic HTTP auth credentials
                // (password and username) from the database:

                remoteAuthHeader = getRemoteAuthCredentials(remoteHost);

                if (remoteAuthHeader != null) {
                    method.addRequestHeader("Authorization", remoteAuthHeader);
                }
            } else if (remoteAuthType.equals("dvn")) {
                // Authenticate with the remote DVN:

                jsessionid = dvnRemoteAuth(remoteHost);
            } else if (remoteAuthType.equals("icpsr")) {
                method = null;
                remoteFileUrl = remoteFileUrl.replace("staging", "www");
                remoteFileUrl = remoteFileUrl.replace("/cgi-bin/file", "/cgi-bin/bob/file");
                method = new GetMethod(remoteFileUrl);

                String icpsrCookie = getICPSRcookie(remoteHost, remoteFileUrl);

                if (icpsrCookie != null) {
                    method.addRequestHeader("Cookie", icpsrCookie);
                }

                if (remoteFileUrl.matches(".*gzip.*")) {
                    zippedStream = true;
                }
            }
        }

        if (jsessionid != null) {
            method.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
        }

        // normally, the HTTP client follows redirects
        // automatically, so we need to explicitely tell it
        // not to:

        method.setFollowRedirects(false);
        status = (new HttpClient()).executeMethod(method);

        // The code below is to enable the click through
        // Terms-of-Use Agreement.
        // We are assuming that if they have gotten here,
        // they must have already clicked on all the
        // licensing agreement forms (the terms-of-use
        // agreements are preserved in the study DDIs as
        // they are exported and harvested between DVNs).

        // There are obvious dangers in this approach.
        // We have to trust the DVN harvesting from us to display
        // the agreements in question to their users. But since
        // terms/restrictions cannot be disabled on harvested
        // content through the normal DVN interface, so they
        // would have to go directly to the database to do so,
        // which would constitute an obvious "hacking" of the
        // mechanism, (hopefully) making them and not us liable
        // for it.

        if (status == 302 || status == 301) {
            // this is a redirect.

            // let's see where it is redirecting us; if it looks like
            // DVN TermsOfUse page, we'll "click" and submit the form,
            // then we'll hopefully be able to download the file.
            // If it's no the TOU page, we are just going to try to
            // follow the redirect and hope for the best.
            // (A good real life example is the Census archive: the
            // URLs for their objects that they give us are actually
            // aliases that are 302-redirected to the actual locations)

            String redirectLocation = null;
            String extraCookies = null;

            for (int i = 0; i < method.getResponseHeaders().length; i++) {
                String headerName = method.getResponseHeaders()[i].getName();
                if (headerName.equals("Location")) {
                    redirectLocation = method.getResponseHeaders()[i].getValue();
                }

                String regexCookie = "^([^;]*;)";
                Pattern patternCookie = Pattern.compile(regexCookie);

                if (headerName.equals("Set-Cookie") || headerName.equals("Set-cookie")) {
                    String cookieHeader = method.getResponseHeaders()[i].getValue();
                    Matcher cookieMatcher = patternCookie.matcher(cookieHeader);
                    String regexpJsession = "JSESSIONID=([^;]*);";
                    Pattern patternJsession = Pattern.compile(regexpJsession);
                    Matcher jsessionMatcher = patternJsession.matcher(cookieHeader);
                    if ((jsessionid == null || jsessionid.equals("")) && jsessionMatcher.find()) {
                        jsessionid = jsessionMatcher.group(1);
                    } else if (cookieMatcher.find()) {
                        extraCookies = cookieMatcher.group(1);
                    }
                }
            }

            if (redirectLocation.matches(".*TermsOfUsePage.*")) {

                // Accept the TOU agreement:

                method = remoteAccessTOU(redirectLocation, jsessionid, remoteFileUrl, extraCookies);

                // If everything has worked right
                // we should be redirected to the final
                // download URL, and the method returned is
                // an established download connection;

                if (method != null) {
                    status = method.getStatusCode();
                } else {
                    // but if something went wrong in the progress,
                    // we just report that we couldn't find
                    // the file:
                    status = 404;
                }

            } else {
                // just try again (and hope for the best!)
                method = new GetMethod(redirectLocation);
                status = (new HttpClient()).executeMethod(method);
            }
        }
    } catch (IOException ex) {
        //if (method != null) {
        //    method.releaseConnection();
        //}
        status = 404;
    }

    this.setStatus(status);

    if (status != 200) {
        if (method != null) {
            method.releaseConnection();
        }

        throw new IOException("HTTP access failed; status: " + status);
    }

    InputStream in = null;

    try {
        if (zippedStream) {
            InputStream zipInputStream = method.getResponseBodyAsStream();
            ZipInputStream zin = new ZipInputStream(zipInputStream);
            zin.getNextEntry();

            this.setIsZippedStream(true);

            in = zin;

        } else {
            in = method.getResponseBodyAsStream();
        }

        this.setInputStream(in);

    } catch (IOException ex) {
        this.setStatus(404);
        String errorMessage = "I/O error has occured while attempting to retreive a remote data file: "
                + ex.getMessage()
                + ". Please try again later and if the problem persists, report it to your DVN technical support contact.";
        this.setErrorMessage(errorMessage);

        throw new IOException(
                "I/O error has occured while attempting to retreive a remote data file: " + ex.getMessage());
    }

    this.setResponseHeaders(method.getResponseHeaders());
    this.setHTTPMethod(method);

}

From source file:it.infn.ct.security.actions.ActivateAccount.java

private void sendMail(LDAPUser user, boolean enabled) throws MailException {
    javax.mail.Session session = null;// ww w.  j ava 2  s. c om
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(user.getPreferredMail());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        _log.error("mail bcc: " + mailBCC);
        String ccMail[] = mailBCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.BCC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");
        if (enabled) {
            mailBody = mailBody.replace("_RESULT_", "accepted");
        } else {
            mailBody = mailBody.replace("_RESULT_", "denied");
        }
        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:it.infn.ct.security.actions.ExtendAccount.java

private void sendMail() throws MailException {
    javax.mail.Session session = null;/*w w w  .j  ava 2  s.  co  m*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        LDAPUser user = LDAPUtils.getUser(username);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:org.jtalks.poulpe.model.utils.JndiAwarePropertyPlaceholderConfigurer.java

/**
 * Takes a look at Tomcat JNDI environment ({@code java:/comp/env}) and tries to find the placeholder there. Returns
 * {@code null} if nothing found there, otherwise found value is returned as a string.
 *
 * <p>Method is public, so that it can be used in initialization phase of web app out of Spring IoC. Also it also
 * doesn't use any logging, which is particularly useful when it comes to initializing of the logger itself.</p>
 *
 * @param placeholder the property key to find its values
 * @return the value of the property from Tomcat JNDI or {@code null} if nothing found there
 *///from   ww w  . j  a  v a 2 s . c o m
public static String resolveJndiProperty(String placeholder) {
    try {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup(TOMCAT_CONTEXT_NAME);
        return (String) envContext.lookup(placeholder);
    } catch (NamingException e) {
        return null;
    }
}

From source file:com.dattack.naming.StandaloneJndiTest.java

@Test
public void testLookupInvalidContext() throws NamingException {

    exception.expect(NamingException.class);
    exception.expectMessage(String.format("Invalid subcontext '%s' in context '/'", INVALID_CONTEXT));
    final InitialContext context = new InitialContext();
    final String name = getCompositeName(INVALID_CONTEXT, VALID_OBJECT_NAME);
    final Object obj = context.lookup(name);
    fail(String.format("This test must fail because the name '%s' not exists in context '/' (object: %s)",
            INVALID_CONTEXT, ObjectUtils.toString(obj)));
}

From source file:io.apiman.gateway.engine.policies.auth.JDBCIdentityValidator.java

/**
 * Lookup the datasource from JNDI.// w ww  .  j a  v  a 2s.c  o m
 * @param config
 */
private DataSource lookupDatasource(JDBCIdentitySource config) {
    DataSource ds = null;
    try {
        InitialContext ctx = new InitialContext();
        ds = lookupDS(ctx, config.getDatasourcePath());
        if (ds == null) {
            ds = lookupDS(ctx, "java:comp/env/" + config.getDatasourcePath()); //$NON-NLS-1$
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (ds == null) {
        throw new RuntimeException("Datasource not found: " + config.getDatasourcePath()); //$NON-NLS-1$
    }
    return ds;
}

From source file:io.apiman.manager.test.server.ManagerApiTestServer.java

/**
 * Stuff to do before the server is started.
 *//*from  w w  w .  ja va 2s  .  c o m*/
protected void preStart() {
    System.setProperty("hibernate.hbm2ddl.auto", "create-drop"); //$NON-NLS-1$ //$NON-NLS-2$

    try {
        InitialContext ctx = new InitialContext();
        ensureCtx(ctx, "java:/comp/env"); //$NON-NLS-1$
        ensureCtx(ctx, "java:/comp/env/jdbc"); //$NON-NLS-1$
        ds = createInMemoryDatasource();
        ctx.bind("java:/comp/env/jdbc/ApiManagerDS", ds); //$NON-NLS-1$
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:wtw.ui.GetChartAction.java

private ProjectManager lookupProjectManagerBean() {
    try {//from  ww  w  .  jav  a2  s. c o  m
        Context c = new InitialContext();
        return (ProjectManager) c.lookup("java:global/WorkToWorker/ProjectManager!wtw.biz.ProjectManager");
    } catch (NamingException ne) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
        throw new RuntimeException(ne);
    }
}