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:com.netspective.axiom.connection.JndiConnectionProvider.java

public JndiConnectionProvider() throws NamingException {
    initialContext = new InitialContext();
    rootContext = initialContext;
}

From source file:com.heliumv.factory.BaseCall.java

private Context getInitialContext() throws NamingException {
    Context env = (Context) new InitialContext().lookup("java:comp/env");
    String namingFactory = (String) env.lookup(Context.INITIAL_CONTEXT_FACTORY);
    String urlProvider = (String) env.lookup(Context.PROVIDER_URL);

    log.debug("namingFactory = {" + namingFactory + "}");
    log.debug("urlProvider = {" + urlProvider + "}");

    Hashtable<String, String> environment = new Hashtable<String, String>();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);
    environment.put(Context.PROVIDER_URL, urlProvider);
    return new InitialContext(environment);
}

From source file:JNDIUtil.java

public static Properties getDefaultProperties() {
    Properties defaultProperties = new Properties();
    try {/*from   w w w . j a  v  a 2 s . c  o m*/
        InitialContext context = new InitialContext();
        defaultProperties.putAll(context.getEnvironment());
    } catch (Exception e) {
        System.out.println("Unexpected exception when trying to retrieve default naming context." + e);
    }
    return defaultProperties;
}

From source file:Controllers.AppointmentController.java

/**
 *
 * @param appointment/*from  www.  ja  v  a 2  s . c o  m*/
 * @param result
 * @param modelMap
 * @return 
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public String AddApp(@ModelAttribute("appointment") Appointment appointment, BindingResult result,
        ModelMap modelMap) {

    int accountId = appointment.getAccountId();
    int departmentId = appointment.getDepartmentId();
    Date fulldate = appointment.getDate();
    java.sql.Date date = new java.sql.Date(fulldate.getTime());
    String message = appointment.getMessage();

    String content = "";

    if (departmentId == 0 || date == null) {
        content = "Sorry, you didn't fill some of fields. Please, try again.";
        modelMap.addAttribute("content", content);
        return "appointmentConfirmation";
    }
    Date m = null;
    int appointmentcounter = 0;
    Appointment[] appointments = fetchAppointments();
    for (int i = 0; i < appointments.length; i++) {
        if (appointments[i].getDate().compareTo(date) == 0 && appointments[i].getDepartmentId() == departmentId)
            appointmentcounter++;
    }
    if (appointmentcounter >= 2) {
        content = "Sorry, there is no any free spaces for your appointment on " + date + " to visit "
                + findDepartmentName(departmentId) + ". Please, select another day.<br>";
        modelMap.addAttribute("content", content);
        return "appointmentConfirmation";
    }

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        Statement stmt = connection.createStatement();
        PreparedStatement pstmt;

        pstmt = connection.prepareStatement(
                "INSERT INTO appointments (accountId, departmentId, date, message)\n" + "VALUES (?,?,?,?);");
        pstmt.setInt(1, accountId);
        pstmt.setInt(2, departmentId);
        pstmt.setDate(3, date);
        pstmt.setString(4, message);
        pstmt.execute();

        content = "<h4>Appontment have been setted.</h4><br><h5>Please, check information below.</h5><br>"
                + "<table>" + "<tr><td>Seleted department:</td><td>" + findDepartmentName(departmentId)
                + "</td></tr>" + "<tr><td>Seleted date:</td><td>"
                + new SimpleDateFormat("yyyy-MM-dd").format(date) + "</td></tr>"
                + "<tr><td>Attached message</td><td>" + message + "</td></tr>" + "</table>";

        stmt.close();
    } catch (NamingException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    modelMap.addAttribute("content", content);

    return "appointmentConfirmation";
}

From source file:eu.agilejava.spring4.config.ApplicationConfig.java

/**
 * Get the CDI Manager from initial context.
 * @return the cdi manager/*from w  ww  .  ja  va 2s. c o m*/
 */
private BeanManager getCDIBeanManager() {
    try {
        InitialContext initialContext = new InitialContext();
        return (BeanManager) initialContext.lookup("java:comp/BeanManager");
    } catch (NamingException e) {
        LOGGER.severe(() -> "Could not look up initialcontext: " + e.getMessage());
        return null;
    }
}

From source file:Controllers.ReportController.java

public Patient[] fetchAppointments(int departmentId, java.sql.Date date) {

    Patient[] patients = null;/* w  w  w  .  ja v a2 s.  c o m*/

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        PreparedStatement pstmt = connection.prepareStatement("SELECT appointments.message, \n"
                + "accounts.firstName, accounts.lastName FROM appointments INNER JOIN accounts ON appointments.accountId = accounts.accountId \n"
                + "WHERE appointments.departmentId = ? AND appointments.date = ?;");

        pstmt.setInt(1, departmentId);
        pstmt.setDate(2, date);

        ResultSet resultSet = pstmt.executeQuery();

        List<Patient> appointmentsList = new ArrayList<Patient>();
        while (resultSet.next()) {
            Patient patient = new Patient();
            patient.setPatientFirstName(resultSet.getString("firstName"));
            patient.setPatientSecondName(resultSet.getString("lastName"));
            patient.setPatientClaim(resultSet.getString("message"));

            appointmentsList.add(patient);
        }

        patients = new Patient[appointmentsList.size()];
        patients = appointmentsList.toArray(patients);

        pstmt.close();

    } catch (NamingException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return patients;
}

From source file:com.duroty.task.POP3ServiceTask.java

/**
 * @throws NamingException//  w  ww. j av a  2 s .com
 * @throws IOException
 *
 */
