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:com.mirth.connect.connectors.jms.JmsDispatcher.java

/**
 * Get the JmsConnection from the cache if one exists, otherwise a new one will be created. This
 * method is synchronized otherwise multiple threads may try to create the same connection
 * simultaneously. Only one thread is allowed to create a connection at a time. Subsequent
 * threads will then retrieve the connection that was already created.
 *///from  w  w w .j  av  a  2 s.  c  o m
private synchronized JmsConnection getJmsConnection(JmsDispatcherProperties jmsDispatcherProperties,
        String connectionKey, Long dispatcherId, boolean replace) throws Exception {
    // If the connection needs to be replaced, clean up the old connection and remove it from the cache.
    if (replace) {
        closeJmsConnectionQuietly(connectionKey);
    }

    JmsConnection jmsConnection = jmsConnections.get(connectionKey);

    if (jmsConnection == null) {
        if (jmsConnections.size() >= maxConnections) {
            throw new Exception("Cannot create new connection. Maximum number (" + maxConnections
                    + ") of cached connections reached.");
        }

        Context initialContext = null;
        ConnectionFactory connectionFactory = null;
        Connection connection = null;

        Map<String, String> connectionProperties = jmsDispatcherProperties.getConnectionProperties();
        if (jmsDispatcherProperties.isUseJndi()) {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

            try {
                MirthContextFactory contextFactory = contextFactoryController
                        .getContextFactory(getResourceIds());
                Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

                Hashtable<String, Object> env = new Hashtable<String, Object>();
                env.put(Context.PROVIDER_URL, jmsDispatcherProperties.getJndiProviderUrl());
                env.put(Context.INITIAL_CONTEXT_FACTORY,
                        jmsDispatcherProperties.getJndiInitialContextFactory());
                env.put(Context.SECURITY_PRINCIPAL, jmsDispatcherProperties.getUsername());
                env.put(Context.SECURITY_CREDENTIALS, jmsDispatcherProperties.getPassword());

                initialContext = new InitialContext(env);

                String connectionFactoryName = jmsDispatcherProperties.getJndiConnectionFactoryName();
                connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName);
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
        } else {
            String className = jmsDispatcherProperties.getConnectionFactoryClass();

            MirthContextFactory contextFactory = contextFactoryController.getContextFactory(getResourceIds());
            connectionFactory = (ConnectionFactory) Class
                    .forName(className, true, contextFactory.getApplicationClassLoader()).newInstance();
        }

        BeanUtil.setProperties(connectionFactory, connectionProperties);

        try {
            logger.debug("Creating JMS connection and session");
            connection = connectionFactory.createConnection(jmsDispatcherProperties.getUsername(),
                    jmsDispatcherProperties.getPassword());
            String clientId = jmsDispatcherProperties.getClientId();

            if (!clientId.isEmpty()) {
                connection.setClientID(clientId);
            }

            logger.debug("Starting JMS connection");
            connection.start();
        } catch (JMSException e) {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close JMS connection.", e);
            }

            try {
                if (initialContext != null) {
                    initialContext.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close initial context.", e);
            }

            throw e;
        }

        // Create the new JmsConnection and add it to the cache.
        jmsConnection = new JmsConnection(connection, initialContext);
        jmsConnections.put(connectionKey, jmsConnection);
    }

    return jmsConnection;
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccDb2LUW.CFAccDb2LUWSchema.java

public boolean connect() {
    final String S_ProcName = "connect";
    if (cnx != null) {
        return (false);
    }/*from  www.  j  av a 2  s.  c  o m*/

    if (configuration != null) {
        try {
            Class.forName("com.ibm.db2.jcc.DB2Driver");
        } catch (ClassNotFoundException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), "connect",
                    "Could not load IBM DB/2 LUW 10.5 driver", e);
        }
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = configuration.getDbUserName();
        String dbPassword = configuration.getDbPassword();
        String url = "jdbc:db2://" + dbServer + ":" + Integer.toString(dbPort) + "/" + dbDatabase;
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            cnx.rollback();
            setSchemaDbName(dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    if (jndiName != null) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            if (ds == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get resolve DataSource \"" + jndiName + "\"");
            }
            cnx = ds.getConnection();
            if (cnx == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get Connection from DataSource \"" + jndiName + "\"");
            }
            cnx.setAutoCommit(false);
            cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            cnx.rollback();
        } catch (NamingException e) {
            cnx = null;
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "NamingException " + e.getMessage(), e);
        } catch (SQLException e) {
            cnx = null;
            inTransaction = false;
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "Neither configurationFile nor jndiName found, do not know how to connect to database");
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccOracle.CFAccOracleSchema.java

