Search in sources :

Example 1 with CConnection

use of org.compiere.db.CConnection in project adempiere by adempiere.

the class Login method getClients.

//	getRoles
/**************************************************************************
	 *  Load Clients.
	 *  <p>
	 *  Sets Role info in context and loads its clients
	 *  @param  role    role information
	 *  @return list of valid client KeyNodePairs or null if in error
	 */
public KeyNamePair[] getClients(KeyNamePair role) {
    if (role == null)
        throw new IllegalArgumentException("Role missing");
    //	s_log.fine("loadClients - Role: " + role.toStringX());
    ArrayList<KeyNamePair> list = new ArrayList<KeyNamePair>();
    KeyNamePair[] retValue = null;
    String sql = //	1/2
    "SELECT DISTINCT r.UserLevel, r.ConnectionProfile, " + //	3/4 
    " c.AD_Client_ID,c.Name " + "FROM AD_Role r" + " INNER JOIN AD_Client c ON (r.AD_Client_ID=c.AD_Client_ID) " + //	#1
    "WHERE r.AD_Role_ID=?" + " AND r.IsActive='Y' AND c.IsActive='Y'";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    //	get Role details
    try {
        pstmt = DB.prepareStatement(sql, null);
        pstmt.setInt(1, role.getKey());
        rs = pstmt.executeQuery();
        if (!rs.next()) {
            rs.close();
            pstmt.close();
            log.log(Level.SEVERE, "No Clients for Role: " + role.toStringX());
            return null;
        }
        //  Role Info
        Env.setContext(m_ctx, "#AD_Role_ID", role.getKey());
        Env.setContext(m_ctx, "#AD_Role_Name", role.getName());
        Ini.setProperty(Ini.P_ROLE, role.getName());
        //	User Level
        //	Format 'SCO'
        Env.setContext(m_ctx, "#User_Level", rs.getString(1));
        //	ConnectionProfile
        CConnection cc = CConnection.get();
        if (//	No User Based
        m_connectionProfile == null) {
            //	Role Based
            m_connectionProfile = rs.getString(2);
            if (m_connectionProfile != null && !cc.getConnectionProfile().equals(m_connectionProfile)) {
                cc.setConnectionProfile(m_connectionProfile);
                Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong());
                Ini.saveProperties(false);
            }
        }
        //  load Clients
        do {
            int AD_Client_ID = rs.getInt(3);
            String Name = rs.getString(4);
            KeyNamePair p = new KeyNamePair(AD_Client_ID, Name);
            list.add(p);
        } while (rs.next());
        rs.close();
        pstmt.close();
        pstmt = null;
        //
        retValue = new KeyNamePair[list.size()];
        list.toArray(retValue);
        log.fine("Role: " + role.toStringX() + " - clients #" + retValue.length);
    } catch (SQLException ex) {
        log.log(Level.SEVERE, sql, ex);
        retValue = null;
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    return retValue;
}
Also used : CConnection(org.compiere.db.CConnection) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 2 with CConnection

use of org.compiere.db.CConnection in project adempiere by adempiere.

the class PackIn method main.

