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:org.jbpm.bpel.tutorial.shipping.ShippingPT_Impl.java

protected void initJmsObjects() throws NamingException, JMSException {
    Context initialContext = new InitialContext();
    try {//from w  w w.ja  v  a2s . com
        Context environmentContext = (Context) initialContext.lookup("java:comp/env");
        shippingDestination = (Destination) environmentContext.lookup(SHIPPING_DESTINATION_NAME);
        log.debug("Retrieved destination: " + SHIPPING_DESTINATION_NAME);

        ConnectionFactory jmsConnectionFactory = (ConnectionFactory) environmentContext
                .lookup(CONNECTION_FACTORY_NAME);
        jmsConnection = jmsConnectionFactory.createConnection();
        log.debug("Created JMS connection: factory=" + CONNECTION_FACTORY_NAME);
    } finally {
        initialContext.close();
    }
}

From source file:EmailJndiServlet.java

public void init() throws ServletException {

    Context env = null;

    try {//www  .  jav a  2  s  .com

        env = (Context) new InitialContext();

        mailSession = (Session) env.lookup("MyEmail");

        if (mailSession == null)
            throw new ServletException("MyEmail is an unknown JNDI object");

        //close the InitialContext
        env.close();

    } catch (NamingException ne) {

        try {
            env.close();
        } catch (NamingException nex) {
        }

        throw new ServletException(ne);

    }

}

From source file:CiudadesApp.Modelo.Actions.Ciudad_Actions.java

private CiudadFacade lookupCiudadFacadeBean() {
    try {//from  w  w  w. ja  v  a  2s .  c  o m
        Context c = new InitialContext();
        return (CiudadFacade) c
                .lookup("java:global/ForodeCiudades/CiudadFacade!CiudadesApp.Modelo.EJBFacade.CiudadFacade");
    } catch (NamingException ne) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
        throw new RuntimeException(ne);
    }
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {/*from w  ww.  j  a  v a 2s.c om*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

        // wait on the main thread until all sent messages have been received
        while (totalReceived.get() < totalSend) {
            Thread.sleep(1000);
        }
        consumer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:Controllers.ReportController.java

public int fetchDepartmentId(int accountId) {

    int departmentId = 0;

    try {//from w  w  w. ja  v  a 2 s  .c  o  m
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource");
        connection = ds.getConnection();

        PreparedStatement pstmt = connection
                .prepareStatement("SELECT * FROM doctors" + " WHERE accountId = ?;");
        pstmt.setInt(1, accountId);
        ResultSet resultSet = pstmt.executeQuery();

        List<Doctor> appointmentsList = new ArrayList<Doctor>();
        while (resultSet.next()) {
            departmentId = resultSet.getInt("departmentId");
        }
        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 departmentId;
}

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

private void sendMail(String code) throws MailException {
    javax.mail.Session session = null;/*from   www  .  j  a v a2 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 {
        String title = user.getTitle() == null ? "" : user.getTitle();

        mailMsg.setFrom(new InternetAddress(mailFrom));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(user.getPreferredMail(),
                title + user.getGivenname() + " " + user.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", title + " " + user.getGivenname() + " " + user.getSurname());
        mailBody = mailBody.replaceAll("_CODE_", code);

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

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

}

From source file:com.mdmserver.managers.ControllerFacade.java

public void lockPhone(int accountId) throws IOException {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;
    try {/* w w  w . ja  v a2s. c o m*/
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.LOCK_PHONE_CONTROL);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void uninstallApp(int accountId, String appPackageName) {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;
    try {/*from   ww  w  . j a va  2 s . c  o m*/
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.UNINSTALL_APP_CONTROL);
            cClient.setJsonCommandDetails(appPackageName);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:com.techm.cadt.pizzahut.db.PizzaDAO.java

private Connection getConnection() throws Exception {
    if (ds == null) {
        Context initCtx = new InitialContext();
        //Context envCtx = (Context) initCtx.lookup("java:comp/env");
        ds = (DataSource) initCtx.lookup("java:jboss/datasources/pizzahutDS");
    }/*from  w w  w.  j  av a2 s .  c o m*/
    return ds.getConnection();
}

From source file:org.freeciv.servlet.LoadServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    InputStream in = request.getInputStream();

    String encodedFile = IOUtils.toString(in, Charset.forName("UTF-8"));
    byte[] compressedFile = Base64.decodeBase64(encodedFile);

    String savename = "" + request.getParameter("savename");
    String username = "" + request.getParameter("username");
    String savegameHash = DigestUtils.shaHex(username + savename + encodedFile);

    if (!p.matcher(username).matches()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid username");
        return;//from w w  w  .j ava2s.  c  o m
    }

    Connection conn = null;
    try {
        Context env = (Context) (new InitialContext().lookup("java:comp/env"));
        DataSource ds = (DataSource) env.lookup("jdbc/freeciv_mysql");
        conn = ds.getConnection();

        PreparedStatement stmt = conn.prepareStatement(
                "select count(*) from savegames where username = ? and title = ? and digest = ?");
        stmt.setString(1, username);
        stmt.setString(2, savename);
        stmt.setString(3, savegameHash);

        ResultSet rs = stmt.executeQuery();
        if (rs.next()) {
            if (rs.getInt(1) != 1) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid savegame");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid savegame");
            return;
        }

        String relativeWebPath = "/savegames/" + username + ".sav.bz2";
        String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
        File file = new File(absoluteDiskPath);
        FileUtils.writeByteArrayToFile(file, compressedFile);

    } catch (Exception err) {
        err.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Savegame digest failed.");
        return;

    } finally {
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

    in.close();

    response.getOutputStream().print("success");

}