public boolean connect() {
    final String S_ProcName = "connect";
    if (cnx != null) {
        return (false);
    }//  w w w  . j  a v a  2 s. c  o m

    if (configuration != null) {
        try {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = configuration.getDbUserName();
        String dbPassword = configuration.getDbPassword();
        String url = "jdbc:oracle:thin:@" + dbServer;
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.rollback();
            setSchemaDbName(dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    if (jndiName != null) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            if (ds == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get resolve DataSource \"" + jndiName + "\"");
            }
            cnx = ds.getConnection();
            if (cnx == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get Connection from DataSource \"" + jndiName + "\"");
            }
            cnx.setAutoCommit(false);
            cnx.rollback();
        } catch (NamingException e) {
            cnx = null;
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "NamingException " + e.getMessage(), e);
        } catch (SQLException e) {
            cnx = null;
            inTransaction = false;
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "Neither configurationFile nor jndiName found, do not know how to connect to database");
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccMySql.CFAccMySqlSchema.java

public boolean connect() {
    final String S_ProcName = "connect";
    if (cnx != null) {
        return (false);
    }//www  .  ja v  a2  s.  c o m

    if (configuration != null) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), "connect",
                    "Could not load MySql 5.5 JDBC driver", e);
        }
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = configuration.getDbUserName();
        String dbPassword = configuration.getDbPassword();
        String url = "jdbc:mysql://" + dbServer + ":" + Integer.toString(dbPort) + "/" + dbDatabase;
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            cnx.rollback();
            setSchemaDbName(dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    if (jndiName != null) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            if (ds == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get resolve DataSource \"" + jndiName + "\"");
            }
            cnx = ds.getConnection();
            if (cnx == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get Connection from DataSource \"" + jndiName + "\"");
            }
            cnx.setAutoCommit(false);
            cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            cnx.rollback();
        } catch (NamingException e) {
            cnx = null;
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "NamingException " + e.getMessage(), e);
        } catch (SQLException e) {
            cnx = null;
            inTransaction = false;
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "Neither configurationFile nor jndiName found, do not know how to connect to database");
}

From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java