// doIt
/***************************************************************************
	 * 
	 * @param args
	 *            XMLfile host port db username password
	 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Please give the file name to read as first parameter.");
        System.exit(1);
    }
    String file = args[0];
    org.compiere.Adempiere.startup(true);
    // globalqss - added argument 8 to generate system sequences
    if (args.length > 8 && args[8].equals(Ini.P_ADEMPIERESYS)) {
        System.out.println("**** WARNING: Working with system sequences " + Ini.P_ADEMPIERESYS + " ****");
        Ini.setProperty(Ini.P_ADEMPIERESYS, true);
    }
    PackIn packIn = new PackIn();
    // Compiere.properties
    if (args.length >= 6) {
        // CConnection cc = CConnection.get("PostgreSQL", args[1],
        // Integer.valueOf(args[2]).intValue(), args[5], args[3], args[4]);
        CConnection cc = CConnection.get();
        // System.out.println("DB Connect String1:"+cc.getDbName());
        PackIn.m_Database = cc.getType();
        DB.setDBTarget(cc);
    }
    // Level.OFF, Level.SEVERE, Level.WARNING, Level.INFO,
    // Level.CONFIG, Level.FINE, Level.FINER, Level.FINEST, Level.ALL
    Level logLevel = Level.FINER;
    switch(Integer.parseInt(args[6])) {
        case 1:
            logLevel = Level.OFF;
            break;
        case 2:
            logLevel = Level.SEVERE;
            break;
        case 3:
            logLevel = Level.WARNING;
            break;
        case 4:
            logLevel = Level.INFO;
            break;
        case 5:
            logLevel = Level.CONFIG;
            break;
        case 6:
            logLevel = Level.FINE;
            break;
        case 7:
            logLevel = Level.FINER;
            break;
        case 8:
            logLevel = Level.FINEST;
            break;
        case 9:
            logLevel = Level.ALL;
            break;
    }
    CLogMgt.setLevel(logLevel);
    CLogMgt.setLoggerLevel(logLevel, null);
    if (args.length >= 8)
        PackIn.m_UpdateMode = args[7];
    String trxName = Trx.createTrxName("PackIn");
    try {
        packIn.importXML(file, Env.getCtx(), trxName);
        Trx trx = Trx.get(trxName, false);
        if (trx != null)
            trx.commit(true);
    } catch (Exception e) {
        System.out.println("Import Failed: " + e.getLocalizedMessage());
        Trx trx = Trx.get(trxName, false);
        if (trx != null)
            trx.rollback();
    }
    System.exit(0);
}
Also used : CConnection(org.compiere.db.CConnection) Level(java.util.logging.Level) Trx(org.compiere.util.Trx)

Example 3 with CConnection

use of org.compiere.db.CConnection in project adempiere by adempiere.

the class Login method getRoles.

/**
	 *	(Test) Client Login.
	 *  <p>
	 *  - Get Connection
	 *  - Compare User info
	 *  <p>
	 *  Sets Context with login info
	 * @param cc connection
	 * @param app_user user
	 * @param app_pwd pwd
	 * @param force ignore pwd
	 * @return  Array of Role KeyNamePair or null if error
	 * The error (NoDatabase, UserPwdError, DBLogin) is saved in the log
	 */
protected KeyNamePair[] getRoles(CConnection cc, String app_user, String app_pwd, boolean force) {
    //	Establish connection
    DB.setDBTarget(cc);
    Env.setContext(m_ctx, "#Host", cc.getAppsHost());
    Env.setContext(m_ctx, "#Database", cc.getDbName());
    Connection conn = DB.getConnectionRO();
    if (conn == null) {
        log.saveError("NoDatabase", "");
        return null;
    }
    try {
        conn.close();
    } catch (SQLException e) {
    }
    if (app_pwd == null)
        return null;
    //
    return getRoles(app_user, app_pwd, force);
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) CConnection(org.compiere.db.CConnection)

Example 4 with CConnection

use of org.compiere.db.CConnection in project adempiere by adempiere.

the class Login method getRoles.

//  login
/**
	 *  Actual DB login procedure.
	 *  @param app_user user
	 *  @param app_pwd pwd
	 *  @param force ignore pwd
	 *  @return role array or null if in error.
	 *  The error (NoDatabase, UserPwdError, DBLogin) is saved in the log
	 */