public POP3ServiceTask(int poolSize) throws NamingException, IOException {
    super();

    this.poolSize = poolSize;

    Map options = ApplicationConstants.options;

    try {
        ctx = new InitialContext();

        HashMap mail = (HashMap) ctx.lookup((String) options.get(Constants.MAIL_CONFIG));

        this.durotyMailFactory = (String) mail.get(Constants.DUROTY_MAIL_FACTOTY);
        this.hibernateSessionFactory = (String) mail.get(Constants.HIBERNATE_SESSION_FACTORY);

        //this.pop3Inbox = (String) mail.get(Constants.MAIL_SERVER_INBOX);
        this.defaultMessagesPath = (String) mail.get(Constants.MAIL_MESSAGES_PATH);

        String tempDir = System.getProperty("java.io.tmpdir");

        if (!tempDir.endsWith(File.separator)) {
            tempDir = tempDir + File.separator;
        }

        FileUtilities.deleteMotLocks(new File(tempDir));
        FileUtilities.deleteLuceneLocks(new File(tempDir));
    } finally {
    }
}

From source file:com.ibm.bluemix.mobilestarterkit.service.ServiceAPI.java

private void saveLog(String PAGE_ADDRESS, String IP_ADDRESS, String BROWSER) {
    System.out.println("saveLog () ");
    /*/*from  www  .  j  a  v a 2  s .  c  o  m*/
     * Look up DB for dashDB to connect with VCAP_Service
     * 
     */
    String lookupName = null;
    try {
        com.ibm.json.java.JSONObject vcap = getVcapServices();
        if (vcap.get("dashDB") != null) {
            com.ibm.json.java.JSONObject dashDB0 = (com.ibm.json.java.JSONObject) ((com.ibm.json.java.JSONArray) vcap
                    .get("dashDB")).get(0);
            String luName = (String) dashDB0.get("name");
            if (luName != null) {
                lookupName = "jdbc/" + luName;
            }
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    DataSource dataSource = null;

    try {
        javax.naming.Context ctx = new InitialContext();
        if (lookupName != null) {
            dataSource = (DataSource) ctx.lookup(lookupName);
        } else {
            dataSource = (DataSource) ctx.lookup("jdbc/dashDB-microsite");
        }

    } catch (NamingException e) {
        e.printStackTrace();
    }

    /*
     * Check if USER_LOG table exists in DashDB
     * 
     */

    try {
        Connection conn = dataSource.getConnection();
        PreparedStatement stmt = conn
                .prepareStatement("SELECT TABNAME,TABSCHEMA FROM SYSCAT.TABLES where TABNAME = 'USER_LOG'");
        ResultSet rs = stmt.executeQuery();

        boolean tableExist = false;

        if (rs != null) {
            while (rs.next()) {
                System.out.println("table name : " + rs.getString(1));
                if (rs.getString(1).equals("USER_LOG")) {
                    tableExist = true;
                }
            }
        } else {
            tableExist = false;
        }

        /*
         * If there is no table, create it.
         * 
         */
        if (!tableExist) {
            System.out.println("table NOT exist ");

            Statement crtStatement = conn.createStatement();
            String crtSql = "CREATE TABLE USER_LOG(PAGE_ADDRESS VARCHAR (200), IP_ADDRESS VARCHAR (200), BROWSER CHAR (200), ACCESS_TIME TIMESTAMP) organize by row";
            crtStatement.executeUpdate(crtSql);

            System.out.println("Create done!!");
        }

        /*
         * Insert Log information
         * 
         */
        Statement insertStatement = conn.createStatement();
        String insertSql = "INSERT INTO USER_LOG (PAGE_ADDRESS, IP_ADDRESS, BROWSER, ACCESS_TIME) VALUES ('"
                + PAGE_ADDRESS + "','" + IP_ADDRESS + "','" + BROWSER + "',  CURRENT TIMESTAMP)";
        insertStatement.executeUpdate(insertSql);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eu.uqasar.web.dashboard.widget.datadeviation.DataDeviationSettingsPanel.java

public DataDeviationSettingsPanel(String id, IModel<DataDeviationWidget> model) {
    super(id, model);

    setOutputMarkupPlaceholderTag(true);

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

    // DropDown select for Projects
    TreeNodeService treeNodeService = null;
    try {//from ww  w . j  a  v a2 s . c  o  m
        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();
    }

    //Form and WMCs
    final Form<Widget> form = new Form<>("form");
    wmcGeneral = newWebMarkupContainer("wmcGeneral");
    form.add(wmcGeneral);

    //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);
            int noOfObjs = OBJS.size();
            int noOfIndis = INDIS.size();

            if (index + 1 == 1 && noOfObjs > 0) {
                buffer.append("<optgroup label='Quality Objectives'></optgroup>");
            }
            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);
    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);
                DataDeviationWidgetView widgetView = (DataDeviationWidgetView) widgetPanel.getWidgetView();
                target.add(widgetView);
                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:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

/**
  * @see junit.framework.TestCase#setUp()
  *//*from   www . j  a v a2s .  c o m*/
@Override
protected void setUp() throws Exception {
    XMLConfig.setBaseConfigPath(getClass().getClassLoader().getResource(".").getPath());
    ServerSetup SMTP = new ServerSetup(11025, null, ServerSetup.PROTOCOL_SMTP);
    ServerSetup POP3 = new ServerSetup(11110, null, ServerSetup.PROTOCOL_POP3);
    server = new GreenMail(new ServerSetup[] { SMTP, POP3 });
    server.setUser("test@gv.com", "password");
    server.setUser("test1@gv.com", "password");
    server.setUser("test2@gv.com", "password");
    server.setUser("test3@gv.com", "password");
    server.start();

    context = new InitialContext();
}