@SuppressWarnings("unused")
private SQLPersistenceManagerImpl() {
    loadUsernamePassword();//from  www .  j a va 2  s  .c  o  m
    constructDatabaseURL();

    // define transaction isolation
    if ("TRANSACTION_READ_COMMITTED".equalsIgnoreCase(
            RegistryProperties.getInstance().getProperty("eric.persistence.rdb.transactionIsolation"))) {
        transactionIsolation = Connection.TRANSACTION_READ_COMMITTED;
    } else {
        transactionIsolation = Connection.TRANSACTION_READ_UNCOMMITTED;
    }

    useConnectionPool = Boolean.valueOf(
            RegistryProperties.getInstance().getProperty("eric.persistence.rdb.useConnectionPooling", "true"))
            .booleanValue();
    skipReferenceCheckOnRemove = Boolean.valueOf(RegistryProperties.getInstance()
            .getProperty("eric.persistence.rdb.skipReferenceCheckOnRemove", "false")).booleanValue();
    dumpStackOnQuery = Boolean.valueOf(
            RegistryProperties.getInstance().getProperty("eric.persistence.rdb.dumpStackOnQuery", "false"))
            .booleanValue();
    boolean debugConnectionPool = Boolean
            .valueOf(RegistryProperties.getInstance().getProperty("eric.persistence.rdb.pool.debug", "false"))
            .booleanValue();

    // Create JNDI context
    if (useConnectionPool) {
        if (!debugConnectionPool) {
            // Use Container's connection pooling
            String ericName = RegistryProperties.getInstance().getProperty("eric.name", "eric");
            String envName = "java:comp/env";
            String dataSourceName = "jdbc/" + ericName + "-registry";
            Context ctx = null;

            try {
                ctx = new InitialContext();
                if (null == ctx) {
                    log.info(ServerResourceBundle.getInstance().getString("message.UnableToGetInitialContext"));
                }
            } catch (NamingException e) {
                log.info(ServerResourceBundle.getInstance().getString("message.UnableToGetInitialContext"), e);
                ctx = null;
            }

            if (null != ctx) {
                try {
                    ctx = (Context) ctx.lookup(envName);

                    if (null == ctx) {
                        log.info(ServerResourceBundle.getInstance().getString(
                                "message.UnableToGetJNDIContextForDataSource", new Object[] { envName }));
                    }
                } catch (NamingException e) {
                    log.info(
                            ServerResourceBundle.getInstance().getString(
                                    "message.UnableToGetJNDIContextForDataSource", new Object[] { envName }),
                            e);
                    ctx = null;
                }
            }

            if (null != ctx) {
                try {
                    ds = (DataSource) ctx.lookup(dataSourceName);

                    if (null == ds) {
                        log.info(ServerResourceBundle.getInstance().getString(
                                "message.UnableToGetJNDIContextForDataSource",
                                new Object[] { envName + "/" + dataSourceName }));
                    }
                } catch (NamingException e) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.UnableToGetJNDIContextForDataSource",
                            new Object[] { envName + "/" + dataSourceName }), e);
                    ds = null;
                }
            }

            if (null != ds) {
                // Create a test connection to make sure all is well with
                // DataSource
                Connection connection = null;
                try {
                    connection = ds.getConnection();
                } catch (Exception e) {
                    log.info(ServerResourceBundle.getInstance().getString(
                            "message.UnableToCreateTestConnectionForDataSource",
                            new Object[] { envName + "/" + dataSourceName }), e);
                    ds = null;
                } finally {
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (Exception e1) {
                            // Do nothing.
                            connection = null;
                        }
                    }
                }
            }
        }

        if (ds == null) {
            // No DataSource available so create our own ConnectionPool
            loadDatabaseDriver();
            createConnectionPool();
        }
    } else {
        loadDatabaseDriver();
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccMSSql.CFAccMSSqlSchema.java

public boolean connect() {
    final String S_ProcName = "connect";
    if (cnx != null) {
        return (false);
    }//from w  w  w . j  av a  2 s .c o  m

    if (configuration != null) {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), "connect",
                    "Could not load MS SQL Server 2012 Express Advanced Edition driver", e);
        }
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = configuration.getDbUserName();
        String dbPassword = configuration.getDbPassword();
        String url = "jdbc:sqlserver://" + dbServer + ":" + Integer.toString(dbPort) + ";";
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            cnx.rollback();
            setSchemaDbName(dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName + "<<connect>>", e);
        }
        Statement stmtUseDatabase = null;
        try {
            stmtUseDatabase = cnx.createStatement();
            stmtUseDatabase.executeUpdate("use " + dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName + "<<useDatabase>>",
                    e);
        } finally {
            if (stmtUseDatabase != null) {
                try {
                    stmtUseDatabase.close();
                } catch (SQLException e) {
                }
                stmtUseDatabase = null;
            }
        }
        return (true);
    }
    if (jndiName != null) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            if (ds == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get resolve DataSource \"" + jndiName + "\"");
            }
            cnx = ds.getConnection();
            if (cnx == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get Connection from DataSource \"" + jndiName + "\"");
            }
            cnx.setAutoCommit(false);
            cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            cnx.rollback();
        } catch (NamingException e) {
            cnx = null;
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(),
                    S_ProcName + "<<jndiGetConnection>>", "NamingException " + e.getMessage(), e);
        } catch (SQLException e) {
            cnx = null;
            inTransaction = false;
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(),
                    S_ProcName + "<<jndiGetConnection>>", e);
        }
        return (true);
    }
    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "Neither configurationFile nor jndiName found, do not know how to connect to database");
}

From source file:com.flexive.tests.embedded.persistence.StructureTest.java