private KeyNamePair[] getRoles(String app_user, String app_pwd, boolean force) {
    log.info("User=" + app_user);
    long start = System.currentTimeMillis();
    if (app_user == null) {
        log.warning("No Apps User");
        return null;
    }
    //	Authentication
    boolean authenticated = false;
    if (Ini.isClient())
        CConnection.get().setAppServerCredential(app_user, app_pwd);
    MSystem system = MSystem.get(m_ctx);
    if (system == null)
        throw new IllegalStateException("No System Info");
    if (app_pwd == null || app_pwd.length() == 0) {
        log.warning("No Apps Password");
        return null;
    }
    if (system.isLDAP()) {
        authenticated = system.isLDAP(app_user, app_pwd);
        if (authenticated)
            app_pwd = null;
    // if not authenticated, use AD_User as backup
    }
    // adaxa-pb: try to authenticate using hashed password -- falls back to plain text/encrypted
    final String where = " COALESCE(LDAPUser,Name) = ? AND" + " EXISTS (SELECT * FROM AD_User_Roles ur" + "         INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID)" + "         WHERE ur.AD_User_ID=AD_User.AD_User_ID AND ur.IsActive='Y' AND r.IsActive='Y') AND " + " EXISTS (SELECT * FROM AD_Client c" + "         WHERE c.AD_Client_ID=AD_User.AD_Client_ID" + "         AND c.IsActive='Y') AND " + " AD_User.IsActive='Y'";
    List<Object> parameters = new ArrayList<Object>();
    parameters.add(app_user);
    //Get User ID and hash Password
    final ValueNamePair[] passwordHash = DB.getValueNamePairs("SELECT  AD_User_ID , Password FROM AD_User WHERE " + where, false, parameters);
    String hash = null;
    String salt = null;
    int AD_User_ID = 0;
    //Validate if password column is encrypted
    boolean isEncrypted = MColumn.isEncrypted(417);
    //Validate  password hash
    if (passwordHash != null && passwordHash.length > 0) {
        AD_User_ID = new Integer(passwordHash[0].getValue());
        hash = isEncrypted ? SecureEngine.decrypt(passwordHash[0].getName()) : passwordHash[0].getName();
        salt = DB.getSQLValueString(null, "SELECT Salt FROM AD_User WHERE AD_User_ID=?", AD_User_ID);
    }
    if (hash == null)
        hash = "0000000000000000";
    if (salt == null)
        salt = "0000000000000000";
    if (MUser.authenticateHash(app_pwd, hash, salt)) {
        authenticated = true;
        app_pwd = null;
    }
    KeyNamePair[] retValue = null;
    ArrayList<KeyNamePair> list = new ArrayList<KeyNamePair>();
    //
    StringBuffer sql = new StringBuffer("SELECT u.AD_User_ID, r.AD_Role_ID,r.Name,").append(" u.ConnectionProfile ").append("FROM AD_User u").append(" INNER JOIN AD_User_Roles ur ON (u.AD_User_ID=ur.AD_User_ID AND ur.IsActive='Y')").append(" INNER JOIN AD_Role r ON (ur.AD_Role_ID=r.AD_Role_ID AND r.IsActive='Y') ");
    if (AD_User_ID > 0)
        // #1
        sql.append("WHERE u.AD_User_ID = ?");
    else
        //	#1
        sql.append("WHERE COALESCE(u.LDAPUser,u.Name)=?");
    sql.append(" AND u.IsActive='Y'").append(" AND EXISTS (SELECT * FROM AD_Client c WHERE u.AD_Client_ID=c.AD_Client_ID AND c.IsActive='Y')");
    if (app_pwd != null)
        sql.append(" AND ((u.Password=? AND (SELECT IsEncrypted FROM AD_Column WHERE AD_Column_ID=417)='N') " + //  #2/3
        "OR (u.Password=? AND (SELECT IsEncrypted FROM AD_Column WHERE AD_Column_ID=417)='Y'))");
    sql.append(" ORDER BY r.Name");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(sql.toString(), null);
        if (AD_User_ID > 0)
            pstmt.setInt(1, AD_User_ID);
        else
            pstmt.setString(1, app_user);
        if (app_pwd != null) {
            pstmt.setString(2, app_pwd);
            pstmt.setString(3, SecureEngine.encrypt(app_pwd));
        }
        //	execute a query
        rs = pstmt.executeQuery();
        if (//	no record found
        !rs.next())
            if (force) {
                Env.setContext(m_ctx, "#AD_User_Name", "System");
                Env.setContext(m_ctx, "#AD_User_ID", "0");
                Env.setContext(m_ctx, "#AD_User_Description", "System Forced Login");
                //	Format 'SCO'
                Env.setContext(m_ctx, "#User_Level", "S  ");
                //	Format c1, c2, ...
                Env.setContext(m_ctx, "#User_Client", "0");
                //	Format o1, o2, ...
                Env.setContext(m_ctx, "#User_Org", "0");
                rs.close();
                pstmt.close();
                retValue = new KeyNamePair[] { new KeyNamePair(0, "System Administrator") };
                return retValue;
            } else {
                rs.close();
                pstmt.close();
                log.saveError("UserPwdError", app_user, false);
                return null;
            }
        Env.setContext(m_ctx, "#AD_User_Name", app_user);
        Env.setContext(m_ctx, "#AD_User_ID", rs.getInt(1));
        Env.setContext(m_ctx, "#SalesRep_ID", rs.getInt(1));
        //
        if (Ini.isClient()) {
            if (MSystem.isSwingRememberUserAllowed())
                Ini.setProperty(Ini.P_UID, app_user);
            else
                Ini.setProperty(Ini.P_UID, "");
            if (Ini.isPropertyBool(Ini.P_STORE_PWD) && MSystem.isSwingRememberPasswordAllowed())
                Ini.setProperty(Ini.P_PWD, app_pwd);
            //	User Based
            m_connectionProfile = rs.getString(4);
            if (m_connectionProfile != null) {
                CConnection cc = CConnection.get();
                if (!cc.getConnectionProfile().equals(m_connectionProfile)) {
                    cc.setConnectionProfile(m_connectionProfile);
                    Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong());
                    Ini.saveProperties(false);
                }
            }
        }
        do //	read all roles
        {
            int AD_Role_ID = rs.getInt(2);
            if (AD_Role_ID == 0)
                Env.setContext(m_ctx, "#SysAdmin", "Y");
            String Name = rs.getString(3);
            KeyNamePair p = new KeyNamePair(AD_Role_ID, Name);
            list.add(p);
        } while (rs.next());
        //
        retValue = new KeyNamePair[list.size()];
        list.toArray(retValue);
        log.fine("User=" + app_user + " - roles #" + retValue.length);
    } catch (Exception ex) {
        log.log(Level.SEVERE, sql.toString(), ex);
        log.saveError("DBLogin", ex);
        retValue = null;
    } finally //
    {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    long ms = System.currentTimeMillis() - start;
    return retValue;
}
Also used : ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) CConnection(org.compiere.db.CConnection) ResultSet(java.sql.ResultSet)

