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: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;/* w  w  w  .ja v a  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.germinus.easyconf.DatasourceURL.java

private synchronized InitialContext getContext() throws NamingException {
    if (ctx == null) {
        ctx = new InitialContext();
    }//from w  w  w. ja va 2  s  .  c  om
    return ctx;
}

From source file:org.fon.documentmanagementsystem.config.AppConfig.java

@Bean
public DataSource dataSource() throws NamingException {
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource) envCtx.lookup("jdbc/nst");
    return ds;// w ww. j  ava  2 s.c  om
}

From source file:com.jaspersoft.jasperserver.war.common.JasperServerUtil.java

public static Connection getJSDatabaseConnection()
        throws ClassNotFoundException, SQLException, NamingException {
    boolean sqlExcpn = false;
    Connection con = null;//from   ww  w .  ja v a 2 s  .com
    try {
        InitialContext cxt = new InitialContext();
        DataSource ds = (DataSource) cxt.lookup(JasperServerConstImpl.getJSDataSrc());
        con = ds.getConnection();
        if (log.isDebugEnabled()) {
            log.debug(
                    "getConnection successful at com.jaspersoft.jasperserver.war.common.JasperServerUtil.getJSDatabaseConnection");
        }
        return con;
    } catch (Exception _ex) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "getConnection FAILED at com.jaspersoft.jasperserver.war.common.JasperServerUtil.getJSDatabaseConnection: "
                            + _ex.getMessage());
        }
        if (log.isErrorEnabled())
            log.error(_ex, _ex);
        sqlExcpn = true;
    } finally {
        if (sqlExcpn) {
            Class.forName(JasperServerConstImpl.getJSConnector());
            con = DriverManager.getConnection(JasperServerConstImpl.getJSUrl(),
                    JasperServerConstImpl.getJSDbUser(), JasperServerConstImpl.getJSDbPasswd());
            return con;
        }
    }
    return con;
}

From source file:com.jobhunt.rest.Login.java

private ApplicationUserRemote lookupApplicationUserManagementRemote() {
    try {//from   www.  j  a va2s  .c o  m
        Context c = new InitialContext();
        return (ApplicationUserRemote) c.lookup("java:global/JobhuntEJB/ApplicationUserBean");
    } catch (NamingException ne) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
        throw new RuntimeException(ne);
    }
}

From source file:com.janrain.utils.BackplaneSystemProps.java

private void load(String paramName, boolean required) {
    String result = System.getProperty(paramName);
    if (StringUtils.isBlank(result)) {
        try {//from   w  ww.j  a va  2 s .c o m
            javax.naming.Context initCtx = new InitialContext();
            result = (String) initCtx.lookup("java:comp/env/" + paramName);
            System.setProperty(paramName, result);
            System.out.println(
                    "Parameter " + paramName + " fetched from context and inserted as system property");
        } catch (Exception e) {
            //continue
            if (required) {
                System.out.println("An error occurred trying to locate required parameter " + paramName + " => "
                        + e.getMessage());
            }
        }
    } else {
        System.out.println("Parameter " + paramName + " exists as a system property");
    }
}

From source file:mx.edu.ittepic.AEEcommerce.servlets.Login.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w  w  w .  java2  s.co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("Cache-Control", "no-store");
    PrintWriter out = response.getWriter();

    CartBean2Remoto ejb = (CartBean2Remoto) request.getSession().getAttribute("ejbsesion");
    String user = request.getParameter("usuario");
    String password = request.getParameter("password");
    System.out.println("password anterior:" + password);
    password = DigestUtils.md5Hex(password);
    System.out.println("password nueva:" + password);
    if (ejb == null) {
        try {
            InitialContext ic = new InitialContext();
            ejb = (CartBean2Remoto) ic.lookup("java:comp/env/ejbs/CartBean2");
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            //password= DigestUtils.md5Hex(password);
            Message m = gson.fromJson(ejb.login(user, password), Message.class);
            if (m.getCode() == 200) {
                request.getSession().setAttribute("ejbsesion", ejb);

            }
            out.print(new GsonBuilder().create().toJson(m));
        } catch (NamingException e) {
            out.print(e.toString());
        }
    }
}

From source file:eu.eubrazilcc.lvl.core.conf.ConfigurationFinder.java

/**
 * Finds available configuration files, searching the different sources in the following order:
 * <ol>//from   w  ww.  j av  a2  s  .c  o m
 *   <li>Application environment;</li>
 *   <li>JNDI context;</li>
 *   <li>Default location in the file-system locally available to the application; and finally</li>
 *   <li>If none of the above works, configuration files are returned from the resources available 
 *       in the application class path.</li>
 * </ol>
 * @return configuration files available to the application
 */