@Test(groups = { "ejb", "structure" })
public void assignmentGroupProperty() throws Exception {
    Context c = EJBLookup.getInitialContext();
    UserTransaction ut = (UserTransaction) c.lookup("java:comp/UserTransaction");
    ut.begin();/*w  ww .j av  a2 s. c  o m*/
    FxString desc = new FxString("group description...");
    desc.setTranslation(2, "gruppen beschreibung");
    final String GROUPNAME = "GROUPTEST" + RandomStringUtils.randomNumeric(5);
    FxGroupEdit ge = FxGroupEdit.createNew(GROUPNAME, desc, new FxString("hint..."), true,
            FxMultiplicity.of(0, FxMultiplicity.N));
    ae.createGroup(ge, "/");
    ge.setName("subgroup");
    ae.createGroup(ge, "/" + GROUPNAME);
    ge.setName("subgroup2");
    ae.createGroup(ge, "/" + GROUPNAME + "/SUBGROUP");
    desc.setTranslation(1, "property description...");
    desc.setTranslation(2, "attribut beschreibung...");
    FxPropertyEdit pe = FxPropertyEdit.createNew("testproperty", desc, new FxString("property hint"), true,
            FxMultiplicity.of(1, 1), true, env().getACL(1), FxDataType.Number, new FxString("123"), true, null,
            null, null);
    ae.createProperty(pe, "/" + GROUPNAME + "/SUBGROUP");
    FxGroupAssignment ga = (FxGroupAssignment) env().getAssignment("ROOT/" + GROUPNAME);
    FxGroupAssignmentEdit gae = FxGroupAssignmentEdit.createNew(ga, env().getType("ROOT"), "GTEST", "/");
    ae.save(gae, true);
    ut.rollback();
}

From source file:com.quix.aia.cn.imo.mapper.UserMaintenance.java

/**
 * <p>This method checks USer id and Password and  sets values to bean  and 
 * also set last time login Date & Time</p>
 * @param User user object//w w  w.  j ava2  s . c  om
 * @param requestParameters Servlet Request Parameter
 * @return User object
 */

//   public User authenticateUser(String userID, String password) {
//      log.log(Level.INFO,"UserMaintenance --> authenticateUser ");
//      
//       ArrayList<User> list = new ArrayList();
//       User user=null;  
//       Query query=null;
//       Session session = null;
//      Transaction tx;
//       try{ 
//         
//             session = HibernateFactory.openSession();
//            tx= session.beginTransaction();
//            String psw=PasswordHashing.EncryptBySHA2(password);
//            query = session.createQuery(" from User where status = 1 and staffLoginId=:LoginId and password=:psw    ");
//            query.setParameter("LoginId",userID.toUpperCase());
//            query.setParameter("psw",psw );
//            
//            list=(ArrayList<User>) query.list();
//            
//            if(list.size()==0){
//               query = session.createQuery(" from User where status = 1 and staffLoginId=:LoginId   ");
//               query.setParameter("LoginId",userID.toUpperCase());
//               list=(ArrayList<User>) query.list();
//               User tempUser=new User();
//               if(list.size()!=0){
//                  tempUser=list.get(0);
//                  query = session.createQuery("UPDATE User SET faildLogin=:failLogin where status = 1 and user_no=:userno  ");
//                  query.setParameter("failLogin", new Date());
//                  query.setParameter("userno", tempUser.getUser_no());
//                  query.executeUpdate();
//                  tx.commit();
//                  
//               }
//               
//               return user;
//            }else{
//               user = new User();
//               user = list.get(0);
//               
//               if(user.getSscCode() > 0)
//                  user.setSscLevel(true);
//               else if(user.getCityCode() > 0)
//                  user.setCityLevel(true);
//               else if(user.getBranchCode() > 0)
//                  user.setBranchLevel(true);
//               else if(user.getDistrict() > 0)
//                  user.setDistrictLevel(true);
//               else if(user.getBuCode() > 0)
//                  user.setBuLevel(true);
//            }
//            
//            query = session.createQuery("UPDATE User SET lastLogIn=:lastLogin where status = 1 and user_no=:userno  ");
//            query.setParameter("lastLogin", new Date());
//            query.setParameter("userno", user.getUser_no());
//            query.executeUpdate();
//            tx.commit();
//            
//            
//          log.log(Level.INFO,"authenticateUser Successfully ................. ");
//       }   
//         catch(Exception e)
//         {
//            log.log(Level.INFO,"authenticateUser Failed ................. ");
//            e.printStackTrace();
//            
//         }finally{
//            try{
//               HibernateFactory.close(session);
//            }catch(Exception e){
//               
//               e.printStackTrace();
//            }
//      
//         }
//      return user;
//   }