Example 5 with CConnection

use of org.compiere.db.CConnection in project adempiere by adempiere.

the class CLogMgt method getInfoDetail.

/**
	 *  Create System Info
	 *  @param sb Optional string buffer
	 *  @param ctx Environment
	 *  @return System Info
	 */
public static StringBuffer getInfoDetail(StringBuffer sb, Properties ctx) {
    if (sb == null)
        sb = new StringBuffer();
    if (ctx == null)
        ctx = Env.getCtx();
    //  Envoronment
    CConnection cc = CConnection.get();
    sb.append(NL).append("=== Environment === ").append(Adempiere.getCheckSum()).append(NL).append(Adempiere.getSummaryAscii()).append(NL).append(getLocalHost()).append(NL).append(cc.getName() + " " + cc.getDbUid() + "@" + cc.getConnectionURL()).append(NL).append(cc.getInfo()).append(NL);
    //  Context
    sb.append(NL).append("=== Context ===").append(NL);
    String[] context = Env.getEntireContext(ctx);
    Arrays.sort(context);
    for (int i = 0; i < context.length; i++) sb.append(context[i]).append(NL);
    //  System
    sb.append(NL).append("=== System ===").append(NL);
    Object[] pp = System.getProperties().keySet().toArray();
    Arrays.sort(pp);
    for (int i = 0; i < pp.length; i++) {
        String key = pp[i].toString();
        String value = System.getProperty(key);
        sb.append(key).append("=").append(value).append(NL);
    }
    return sb;
}
Also used : CConnection(org.compiere.db.CConnection)

Aggregations

CConnection (org.compiere.db.CConnection)11 SQLException (java.sql.SQLException)4 File (java.io.File)3 IOException (java.io.IOException)3 MalformedURLException (java.net.MalformedURLException)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 ArrayList (java.util.ArrayList)2 Trx (org.compiere.util.Trx)2 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 FileReader (java.io.FileReader)1 FileWriter (java.io.FileWriter)1 MemoryMXBean (java.lang.management.MemoryMXBean)1 RuntimeMXBean (java.lang.management.RuntimeMXBean)1 ThreadMXBean (java.lang.management.ThreadMXBean)1 Timestamp (java.sql.Timestamp)1