public final static ImmutableList<URL> findConfigurationFiles() {
    ImmutableList<File> configFiles = null;
    // try to read environment variable and retrieve configuration files from the file system
    try {
        final String location = getenv(ENV_HOME_VAR) + "/etc";
        if (isNotBlank(location) && testConfigurationFiles(location, CONFIGURATION_FILENAMES)) {
            configFiles = convertPathListToFiles(location, CONFIGURATION_FILENAMES);
            LOGGER.trace("Environment variable '" + ENV_HOME_VAR + "' found. Configuration files: "
                    + filesToString(configFiles));
        } else {
            LOGGER.trace("Environment variable '" + ENV_HOME_VAR + "' was not found");
        }
    } catch (Exception ignore) {
    }
    // try to read from JNDI context
    if (configFiles == null) {
        try {
            final Context initCtx = new InitialContext();
            final Context envCtx = (Context) initCtx.lookup("java:comp/env");
            final String location = (String) envCtx.lookup(ENV_HOME_VAR) + "/etc";
            if (isNotBlank(location) && testConfigurationFiles(location, CONFIGURATION_FILENAMES)) {
                configFiles = convertPathListToFiles(location, CONFIGURATION_FILENAMES);
                LOGGER.trace("JNDI context variable '" + DEFAULT_LOCATION + "' found. Configuration files: "
                        + filesToString(configFiles));
            } else {
                LOGGER.trace("JNDI context variable '" + DEFAULT_LOCATION + "' was not found");
            }
        } catch (Exception e) {
            LOGGER.trace(
                    "Failed to search for configuration files in JNDI context variable: '" + ENV_HOME_VAR + "'",
                    e);
        }
    }
    // try to retrieve configuration files from the default location
    if (configFiles == null) {
        try {
            final String location = DEFAULT_LOCATION + "/etc";
            if (isNotBlank(location) && testConfigurationFiles(location, CONFIGURATION_FILENAMES)) {
                configFiles = convertPathListToFiles(location, CONFIGURATION_FILENAMES);
                LOGGER.trace("Default location '" + DEFAULT_LOCATION + "' found. Configuration files: "
                        + filesToString(configFiles));
            } else {
                LOGGER.trace("Default location '" + DEFAULT_LOCATION + "' was not found");
            }
        } catch (Exception e) {
            LOGGER.warn("Failed to search for configuration files in default location: " + DEFAULT_LOCATION, e);
        }
    }
    // return default configuration files
    if (configFiles == null) {
        return getDefaultConfiguration();
    } else {
        return from(configFiles).transform(new Function<File, URL>() {
            @Override
            public URL apply(final File file) {
                URL url = null;
                if (file != null) {
                    try {
                        url = file.toURI().toURL();
                    } catch (MalformedURLException e) {
                        LOGGER.warn("Ignoring file: " + file.getName(), e);
                    }
                }
                return url;
            }
        }).filter(notNull()).toList();
    }
}

From source file:com.sun.socialsite.business.MailProvider.java

public MailProvider() throws StartupException {

    String connectionTypeString = Config.getProperty("mail.configurationType");
    if ("properties".equals(connectionTypeString)) {
        type = ConfigurationType.MAIL_PROPERTIES;
    }/*from ww w  .  j  ava 2 s . c  om*/
    jndiName = Config.getProperty("mail.jndi.name");
    mailHostname = Config.getProperty("mail.hostname");
    mailUsername = Config.getProperty("mail.username");
    mailPassword = Config.getProperty("mail.password");
    try {
        String portString = Config.getProperty("mail.port");
        if (portString != null) {
            mailPort = Integer.parseInt(portString);
        }
    } catch (Throwable t) {
        log.warn("mail server port not a valid integer, ignoring");
    }

    // init and connect now so we fail early
    if (type == ConfigurationType.JNDI_NAME) {
        String name = "java:comp/env/" + jndiName;
        try {
            Context ctx = (Context) new InitialContext();
            session = (Session) ctx.lookup(name);
        } catch (NamingException ex) {
            throw new StartupException("ERROR looking up mail-session with JNDI name: " + name);
        }
    } else {
        Properties props = new Properties();
        props.put("mail.smtp.host", mailHostname);
        if (mailUsername != null && mailPassword != null) {
            props.put("mail.smtp.auth", "true");
        }
        if (mailPort != -1) {
            props.put("mail.smtp.port", "" + mailPort);
        }
        session = Session.getDefaultInstance(props, null);
    }

    try {
        Transport transport = getTransport();
        transport.close();
    } catch (Throwable t) {
        throw new StartupException("ERROR connecting to mail server", t);
    }

}

From source file:com.liferay.portal.dao.jdbc.DataSourceFactoryImpl.java

public DataSource initDataSource(Properties properties) throws Exception {
    Properties defaultProperties = PropsUtil.getProperties("jdbc.default.", true);

    PropertiesUtil.merge(defaultProperties, properties);

    properties = defaultProperties;//  w  w w  . j a  v a 2  s.c o m

    String jndiName = properties.getProperty("jndi.name");

    if (Validator.isNotNull(jndiName)) {
        try {
            return (DataSource) JNDIUtil.lookup(new InitialContext(), jndiName);
        } catch (Exception e) {
            _log.error("Unable to lookup " + jndiName, e);
        }
    }

    DataSource dataSource = null;

    String liferayPoolProvider = PropsValues.JDBC_DEFAULT_LIFERAY_POOL_PROVIDER;

    if (liferayPoolProvider.equalsIgnoreCase("c3p0") || liferayPoolProvider.equalsIgnoreCase("c3po")) {

        if (_log.isDebugEnabled()) {
            _log.debug("Initializing C3P0 data source");
        }

        dataSource = initDataSourceC3PO(properties);
    } else if (liferayPoolProvider.equalsIgnoreCase("dbcp")) {
        if (_log.isDebugEnabled()) {
            _log.debug("Initializing DBCP data source");
        }

        dataSource = initDataSourceDBCP(properties);
    } else if (liferayPoolProvider.equalsIgnoreCase("primrose")) {
        if (_log.isDebugEnabled()) {
            _log.debug("Initializing Primrose data source");
        }

        dataSource = initDataSourcePrimrose(properties);
    } else {
        if (_log.isDebugEnabled()) {
            _log.debug("Initializing Tomcat data source");
        }

        dataSource = initDataSourceTomcat(properties);
    }

    if (_log.isDebugEnabled()) {
        _log.debug("Created data source " + dataSource.getClass().getName());

        SortedProperties sortedProperties = new SortedProperties(properties);

        sortedProperties.list(System.out);
    }

    return dataSource;
}