Search in sources :

Example 1 with AMLogException

use of com.sun.identity.log.AMLogException in project OpenAM by OpenRock.

the class LogReadDBHandler method logRecRead.

/**
     * LogReader calls this method. It collects header, records,
     * applies query (if any), sorts (if asked) the records on field, checks
     * the max records to return, collects all the recods and returns.
     *
     * @param tableNames db table names
     * @param logQuery is user specified qury chriteria with sorting requirement
     * @param logMgr the log manager associated with this handler
     * @param sourceData it specifies whether return data should be original
     *        data received by logger (source) or formatted data as in file.
     * @return all the matched records with query
     * @throws IOException if it fails to read log records.
     * @throws NoSuchFieldException if it fails to retrieve the name of field.
     * @throws IllegalArgumentException if query has wrong value.
     * @throws RuntimeException if it fails to retrieve log record.
     * @throws SQLException if it fails to process sql query.
     * @throws Exception if it fails any of operation.
     */
public String[][] logRecRead(Set tableNames, LogQuery logQuery, java.util.logging.LogManager logMgr, boolean sourceData) throws IOException, NoSuchFieldException, IllegalArgumentException, RuntimeException, SQLException, Exception {
    String sortField = null;
    // if the object is persistence use it otherwise don't
    this.cleaner();
    //
    // tblNames is needed for the guaranteed "underscore" form
    // (e.g., "amAuthentication_access") of the table names
    // 
    Set tblNames = new HashSet();
    StringBuilder allTablesSB = new StringBuilder("");
    for (Iterator it = tableNames.iterator(); it.hasNext(); ) {
        String ss = (String) it.next();
        String ss2 = ss.replace('.', '_');
        tblNames.add(ss2);
        allTablesSB.append(ss2);
    }
    //
    try {
        this.databaseURL = logMgr.getProperty(LogConstants.LOG_LOCATION);
        this.dbDriver = logMgr.getProperty(LogConstants.DB_DRIVER);
        this.dbUserName = logMgr.getProperty(LogConstants.DB_USER);
        this.dbPassWord = logMgr.getProperty(LogConstants.DB_PASSWORD);
        this.maxRecordsStr = logMgr.getProperty(LogConstants.MAX_RECORDS);
    } catch (Exception e) {
        Debug.error("DBLogRecReadSet:config: ", e);
        // rethrow the exception
        throw e;
    }
    if (this.dbDriver.toLowerCase().indexOf("oracle") != -1) {
        isMySQL = false;
    } else if (this.dbDriver.toLowerCase().indexOf("mysql") != -1) {
        isMySQL = true;
    } else {
        isMySQL = false;
        Debug.warning("DBlogRecRead:assuming driver: '" + this.dbDriver + "' is Oracle-compatible.");
    }
    try {
        this.maxRecords = Integer.parseInt(maxRecordsStr);
    } catch (NumberFormatException nfe) {
        if (Debug.warningEnabled()) {
            Debug.warning("DBlogRecRead(s): maxRecords error (" + maxRecordsStr + "), set to MAX");
        }
        this.maxRecords = LogConstants.MAX_RECORDS_DEFAULT_INT;
    }
    //
    //  kind of a bad situation here between Oracle and MySQL.
    //  pre-v4 MySQL doesn't support the "union" operator, so multi-
    //  table selects has to be affected as multiple single-table
    //  selects and combining their results.
    //
    //  the Oracle case is more straightforward, and if we decide
    //  to only support >= V4 MySQL, can just use the !isMySQL
    //  branch.
    //
    String selectStr;
    if (!isMySQL) {
        if (sourceData == true) {
            String temps = logQuery.getSortingField();
            if (temps != null) {
                sortField = temps.trim();
            }
            // default all
            String columns = "*";
            ArrayList sCol = logQuery.getColumns();
            if (sCol != null) {
                StringBuilder colSB = new StringBuilder();
                int sSize = sCol.size();
                for (int i = 0; i < sSize; i++) {
                    colSB.append((String) sCol.get(i));
                    if ((i + 1) < sSize) {
                        colSB.append(", ");
                    }
                }
                columns = colSB.toString();
            }
            selectStr = lq2Select(tblNames, columns, logQuery);
            if (Debug.messageEnabled()) {
                Debug.message("logRecRead/4:selectStr = " + selectStr);
            }
        } else {
            // default all
            String columns = "*";
            selectStr = lq2Select(tblNames, columns, null);
            if (Debug.messageEnabled()) {
                Debug.message("logRecRead/4.2:selectStr = " + selectStr);
            }
        }
        String[][] tableResults;
        try {
            connectToDatabase(dbUserName, dbPassWord);
        } catch (SQLException sqe) {
            Debug.error("DBlogRecRead:connect:SQE:code=" + sqe.getErrorCode() + ", msg=" + sqe.getMessage());
            // rethrow for LogReader to catch
            throw sqe;
        } catch (ClassNotFoundException cnfe) {
            // rethrow for LogReader to catch
            throw cnfe;
        }
        String selStr = selectStr;
        Statement stmt = null;
        int numberOfRows = 0;
        try {
            stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            if (Debug.messageEnabled()) {
                Debug.message("DBlogRecRead:about to execute: " + selStr);
            }
            ResultSet rs = stmt.executeQuery(selStr);
            //
            //  fetchsize appears to be 10 from rs.getFetchSize();
            //
            ResultSetMetaData rsmd = rs.getMetaData();
            int numberOfColumns = rsmd.getColumnCount();
            if (Debug.messageEnabled()) {
                Debug.message("DBlogRecRead:#columns = " + numberOfColumns);
            }
            //
            //  these are the column (field) names
            //
            String[] spltHdrStr = new String[numberOfColumns];
            for (int i = 1; i <= numberOfColumns; i++) {
                String tempstr = rsmd.getColumnName(i);
                if (Debug.messageEnabled()) {
                    Debug.message("DBlogRecRead:col #" + i + " name = " + tempstr);
                }
                spltHdrStr[i - 1] = tempstr;
            }
            listOfValidRecords.add(spltHdrStr);
            // have to figure out #rows
            while (rs.next()) {
                numberOfRows++;
            }
            if (Debug.messageEnabled()) {
                Debug.message("DBlogRecRead:#rows = " + numberOfRows);
            }
            if (numberOfRows == 0) {
                stmt.close();
                try {
                    conn.close();
                } catch (SQLException ex) {
                    //
                    //  might not care about this too much...?
                    //
                    Debug.error("DBlogRecRead:rows=0:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
                }
                //
                //  should be at least the column names
                //
                int recSize = listOfValidRecords.size();
                if (recSize <= 0) {
                    return null;
                }
                queryResult = new String[recSize][];
                for (int i = 0; i < recSize; i++) {
                    queryResult[i] = (String[]) listOfValidRecords.get(i);
                }
                return queryResult;
            }
            if (numberOfRows > this.maxRecords) {
                stmt.close();
                try {
                    conn.close();
                } catch (SQLException ex) {
                    //
                    //  don't care about this too much...
                    //
                    Debug.error("DBlogRecRead:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
                }
                throw new AMLogException(AMLogException.LOG_DB_TOOMANYRECORDS);
            }
            //
            //  reset to the beginning
            //
            boolean isFirst = rs.first();
            if (isFirst == false) {
                Debug.error("DBlogRecRead:first() is false!");
            }
            //
            //  think we're not going to allow MOST_RECENT_MAX_RECORDS
            //  with multi-table query...
            //
            int rowsToAlloc = numberOfRows;
            tableResults = new String[rowsToAlloc][numberOfColumns];
            String result = null;
            int rowCount = 0;
            for (int i = 0; i < numberOfColumns; i++) {
                result = rs.getString(i + 1);
                tableResults[0][i] = result;
            }
            rowCount = 1;
            while (rs.next()) {
                for (int i = 0; i < numberOfColumns; i++) {
                    result = rs.getString(i + 1);
                    tableResults[rowCount][i] = result;
                }
                rowCount++;
            }
            stmt.close();
        } catch (SQLException se) {
            Debug.error("DBlogRecRead:query:SQE:code=" + se.getErrorCode() + ", msg=" + se.getMessage());
            // rethrow for LogReader to catch
            throw se;
        }
        try {
            this.getRecords(tableResults, sourceData);
        } catch (IOException e) {
            // catch & rethrow it
            throw e;
        } catch (IllegalArgumentException e) {
            // catch & rethrow it
            throw e;
        } catch (RuntimeException e) {
            // catch & rethrow it
            throw e;
        } catch (Exception e) {
            // catch & rethrow it
            throw e;
        }
        int recSize = listOfValidRecords.size();
        // checks whether it has got any record or not
        if (recSize <= 0) {
            // if no record found return null
            return null;
        }
        try {
            conn.close();
        } catch (SQLException ex) {
            //
            //  might not care about this too much...?
            //
            Debug.error("DBlogRecRead:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
        }
        queryResult = new String[recSize][];
        for (int i = 0; i < recSize; i++) {
            queryResult[i] = (String[]) listOfValidRecords.get(i);
        }
    } else {
        // else (isMySQL case)
        //
        //  Multi-table select for <V4 MySQL is essentially
        //  looping through the tables and combining the results.
        //
        String columns = null;
        if (sourceData == true) {
            String temps = logQuery.getSortingField();
            if (temps != null) {
                sortField = temps.trim();
            }
            // default all
            columns = "*";
            ArrayList sCol = logQuery.getColumns();
            if (sCol != null) {
                StringBuilder colSB = new StringBuilder();
                int sSize = sCol.size();
                for (int i = 0; i < sSize; i++) {
                    colSB.append((String) sCol.get(i));
                    if ((i + 1) < sSize) {
                        colSB.append(", ");
                    }
                }
                columns = colSB.toString();
            }
        } else {
            // default all
            columns = "*";
        }
        //
        //  do same select on each table
        //
        boolean isFirstTable = true;
        int totalNumberOfRows = 0;
        int recSize = 0;
        for (Iterator it = tblNames.iterator(); it.hasNext(); ) {
            String thisTable = (String) it.next();
            if (sourceData == true) {
                selectStr = lq2Select(thisTable, columns, logQuery);
                if (Debug.messageEnabled()) {
                    Debug.message("logRecRead/5:selectStr = " + selectStr);
                }
            } else {
                selectStr = lq2Select(thisTable, columns, null);
                if (Debug.messageEnabled()) {
                    Debug.message("logRecRead/5.2:selectStr = " + selectStr);
                }
            }
            String[][] tableResults = null;
            try {
                connectToDatabase(dbUserName, dbPassWord);
            } catch (SQLException sqe) {
                Debug.error("DBlogRecRead:connect:SQE:code=" + sqe.getErrorCode() + ", msg=" + sqe.getMessage());
                // rethrow for LogReader to catch
                throw sqe;
            } catch (ClassNotFoundException cnfe) {
                // rethrow for LogReader to catch
                throw cnfe;
            }
            String selStr = selectStr;
            Statement stmt = null;
            int numberOfRows = 0;
            //
            try {
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                if (Debug.messageEnabled()) {
                    Debug.message("DBlogRecRead:about to execute: " + selStr);
                }
                ResultSet rs = stmt.executeQuery(selStr);
                //
                //  fetchsize appears to be 10 from rs.getFetchSize();
                //
                ResultSetMetaData rsmd = rs.getMetaData();
                int numberOfColumns = rsmd.getColumnCount();
                if (Debug.messageEnabled()) {
                    Debug.message("DBlogRecRead:#columns = " + numberOfColumns);
                }
                if (isFirstTable) {
                    String[] spltHdrStr = new String[numberOfColumns];
                    for (int i = 1; i <= numberOfColumns; i++) {
                        String tempstr = rsmd.getColumnName(i);
                        if (Debug.messageEnabled()) {
                            Debug.message("DBlogRecRead:col #" + i + " name = " + tempstr);
                        }
                        spltHdrStr[i - 1] = tempstr;
                    }
                    listOfValidRecords.add(spltHdrStr);
                }
                // have to figure out #rows
                numberOfRows = 0;
                while (rs.next()) {
                    numberOfRows++;
                }
                totalNumberOfRows += numberOfRows;
                if (totalNumberOfRows > this.maxRecords) {
                    stmt.close();
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        //
                        //  don't care about this too much...
                        //
                        Debug.error("DBlogRecRead:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
                    }
                    throw new AMLogException(AMLogException.LOG_DB_TOOMANYRECORDS);
                }
                if (numberOfRows > 0) {
                    //
                    //  reset to the "beginning"
                    //
                    boolean isFirst = rs.first();
                    if (isFirst == false) {
                        Debug.error("DBlogRecRead:first() is false!");
                    }
                    //
                    //  think we're not going to allow 
                    //  MOST_RECENT_MAX_RECORDS with multi-table query...
                    //
                    tableResults = new String[numberOfRows][numberOfColumns];
                    String result = null;
                    int rowCount = 0;
                    do {
                        for (int i = 0; i < numberOfColumns; i++) {
                            result = rs.getString(i + 1);
                            tableResults[rowCount][i] = result;
                        }
                        rowCount++;
                    } while (rs.next());
                }
                //
                //  print the actual results in the debug log
                //
                stmt.close();
            } catch (SQLException se) {
                Debug.error("DBlogRecRead:query:SQE:code=" + se.getErrorCode() + ", msg=" + se.getMessage());
                // rethrow for LogReader to catch
                throw se;
            }
            if (numberOfRows > 0) {
                try {
                    this.getRecords(tableResults, sourceData);
                } catch (IOException e) {
                    // catch & rethrow it
                    throw e;
                } catch (IllegalArgumentException e) {
                    // catch & rethrow it
                    throw e;
                } catch (RuntimeException e) {
                    // catch & rethrow it
                    throw e;
                } catch (Exception e) {
                    // catch & rethrow it
                    throw e;
                }
            }
            if (isFirstTable) {
                isFirstTable = false;
            }
        }
        try {
            conn.close();
        } catch (SQLException ex) {
            //
            //  might not care about this too much...?
            //
            Debug.error("DBlogRecRead:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
        }
        if (logQuery != null) {
            String sortByField = logQuery.getSortingField();
            if (sortByField != null) {
                try {
                    this.sorter = new LogRecordSorter(sortByField, listOfValidRecords);
                    queryResult = this.sorter.getSortedRecords();
                } catch (NoSuchFieldException e) {
                    Debug.error("DBlogRecRead/5:sort:nsfe: " + e.getMessage());
                    throw e;
                } catch (IllegalArgumentException e) {
                    Debug.error("DBlogRecRead/5:sort:iae: " + e.getMessage());
                    throw e;
                } catch (RuntimeException e) {
                    Debug.error("DBlogRecRead/5:sort:rte: " + e.getMessage());
                    throw e;
                } catch (Exception e) {
                    Debug.error("DBlogRecRead/5:sort:ex: " + e.getMessage());
                    throw e;
                }
                return (queryResult);
            }
        }
        recSize = listOfValidRecords.size();
        // checks whether it has got any record or not
        if (recSize <= 0) {
            // if no record found return null
            return null;
        }
        //
        //  can we use the toArray() converter?
        //
        queryResult = new String[recSize][];
        for (int i = 0; i < recSize; i++) {
            queryResult[i] = (String[]) listOfValidRecords.get(i);
        }
    }
    return queryResult;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ResultSet(java.sql.ResultSet) LogRecordSorter(com.sun.identity.log.util.LogRecordSorter) SQLException(java.sql.SQLException) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) SQLException(java.sql.SQLException) AMLogException(com.sun.identity.log.AMLogException) ResultSetMetaData(java.sql.ResultSetMetaData) Iterator(java.util.Iterator) ResultSet(java.sql.ResultSet) AMLogException(com.sun.identity.log.AMLogException) HashSet(java.util.HashSet)

Example 2 with AMLogException

use of com.sun.identity.log.AMLogException in project OpenAM by OpenRock.

the class LogReadDBHandler method logRecRead.

/**
     * LogReader calls this method. It collects header, records,
     * applies query (if any), sorts (if asked) the records on field, checks
     * the max records to return, collects all the recods and returns.
     *
     * @param tableName db table name
     * @param logQuery is user specified qury chriteria with sorting requirement
     * @param logMgr the log manager associated with this handler
     * @param sourceData it specifies whether return data should be original
     *        data received by logger (source) or formatted data as in file.
     * @return all the matched records with query
     * @throws IOException if it fails to read log records.
     * @throws NoSuchFieldException if it fails to retrieve the name of field.
     * @throws IllegalArgumentException if query has wrong value.
     * @throws RuntimeException if it fails to retrieve log record.
     * @throws SQLException if it fails to process sql query.
     * @throws Exception if it fails any of operation.
     */
public String[][] logRecRead(String tableName, LogQuery logQuery, java.util.logging.LogManager logMgr, boolean sourceData) throws IOException, NoSuchFieldException, IllegalArgumentException, RuntimeException, SQLException, Exception {
    String sortField = null;
    // if the object is persistence use it otherwise don't
    this.cleaner();
    tableName = tableName.replace('.', '_');
    try {
        this.databaseURL = logMgr.getProperty(LogConstants.LOG_LOCATION);
        this.dbDriver = logMgr.getProperty(LogConstants.DB_DRIVER);
        this.dbUserName = logMgr.getProperty(LogConstants.DB_USER);
        this.dbPassWord = logMgr.getProperty(LogConstants.DB_PASSWORD);
        this.maxRecordsStr = logMgr.getProperty(LogConstants.MAX_RECORDS);
    } catch (Exception e) {
        Debug.error("DBLogRecRead:config: ", e);
        // rethrow the exception
        throw e;
    }
    if (this.dbDriver.toLowerCase().indexOf("oracle") != -1) {
        isMySQL = false;
    } else if (this.dbDriver.toLowerCase().indexOf("mysql") != -1) {
        isMySQL = true;
    } else {
        isMySQL = false;
        Debug.warning("DBlogRecRead:assuming driver: '" + this.dbDriver + "' is Oracle-compatible.");
    }
    String selectStr;
    if (sourceData == true) {
        String temps = logQuery.getSortingField();
        if (temps != null) {
            sortField = temps.trim();
        }
        // default all
        String columns = "*";
        ArrayList sCol = logQuery.getColumns();
        if (sCol != null) {
            StringBuilder colSB = new StringBuilder();
            int sSize = sCol.size();
            for (int i = 0; i < sSize; i++) {
                colSB.append((String) sCol.get(i));
                if ((i + 1) < sSize) {
                    colSB.append(", ");
                }
            }
            columns = colSB.toString();
        }
        selectStr = lq2Select(tableName, columns, logQuery);
        if (Debug.messageEnabled()) {
            Debug.message("logRecRead/4:selectStr = " + selectStr);
        }
    } else {
        selectStr = lq2Select(tableName, null, null);
        if (Debug.messageEnabled()) {
            Debug.message("logRecRead/4.2:selectStr = " + selectStr);
        }
    }
    try {
        this.maxRecords = Integer.parseInt(maxRecordsStr);
    } catch (NumberFormatException nfe) {
        if (Debug.warningEnabled()) {
            Debug.warning("DBlogRecRead: maxRecords error (" + maxRecordsStr + "), set to MAX");
        }
        this.maxRecords = LogConstants.MAX_RECORDS_DEFAULT_INT;
    }
    String[][] tableResults;
    try {
        connectToDatabase(dbUserName, dbPassWord);
    } catch (SQLException sqe) {
        Debug.error("DBlogRecRead:connect:SQE:code=" + sqe.getErrorCode() + ", msg=" + sqe.getMessage());
        // rethrow for LogReader to catch
        throw sqe;
    } catch (ClassNotFoundException cnfe) {
        // rethrow for LogReader to catch
        throw cnfe;
    }
    String selStr = selectStr;
    Statement stmt = null;
    int numberOfRows = 0;
    try {
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        if (Debug.messageEnabled()) {
            Debug.message("DBlogRecRead:about to execute: " + selStr);
        }
        ResultSet rs = stmt.executeQuery(selStr);
        //
        //  fetchsize appears to be 10 from rs.getFetchSize();
        //
        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        if (Debug.messageEnabled()) {
            Debug.message("DBlogRecRead:#columns = " + numberOfColumns);
        }
        //
        //  these are the column (field) names
        //
        String[] spltHdrStr = new String[numberOfColumns];
        for (int i = 1; i <= numberOfColumns; i++) {
            String tempstr = rsmd.getColumnName(i);
            if (Debug.messageEnabled()) {
                Debug.message("DBlogRecRead:col #" + i + " name = " + tempstr);
            }
            spltHdrStr[i - 1] = tempstr;
        }
        listOfValidRecords.add(spltHdrStr);
        // have to figure out #rows
        while (rs.next()) {
            numberOfRows++;
        }
        if (Debug.messageEnabled()) {
            Debug.message("DBlogRecRead:#rows = " + numberOfRows);
        }
        if (numberOfRows == 0) {
            stmt.close();
            try {
                conn.close();
            } catch (SQLException ex) {
                //
                //  might not care about this too much...?
                //
                Debug.error("DBlogRecRead:rows=0:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
            }
            //
            //  should be at least the column names
            //
            int recSize = listOfValidRecords.size();
            if (recSize <= 0) {
                // if no record found return null
                return null;
            }
            queryResult = new String[recSize][];
            for (int i = 0; i < recSize; i++) {
                queryResult[i] = (String[]) listOfValidRecords.get(i);
            }
            return queryResult;
        }
        if (numberOfRows > this.maxRecords) {
            stmt.close();
            try {
                conn.close();
            } catch (SQLException ex) {
                //
                //  don't care about this too much...
                //
                Debug.error("DBlogRecRead:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
            }
            throw new AMLogException(AMLogException.LOG_DB_TOOMANYRECORDS);
        }
        //
        //  reset to the beginning
        //
        boolean isFirst = rs.first();
        if (isFirst == false) {
            Debug.error("DBlogRecRead:first() is false!");
        }
        int rowsToAlloc = numberOfRows;
        if (logQuery.getNumRecordsWanted() == LogQuery.MOST_RECENT_MAX_RECORDS) {
            //
            if (numberOfRows > this.maxRecords) {
                rowsToAlloc = this.maxRecords;
            }
        }
        tableResults = new String[rowsToAlloc][numberOfColumns];
        String result = null;
        int rowCount = 0;
        //
        //  if LogQuery.MOST_RECENT_MAX_RECORDS selected,
        //  then we just have to get the "this.maxRecords" records.
        //
        int skipThisManyRecords = 0;
        if (logQuery.getNumRecordsWanted() == LogQuery.MOST_RECENT_MAX_RECORDS) {
            if (numberOfRows > this.maxRecords) {
                skipThisManyRecords = numberOfRows - this.maxRecords;
            }
        }
        if (Debug.messageEnabled()) {
            Debug.message("DBlogRecRead:skipThisMany = " + skipThisManyRecords);
        }
        for (int i = 0; i < numberOfColumns; i++) {
            result = rs.getString(i + 1);
            tableResults[0][i] = result;
        }
        rowCount = 1;
        while (rs.next()) {
            if (skipThisManyRecords-- <= 0) {
                for (int i = 0; i < numberOfColumns; i++) {
                    result = rs.getString(i + 1);
                    tableResults[rowCount][i] = result;
                }
                rowCount++;
            }
        }
        stmt.close();
    } catch (SQLException se) {
        Debug.error("DBlogRecRead:query:SQE:code=" + se.getErrorCode() + ", msg=" + se.getMessage());
        // rethrow for LogReader to catch
        throw se;
    }
    try {
        this.getRecords(tableResults, sourceData);
    } catch (IOException e) {
        // catch & rethrow it
        throw e;
    } catch (IllegalArgumentException e) {
        // catch & rethrow it
        throw e;
    } catch (RuntimeException e) {
        // catch & rethrow it
        throw e;
    } catch (Exception e) {
        // catch & rethrow it
        throw e;
    }
    int recSize = listOfValidRecords.size();
    // checks whether it has got any record or not
    if (recSize <= 0) {
        // if no record found return null
        return null;
    }
    try {
        conn.close();
    } catch (SQLException ex) {
        //
        //  might not care about this too much...?
        //
        Debug.error("DBlogRecRead:conn.close (" + ex.getErrorCode() + "): " + ex.getMessage());
    }
    queryResult = new String[recSize][];
    for (int i = 0; i < recSize; i++) {
        queryResult[i] = (String[]) listOfValidRecords.get(i);
    }
    return queryResult;
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) SQLException(java.sql.SQLException) AMLogException(com.sun.identity.log.AMLogException) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) AMLogException(com.sun.identity.log.AMLogException)

Example 3 with AMLogException

use of com.sun.identity.log.AMLogException in project OpenAM by OpenRock.

the class AMLogTest method setup.

/**
     * Before running the test(s), ensure:
     *   o the log svc config is set with buffer timer off, buff size = 1
     *
     * @throws Exception if an AMLogException occurs
     */
@Parameters({ "logtest-log-location", "logtest-logname" })
@BeforeTest(groups = { "api-adminwrite", "api-adminread" })
public void setup(String logLoc, String logFName) throws Exception {
    Object[] params = { theRealm, logLoc, logFName };
    entering("setup", params);
    setbufferSizer("OFF", "1");
    try {
        lmgr.readConfiguration();
        String tlogLoc = lmgr.getProperty(LogConstants.LOG_LOCATION);
        if ((tlogLoc == null) || (tlogLoc.length() == 0)) {
            tlogLoc = logLoc;
        }
        if ((logFName != null) && (logFName.length() > 0)) {
            logName = logFName;
        } else {
            logName = defaultLogName;
        }
        loggingLocation = tlogLoc;
        logPath = loggingLocation + "/" + logName;
        File f1 = new File(logPath);
        if (f1.exists() && (f1.length() > 0)) {
            f1.delete();
        }
        logger = (Logger) Logger.getLogger(logFName);
    } catch (Exception e) {
        log(Level.SEVERE, "setup", e.getMessage(), params);
        e.printStackTrace();
        throw e;
    }
    exiting("setup");
}
Also used : File(java.io.File) AMLogException(com.sun.identity.log.AMLogException) SMSException(com.sun.identity.sm.SMSException) IOException(java.io.IOException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException) Parameters(org.testng.annotations.Parameters) BeforeTest(org.testng.annotations.BeforeTest)

Example 4 with AMLogException

use of com.sun.identity.log.AMLogException in project OpenAM by OpenRock.

the class AMLogTest method readAllRecords.

private void readAllRecords(String fileName, SSOToken ssot, int numRecsExp) throws AMLogException {
    int numRecs = 0;
    try {
        String[][] result = LogReader.read(fileName, ssot);
        numRecs = Array.getLength(result);
    } catch (AMLogException ale) {
        throw new AMLogException("readAllRecords:AMLogException: " + ale.getMessage());
    } catch (NoSuchFieldException nsfe) {
        throw new AMLogException("readAllRecords:NoSuchField: " + nsfe.getMessage());
    } catch (IOException ioe) {
        throw new AMLogException("readAllRecords:IOException: " + ioe.getMessage());
    } catch (Exception e) {
        throw new AMLogException("readAllRecords:Exception: " + e.getMessage());
    }
    // first record has the column names
    if (numRecs != (numRecsExp + 2)) {
        throw new AMLogException("Number of records read (" + numRecs + ") doesn't match expected (" + (numRecsExp + 1) + ")");
    }
}
Also used : AMLogException(com.sun.identity.log.AMLogException) IOException(java.io.IOException) AMLogException(com.sun.identity.log.AMLogException) SMSException(com.sun.identity.sm.SMSException) IOException(java.io.IOException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SSOException(com.iplanet.sso.SSOException)

Example 5 with AMLogException

use of com.sun.identity.log.AMLogException in project OpenAM by OpenRock.

the class AMLogTest method writeAdminLogRecord.

/**
     *  need:
     *    only the amadmin SSOToken (used in LogRecord), since
     *      can't (currently) use user SSOTokens.  also means
     *      the log delegation can't be tested.
     *    column values
     *      data
     *      module_name
     *      domain
     *      log_level
     *      login_id
     *      ip_addr
     *      host_name
     *      message_id
     *    number of records to write
     *
     */
@Parameters({ "logwrite-data", "logwrite-modulename", "logwrite-domain", "logwrite-log-level", "logwrite-login-id", "logwrite-ip-addr", "logwrite-host-name", "logwrite-message-id", "logwrite-number-of-records" })
@Test(groups = { "api-adminwrite" })
public void writeAdminLogRecord(String rData, String rModuleName, String rDomain, String rLogLevel, String rLoginId, String rIPAddr, String rHostName, String rMsgId, String rNumRecs) throws AMLogException {
    LogRecord lR = null;
    Level llevel = null;
    int numRecs = 0;
    if ((rNumRecs != null) && (rNumRecs.length() > 0)) {
        try {
            numRecs = Integer.parseInt(rNumRecs);
        } catch (NumberFormatException nfe) {
            log(Level.WARNING, "writeAdminLogRecord", nfe.getMessage());
            numRecs = 1;
        }
    }
    llevel = getLogLevel(rLogLevel);
    /**
         *  DOMAIN, LOGIN_ID, IP_ADDR, and HOST_NAME are extracted from the
         *  SSOToken and added by the LogRecord handling.  if any values are
         *  provided to the test, then they'll be added.
         */
    int totalRecs = 0;
    SSOToken adminToken = getAdminSSOToken();
    /*
         *  put variable data in ("msgDataPrefix + i") reverse
         *  order, so we can test sortBy in the read test.
         */
    for (int i = (numRecs - 1); i >= 0; i--) {
        lR = new LogRecord(llevel, msgDataPrefix + i + "|" + rData, adminToken);
        if ((rDomain != null) && (rDomain.length() > 0)) {
            lR.addLogInfo(LogConstants.DOMAIN, rDomain);
        }
        // ignore rLoginId parameter; use "amAdmin"
        lR.addLogInfo(LogConstants.LOGIN_ID, "amAdmin");
        if ((rIPAddr != null) && (rIPAddr.length() > 0)) {
            lR.addLogInfo(LogConstants.IP_ADDR, rIPAddr);
        }
        if ((rHostName != null) && (rHostName.length() > 0)) {
            lR.addLogInfo(LogConstants.HOST_NAME, rHostName);
        }
        if ((rModuleName != null) && (rModuleName.length() > 0)) {
            lR.addLogInfo(LogConstants.MODULE_NAME, rModuleName);
        }
        if ((rMsgId != null) && (rMsgId.length() > 0)) {
            String msgid = rMsgId + i;
            lR.addLogInfo(LogConstants.MESSAGE_ID, msgid);
        }
        try {
            logger.log(lR, adminToken);
            totalRecs++;
        } catch (AMLogException alex) {
            //  unexpected exception
            log(Level.SEVERE, "writeAdminLogRecord", alex.getMessage());
            throw alex;
        }
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) LogRecord(com.sun.identity.log.LogRecord) AMLogException(com.sun.identity.log.AMLogException) Level(java.util.logging.Level) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) AfterTest(org.testng.annotations.AfterTest)

Aggregations

AMLogException (com.sun.identity.log.AMLogException)10 IOException (java.io.IOException)5 SSOException (com.iplanet.sso.SSOException)4 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)4 LogRecord (com.sun.identity.log.LogRecord)3 SMSException (com.sun.identity.sm.SMSException)3 SQLException (java.sql.SQLException)3 Statement (java.sql.Statement)3 SSOToken (com.iplanet.sso.SSOToken)2 Logger (com.sun.identity.log.Logger)2 ResultSet (java.sql.ResultSet)2 ResultSetMetaData (java.sql.ResultSetMetaData)2 ArrayList (java.util.ArrayList)2 Iterator (java.util.Iterator)2 BeforeTest (org.testng.annotations.BeforeTest)2 Parameters (org.testng.annotations.Parameters)2 ThreadPoolException (com.iplanet.am.util.ThreadPoolException)1 ConnectionException (com.iplanet.log.ConnectionException)1 DriverLoadException (com.iplanet.log.DriverLoadException)1 RequestSet (com.iplanet.services.comm.share.RequestSet)1