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.freeciv.servlet.SaveServlet.java

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

    String username = "" + request.getParameter("username");
    if (!p.matcher(username).matches()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid username");
        return;//  w  w w.  j  a  va 2  s  .c  o m
    }

    String savename = "" + request.getParameter("savename");

    if (savename.length() == 0 || username.length() == 0 || savename.length() >= 64
            || username.length() >= 32) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid username or savename.");
        return;
    }

    String relativeWebPath = "/savegames/" + username + ".sav.bz2";
    String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
    File file = new File(absoluteDiskPath);
    if (!file.exists()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Savegame file not found!");
        return;

    } else if (file.length() == 0 || file.length() > 5000000) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid file size of savegame.");
        return;

    }

    InputStream in = new FileInputStream(file);
    byte[] compressedFile = IOUtils.toByteArray(in);
    String encodedFile = new String(Base64.encodeBase64(compressedFile));
    String savegameHash = DigestUtils.shaHex(username + savename + encodedFile);

    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("INSERT INTO savegames VALUES (NULL, ?,?,?)");
        stmt.setString(1, username);
        stmt.setString(2, savename);
        stmt.setString(3, savegameHash);
        stmt.executeUpdate();

    } 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();
            }
    }

    response.getOutputStream().print(encodedFile);
    in.close();

}

From source file:DbServletTrans.java

public void init() throws ServletException {

    Context env = null;

    try {/*from   w  w w . j  av a  2s . c  om*/

        env = (Context) new InitialContext().lookup("java:comp/env");
        pool = (DataSource) env.lookup("jdbc/oracle-8i-athletes");
        if (pool == null)
            throw new ServletException("'oracle-8i-athletes' is an unknown DataSource");

    } catch (NamingException ne) {

        throw new ServletException(ne);

    }

}

From source file:Controllers.ReportController.java

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

    Patient[] patients = null;/* w  w  w.  j a  v  a 2s  .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.wabacus.config.database.datasource.JNDIDataSource.java

public DataSource getDataSource() {
    Context context = null;
    try {//from  w  w  w .  j a v a2s  . co m
        if (ds != null) {
            return ds;
        }
        context = new InitialContext();
        ds = (DataSource) context.lookup(jndi);
        return ds;
    } catch (Exception e) {
        log.error("????", e);
        return null;
    } finally {
        try {
            if (context != null) {
                context.close();
            }
        } catch (Exception ex) {
            log.error("????", ex);
        }
    }

}

From source file:hudson.model.AbstractModelObject.java

/**
 * Checks jndi,environment, hudson environment and system properties for specified key.
 * Property is checked in direct order:/* w w  w  .j  a  va2  s . c  om*/
 * <ol>
 * <li>JNDI ({@link InitialContext#lookup(String)})</li>
 * <li>Hudson environment ({@link EnvVars#masterEnvVars})</li>
 * <li>System properties ({@link System#getProperty(String)})</li>
 * </ol>
 * @param key - the name of the configured property.
 * @return the string value of the configured property, or null if there is no property with that key.
 */
protected String getConfiguredHudsonProperty(String key) {
    if (StringUtils.isNotBlank(key)) {
        String resultValue;
        try {
            InitialContext iniCtxt = new InitialContext();
            Context env = (Context) iniCtxt.lookup("java:comp/env");
            resultValue = StringUtils.trimToNull((String) env.lookup(key));
            if (null != resultValue) {
                return resultValue;
            }
            // look at one more place. See http://issues.hudson-ci.org/browse/HUDSON-1314
            resultValue = StringUtils.trimToNull((String) iniCtxt.lookup(key));
            if (null != resultValue) {
                return resultValue;
            }
        } catch (NamingException e) {
            // ignore
        }

        // look at the env var next
        resultValue = StringUtils.trimToNull(EnvVars.masterEnvVars.get(key));
        if (null != resultValue) {
            return resultValue;
        }

        // finally check the system property
        resultValue = StringUtils.trimToNull(System.getProperty(key));
        if (null != resultValue) {
            return resultValue;
        }
    }
    return null;
}

From source file:DbMetaServlet.java

public void init() throws ServletException {

    Context env = null;

    try {/*  w w w  .ja v  a  2 s  .c  o m*/

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

        pool = (DataSource) env.lookup("jdbc/oracle-8i-athletes");

        if (pool == null)
            throw new ServletException("'oracle-8i-athletes' is an unknown DataSource");

    } catch (NamingException ne) {

        throw new ServletException(ne);

    }
}

From source file:org.mobicents.slee.enabler.rest.client.example.RESTClientEnablerExampleSbb.java

public void setSbbContext(SbbContext context) {
    sbbContext = (SbbContextExt) context;
    this.tracer = this.sbbContext.getTracer("WsClientEnabler");
    // this.timerFacility = sbbContext.getTimerFacility();
    try {/*w w w .j a  v a 2 s .co m*/
        Context myEnv = (Context) new InitialContext().lookup("java:comp/env");
        String twitterConsumerKey = (String) myEnv.lookup("twitter.consumerKey");
        String twitterConsumerSecret = (String) myEnv.lookup("twitter.consumerSecret");
        String twitterAccessToken = (String) myEnv.lookup("twitter.accessToken");
        String twitterAccessTokenKey = (String) myEnv.lookup("twitter.accessTokenKey");
        consumer = new CommonsHttpOAuthConsumer(twitterConsumerKey, twitterConsumerSecret);
        consumer.setTokenWithSecret(twitterAccessToken, twitterAccessTokenKey);
    } catch (NamingException e) {
        tracer.severe("failed to set sbb context", e);
    }
}

From source file:org.artificer.events.jms.JMSEventProducer.java

private Object jndiLookup(String name) throws NamingException {
    Context initContext = new InitialContext();
    try {/*from  www  .j a v  a  2  s. com*/
        Context jndiContext = (Context) initContext.lookup("java:comp/env");
        return jndiContext.lookup(name);
    } catch (NamingException e) {
        // EAP (no namespace)
        Context jndiContext = (Context) initContext.lookup("java:");
        return jndiContext.lookup(name);
    }
}

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

private void sendMail(LDAPUser user, boolean enabled) throws MailException {
    javax.mail.Session session = null;/*from  w ww  .j ava  2 s.c o 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, 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:org.jbpm.bpel.tutorial.task.TaskManager_Impl.java

public void init(Object context) throws ServiceException {
    // jbpm configuration
    ServletEndpointContext endpointContext = (ServletEndpointContext) context;
    String configResource = endpointContext.getServletContext().getInitParameter(JBPM_CONFIG_RESOURCE_PARAM);
    jbpmConfiguration = JbpmConfiguration.getInstance(configResource);

    // task callback service
    try {//from   w  ww  . j  a  v a2s . c o  m
        Context initialContext = new InitialContext();
        taskCallbackService = (Service) initialContext.lookup("java:comp/env/service/TaskCallback");
        initialContext.close();
    } catch (NamingException e) {
        throw new ServiceException("could not retrieve task callback service", e);
    }
}