public User authenticateUser(String userID, String password, String branch, ServletContext context) {
    log.log(Level.INFO, "UserMaintenance --> authenticateUser ");

    ArrayList<User> list = new ArrayList();
    User user = null;
    Query query = null;
    Session session = null;
    Transaction tx;
    UserRest userRest = null;
    UserAuthResponds userAuth = new UserAuthResponds();
    if ("admin".equalsIgnoreCase(userID) && "P@ssword1".equals(password)) {
        user = new User();
        user.setBranchCode(0);
        user.setBranchLevel(false);
        user.setBuCode(0);
        user.setStaffName("Admin");
        user.setBuLevel(true);
        // user.setChannelCode("2|3|");
        user.setCityCode("0");
        user.setCityLevel(false);
        user.setContactNo("0000000000");
        user.setDepartment(0);
        user.setDistrict(0);
        user.setDistrictLevel(false);
        user.setEmail("admin@email.com");
        user.setPassword(password);
        user.setSscCode("0");
        user.setSscLevel(false);
        user.setOfficeCode("0");
        user.setOfficeLevel(false);
        user.setBranchCode(0);
        user.setBranchLevel(false);
        user.setStaffLoginId("Admin");
        user.setStatus(true);
        user.setStatusPsw(true);
        user.setUser_no(0);
        user.setUserType("AD");
        user.setCho(true);
        log.log(Level.INFO, "authenticateUser Successfully ................. ");
    } else {
        GsonBuilder builder = new GsonBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        try {

            String co = "";
            //                  userID="NSNP306";
            //                  password="A111111A";
            AamData aamData = new AamData();
            co = branch;
            //                  co="0986";
            Map<String, String> map = (Map<String, String>) context
                    .getAttribute(ApplicationAttribute.CONFIGURATION_PROPERTIES_MAP);
            //                  String userAuthUrl  = ResourceBundle.getBundle("configurations").getString("userAuthUrl");
            //                  String userAuthUrl = map.get("userAuthUrl");
            String userAuthUrlFinal = "";
            //                  String userAuthEnvironment = map.get("userAuthEnvironment");
            //                  String userAuthEnvironment = context.getInitParameter("userAuthEnvironment");
            Context envEntryContext = (Context) new InitialContext().lookup("java:comp/env");
            String userAuthEnvironment = (String) envEntryContext.lookup("userAuthEnvironment");
            if ("internet".equalsIgnoreCase(userAuthEnvironment)) {
                userAuthUrlFinal = map.get("userAuthUrlInternet") + "&co=" + co + "&account=" + userID
                        + "&password=" + password;

            } else {
                userAuthUrlFinal = map.get("userAuthUrl") + "&co=" + co + "&account=" + userID + "&password="
                        + password;
            }
            log.log(Level.INFO,
                    "UserAuthUrl : " + userAuthUrlFinal + " :- userAuthEnvironment : " + userAuthEnvironment,
                    "");
            HttpGet getRequest = new HttpGet(userAuthUrlFinal);
            getRequest.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(getRequest);

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException(
                        "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

            String output;
            log.log(Level.INFO, "UserMaintenance --> Output from Server ....  ");
            // System.out.println("Output from Server .... \n");
            if ((output = br.readLine()) != null) {
                //System.out.println(output);
                Gson googleJson = new Gson();
                userAuth = googleJson.fromJson(output, UserAuthResponds.class);
                System.out.println("Success " + userAuth.getSuccess());
                if (userAuth.getSuccess().equals("1")) {

                    String content = userAuth.getContent();

                    content = AESPasswordManager.getInstance().decryptPassword(content);

                    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                        @Override
                        public Date deserialize(JsonElement json, Type typeOfT,
                                JsonDeserializationContext context) throws JsonParseException {
                            return LMSUtil.convertDateToyyyy_mm_dd(json.getAsString());
                        }
                    });

                    googleJson = builder.create();

                    //                       content="{\"BRANCH\":\"0986\",\"CITY\":NULL,\"SSC\":NULL,\"USERTYPE\":NULL,\"USERID\":\"000015710\",\"USERNAME\":\"                        \",\"USERSTATUS\":\"A\",\"TEAMCODE\":\"G00000060\",\"TEAMNAME\":\"                        \",\"OFFICECODE\":\"YA01\",\"OFFICENAME\":\"                      \",\"CERTIID\":\"310110198008080808  \",\"DATEOFBIRTH\":\"1980-08-08\",\"GENDER\":\"F \",\"CONTRACTEDDATE\":\"2002-10-01 12:00:00.0\",\"TITLE\":\"L3\",\"DTLEADER\":NULL}";

                    userRest = googleJson.fromJson(content, UserRest.class);

                    if ("STAFF".equalsIgnoreCase(userRest.getUSERTYPE())) {
                        //                     
                        //                     aamData = AamDataMaintenance.retrieveDataToModel(userID);
                        //                     
                        //                     
                        //                     user = new User();
                        //                     if(aamData.getBranchCode()==null){
                        //                        user.setBranchCode(0);
                        //                     }else{
                        //                        user.setBranchCode(aamData.getBranchCode());
                        //                     }
                        //                     
                        //                     if(aamData.getOfficeCode()==null){
                        //                        user.setOfficeCode(0);
                        //                     }else{
                        //                        user.setOfficeCode(Integer.parseInt(aamData.getOfficeCode()));
                        //                     }
                        //                     
                        //                     if(aamData.getDistrictCode()==null){
                        //                        user.setDistrict(0);
                        //                     }else{
                        //                        user.setDistrict(aamData.getDistrictCode());
                        //                     }
                        //                     
                        //                     if(aamData.getCityCode()==null){
                        //                        user.setCityCode(0);
                        //                     }else{
                        //                        user.setCityCode(aamData.getCityCode());
                        //                     }
                        //                     
                        //                     if(aamData.getBuCode()==null){
                        //                        user.setBuCode(0);
                        //                     }else{
                        //                        user.setBuCode(aamData.getBuCode());
                        //                     }
                        //                     if(aamData.getSscCode()==null){
                        //                        user.setSscCode(0);
                        //                     }else{
                        //                        user.setSscCode(aamData.getSscCode());
                        //                     }
                        //                     
                        //                     user.setStaffLoginId(aamData.getAgentCode());
                        //                  
                        //                     user.setUserType(userRest.getUSERTYPE());
                        //                     if(userRest.getUSERSTATUS()!=null){
                        //                        if(userRest.getUSERSTATUS().equalsIgnoreCase("A")){
                        //                           user.setStatus(true);
                        //                        }else{
                        //                           user.setStatus(false);
                        //                        }
                        //                     }else{
                        //                        user.setStatus(false);
                        //                     }
                        //                     
                        //                     if(aamData.getAgentName()==null){
                        //                        user.setStaffName("");
                        //                     }else{
                        //                        user.setStaffName(aamData.getAgentName());
                        //                     }
                        //                     
                        //                     if(user.getOfficeCode() > 0)
                        //                        user.setOfficeLevel(true);
                        //                     if(user.getSscCode() > 0)
                        //                        user.setSscLevel(true);
                        //                     
                        //                     else if(user.getCityCode() > 0)
                        //                        user.setCityLevel(true);
                        //                     else if(user.getBranchCode() > 0)
                        //                        user.setBranchLevel(true);
                        //                     else if(user.getDistrict() > 0)
                        //                        user.setDistrictLevel(true);
                        //                     else if(user.getBuCode() > 0)
                        //                        user.setBuLevel(true);

                        session = HibernateFactory.openSession();
                        tx = session.beginTransaction();
                        //String psw=PasswordHashing.EncryptBySHA2(password);
                        query = session.createQuery(" from User where status = 1 and staffLoginId=:LoginId ");
                        query.setParameter("LoginId", userID.toUpperCase());
                        //query.setParameter("psw",psw );

                        list = (ArrayList<User>) query.list();

                        if (list.size() == 0) {
                            //                           query = session.createQuery(" from User where status = 1 and staffLoginId=:LoginId   ");
                            //                           query.setParameter("LoginId",userID.toUpperCase());
                            //                           list=(ArrayList<User>) query.list();
                            //                           User tempUser=new User();
                            //                           if(list.size()!=0){
                            //                              tempUser=list.get(0);
                            //                              query = session.createQuery("UPDATE User SET faildLogin=:failLogin where status = 1 and user_no=:userno  ");
                            //                              query.setParameter("failLogin", new Date());
                            //                              query.setParameter("userno", tempUser.getUser_no());
                            //                              query.executeUpdate();
                            //                              tx.commit();
                            //                              
                            //                           }
                            //                           
                            return user;
                        } else {
                            user = new User();
                            user = list.get(0);

                            if (!user.getOfficeCode().trim().equals("0"))
                                user.setOfficeLevel(true);
                            else if (!user.getSscCode().trim().equals("0"))
                                user.setSscLevel(true);
                            else if (!user.getCityCode().trim().equals("0"))
                                user.setCityLevel(true);
                            else if (user.getBranchCode() > 0)
                                user.setBranchLevel(true);
                            else if (user.getDistrict() > 0)
                                user.setDistrictLevel(true);
                            else if (user.getBuCode() > 0)
                                user.setBuLevel(true);
                        }

                        query = session.createQuery(
                                "UPDATE User SET lastLogIn=:lastLogin where status = 1 and user_no=:userno  ");
                        query.setParameter("lastLogin", new Date());
                        query.setParameter("userno", user.getUser_no());
                        query.executeUpdate();
                        tx.commit();

                        log.log(Level.INFO, "authenticateUser Successfully ................. ");

                    } else {
                        log.log(Level.INFO, "Login Failed............");
                    }

                } else {
                    log.log(Level.INFO, "Login Failed............");

                }

            }

        } catch (Exception e) {
            log.log(Level.SEVERE, e.getMessage());
            e.printStackTrace();
            LogsMaintenance logsMain = new LogsMaintenance();
            StringWriter errors = new StringWriter();
            e.printStackTrace(new PrintWriter(errors));
            logsMain.insertLogs("UserMaintenance", Level.SEVERE + "", errors.toString());
        } finally {
            httpClient.getConnectionManager().shutdown();
            HibernateFactory.close(session);
        }
    }
    return user;
}

From source file:com.duroty.application.mail.manager.MailManager.java

/**
 * Creates a new MailManager object.//from w  w  w.j ava2s.  c o m
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NamingException 
 */
public MailManager(HashMap mail)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, NamingException {
    super();

    String messageFactory = (String) mail.get(Constants.MESSAGES_FACTORY);

    if ((messageFactory != null) && !messageFactory.trim().equals("")) {
        Class clazz = null;
        clazz = Class.forName(messageFactory.trim());
        this.messageable = (Messageable) clazz.newInstance();
        this.messageable.setProperties(mail);
    }

    this.folderAll = (String) mail.get(Constants.MAIL_FOLDER_ALL);
    this.folderInbox = (String) mail.get(Constants.MAIL_FOLDER_INBOX);
    this.folderSent = (String) mail.get(Constants.MAIL_FOLDER_SENT);
    this.folderTrash = (String) mail.get(Constants.MAIL_FOLDER_TRASH);
    this.folderBlog = (String) mail.get(Constants.MAIL_FOLDER_BLOG);
    this.folderDraft = (String) mail.get(Constants.MAIL_FOLDER_DRAFT);
    this.folderSpam = (String) mail.get(Constants.MAIL_FOLDER_SPAM);
    this.folderImportant = (String) mail.get(Constants.MAIL_FOLDER_IMPORTANT);
    this.folderHidden = (String) mail.get(Constants.MAIL_FOLDER_HIDDEN);
    this.folderChat = (String) mail.get(Constants.MAIL_FOLDER_CHAT);
    this.quoteSizeAlert = Integer.valueOf((String) mail.get(Constants.MAIL_QUOTE_SIZE_ALERT)).intValue();

    tidy.setUpperCaseTags(true);
    tidy.setInputEncoding(Charset.defaultCharset().displayName());
    tidy.setOutputEncoding(Charset.defaultCharset().displayName());
    tidy.setMakeBare(true);
    tidy.setMakeClean(true);
    tidy.setShowWarnings(false);
    tidy.setErrout(new PrintWriter(new NullWriter()));
    tidy.setWord2000(true);
    tidy.setDropProprietaryAttributes(true);
    tidy.setFixBackslash(true);
    tidy.setXHTML(true);

    //tidy.setXmlOut(true);
    tidy.setWrapSection(true);
    tidy.setWrapScriptlets(true);
    tidy.setWrapPhp(true);
    tidy.setQuiet(true);
    tidy.setBreakBeforeBR(true);
    tidy.setEscapeCdata(true);
    tidy.setForceOutput(true);
    tidy.setHideComments(false);
    tidy.setPrintBodyOnly(true);
    tidy.setTidyMark(false);

    Map options = ApplicationConstants.options;

    Context ctx = new InitialContext();

    this.extensions = (HashMap) ctx.lookup((String) options.get(Constants.EXTENSION_CONFIG));
}