Search in sources :

Example 31 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class TwitterAdapter method setSignPost.

public void setSignPost(Binary b) throws UserException {
    ObjectInputStream ois;
    try {
        ois = new ObjectInputStream(b.getDataAsStream());
        mySignPost = (OAuthSignpostClient) ois.readObject();
    } catch (Exception e) {
        throw new UserException(-1, e.getMessage(), e);
    }
}
Also used : UserException(com.dexels.navajo.script.api.UserException) UserException(com.dexels.navajo.script.api.UserException) TwitterException(winterwell.jtwitter.TwitterException) MappableException(com.dexels.navajo.script.api.MappableException) ObjectInputStream(java.io.ObjectInputStream)

Example 32 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class SPMap method getResultSet.

@SuppressWarnings("deprecation")
@Override
protected ResultSetMap[] getResultSet(boolean updateOnly) throws UserException {
    if (debug) {
        logger.info("TIMING SPMAP, start query... : " + update);
    }
    long start = System.currentTimeMillis();
    requestCount++;
    ResultSet rs = null;
    try {
        createConnection();
        if (con == null) {
            throw new UserException(-1, "in SQLMap. Could not open database connection [driver = " + driver + ", url = " + url + ", username = '" + username + "', password = '" + password + "']");
        }
        if (resultSet == null) {
            String spName = "";
            // Close previously open call statements:
            if (callStatement != null) {
                try {
                    callStatement.close();
                } catch (Exception e) {
                    logger.warn("Non fatal error closing statement", e);
                }
                callStatement = null;
                openCallStatements--;
            }
            if (query != null) {
                callStatement = con.prepareCall(query);
                openCallStatements++;
                if (query.indexOf("Call") != -1 && query.indexOf("(") != -1) {
                    spName = query.substring(query.indexOf("Call") + 5, query.indexOf("("));
                }
            } else {
                callStatement = con.prepareCall(update);
                openCallStatements++;
                if (update.indexOf("Call") != -1 && update.indexOf("(") != -1) {
                    spName = update.substring(update.indexOf("Call") + 5, update.indexOf("("));
                }
            }
            if (debug) {
                logger.info("callStatement = " + callStatement.toString());
            }
            if (debug) {
                logger.info("parameters = " + parameters);
            }
            if (parameters != null) {
                int spIndex = 0;
                for (int i = 0; i < parameters.size(); i++) {
                    Object param = parameters.get(i);
                    int type = ((Integer) parameterTypes.get(i)).intValue();
                    if (debug) {
                        logger.info("Setting parameter: " + param + "(" + (param != null ? param.getClass().toString() : "") + "), type = " + type);
                    }
                    if (type == INPUT_PARAM) {
                        spIndex++;
                        SQLMapHelper.setParameter(callStatement, param, i, this, this.getDbIdentifier(), this.isLegacyMode, this.debug, this.myAccess);
                    } else {
                        int sqlType = ((Integer) lookupTable.get(param)).intValue();
                        callStatement.registerOutParameter(i + 1, sqlType);
                    }
                }
            }
            if (query != null) {
                // logger.info("\nCalling query - callStatement.query()");
                rs = callStatement.executeQuery();
            // logger.info("\nCalled query");
            } else {
                // logger.info("\nCalling update - callStatement.execute()");
                callStatement.execute();
            // logger.info("\nCalled update");
            }
        }
        if (rs != null) {
            ResultSetMetaData meta = rs.getMetaData();
            int columns = meta.getColumnCount();
            ArrayList dummy = new ArrayList();
            int index = 1;
            remainCount = 0;
            while (rs.next()) {
                if ((index >= startIndex) && (index <= endIndex)) {
                    ResultSetMap rm = new ResultSetMap();
                    for (int i = 1; i < (columns + 1); i++) {
                        String param = meta.getColumnName(i);
                        int type = meta.getColumnType(i);
                        // logger.info(param + " has type " + getType(type));
                        Object value = null;
                        java.util.Calendar c = java.util.Calendar.getInstance();
                        if (rs.getString(i) != null) {
                            value = SQLMapHelper.getColumnValue(rs, type, i);
                        }
                        rm.addValue(param.toUpperCase(), value);
                    }
                    dummy.add(rm);
                    viewCount++;
                } else if (index >= startIndex) {
                    remainCount++;
                }
                rowCount++;
                index++;
            }
            resultSet = new ResultSetMap[dummy.size()];
            resultSet = (ResultSetMap[]) dummy.toArray(resultSet);
        }
    } catch (SQLException sqle) {
        AuditLog.log(sqle.getLocalizedMessage() + "/" + sqle.getSQLState(), "SPMap", sqle, Level.SEVERE, myAccess.accessID);
        throw new UserException(-1, sqle.getLocalizedMessage() + "/" + sqle.getSQLState(), sqle);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace(Access.getConsoleWriter(myAccess));
            }
            rs = null;
        }
        this.resetAll();
    }
    long end = System.currentTimeMillis();
    double total = (end - start) / 1000.0;
    totaltiming += total;
    if (debug) {
        logger.info("finished " + total + " seconds. Average query time: " + (totaltiming / requestCount) + " (" + requestCount + ")");
    }
    return resultSet;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) ResultSetMap(com.dexels.navajo.adapter.sqlmap.ResultSetMap) UserException(com.dexels.navajo.script.api.UserException) SQLException(java.sql.SQLException) MappableException(com.dexels.navajo.script.api.MappableException) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) UserException(com.dexels.navajo.script.api.UserException)

Example 33 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class SPMap method setUpdate.

@Override
public void setUpdate(String newUpdate) throws UserException {
    if ((this.update != null) || (this.query != null)) {
        throw new UserException(-1, "SPMap does not allow for multiple queries/updates, use a new SPMap");
    }
    // Close previous callStatement if it exists.
    try {
        if (callStatement != null) {
            callStatement.close();
            callStatement = null;
            openCallStatements--;
        }
    } catch (Exception e) {
        e.printStackTrace(Access.getConsoleWriter(myAccess));
    }
    super.setUpdate(newUpdate);
    parameterTypes = new ArrayList();
}
Also used : ArrayList(java.util.ArrayList) UserException(com.dexels.navajo.script.api.UserException) UserException(com.dexels.navajo.script.api.UserException) SQLException(java.sql.SQLException) MappableException(com.dexels.navajo.script.api.MappableException)

Example 34 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class SPMap method getOutputParameter.

public Object getOutputParameter(Integer i) throws UserException {
    int index = i.intValue();
    // logger.info("in getOutputParameter("+index+")");
    Object value = null;
    if (callStatement != null) {
        try {
            // logger.info("parameters = " + parameters);
            if (index > parameters.size()) {
                throw new UserException(-1, "Outputparameter index out of range: " + i.intValue());
            }
            String type = (String) parameters.get(index - 1);
            if (lookupTable.get(type) == null) {
                throw new UserException(-1, "Outputparameter index out of range, trying to read a normal parameter as an output parameter: " + i.intValue());
            }
            int sqlType = ((Integer) lookupTable.get(type)).intValue();
            java.util.Calendar c = java.util.Calendar.getInstance();
            switch(sqlType) {
                case Types.VARCHAR:
                case Types.CHAR:
                    value = callStatement.getString(index);
                    break;
                case Types.BIT:
                    value = Boolean.valueOf(callStatement.getBoolean(index));
                    break;
                case Types.DATE:
                    if (callStatement.getDate(index) != null) {
                        Date d = callStatement.getDate(index, c);
                        long l = d.getTime();
                        value = new java.util.Date(l);
                    }
                    break;
                case // For Oracle; timestamp with timezone, treat this as clocktime.
                -101:
                    if (callStatement.getTimestamp(index) != null) {
                        Timestamp ts = callStatement.getTimestamp(index, c);
                        long l = ts.getTime();
                        value = new ClockTime(new java.util.Date(l));
                    }
                    break;
                case Types.TIMESTAMP:
                    if (callStatement.getTimestamp(index) != null) {
                        Timestamp ts = callStatement.getTimestamp(index, c);
                        long l = ts.getTime();
                        value = new java.util.Date(l);
                    }
                    break;
                case Types.INTEGER:
                    value = Integer.valueOf(callStatement.getInt(index));
                    break;
                case Types.NUMERIC:
                    ResultSetMetaData meta = callStatement.getMetaData();
                    int prec = meta.getPrecision(index);
                    int scale = meta.getScale(index);
                    if (scale == 0) {
                        value = Integer.valueOf(callStatement.getInt(index));
                    } else {
                        value = Double.valueOf(callStatement.getString(index));
                    }
                    break;
                case Types.SMALLINT:
                case Types.TINYINT:
                    value = Integer.valueOf(callStatement.getInt(index));
                    break;
                case Types.DOUBLE:
                case Types.FLOAT:
                    value = Double.valueOf(callStatement.getDouble(index));
                    break;
                default:
                    value = callStatement.getString(index);
                    break;
            }
        } catch (SQLException sqle) {
            AuditLog.log("SPMap", sqle.getLocalizedMessage() + "/" + sqle.getSQLState(), sqle, Level.SEVERE, myAccess.accessID);
            throw new UserException(-1, sqle.getMessage(), sqle);
        }
        return value;
    } else {
        return "";
    }
}
Also used : SQLException(java.sql.SQLException) ClockTime(com.dexels.navajo.document.types.ClockTime) Timestamp(java.sql.Timestamp) Date(java.sql.Date) ResultSetMetaData(java.sql.ResultSetMetaData) UserException(com.dexels.navajo.script.api.UserException)

Example 35 with UserException

use of com.dexels.navajo.script.api.UserException in project navajo by Dexels.

the class SQLMap method createConnection.

protected final void createConnection() throws SQLException, UserException {
    if (this.debug) {
        Access.writeToConsole(myAccess, this.getClass() + ": in createConnection()\n");
    }
    if (transactionContext != -1) {
        GrusConnection gc = null;
        if (GrusProviderFactory.getInstance() != null) {
            gc = GrusProviderFactory.getInstance().requestConnection(transactionContext);
        } else {
            gc = LegacyDbConnectionBroker.getGrusConnection(transactionContext);
        }
        if (gc == null) {
            throw new UserException(-1, "Invalid transaction context set: " + transactionContext);
        }
        con = gc.getConnection();
        if (con == null) {
            throw new UserException(-1, "Invalid transaction context set: " + transactionContext);
        }
        // Set myConnectionBroker.
        myConnectionBroker = gc.getMyBroker();
        // Make sure to set connection id.
        this.connectionId = transactionContext;
    }
    if (con == null) {
        if (this.debug) {
            Access.writeToConsole(myAccess, "in createConnection() for datasource " + datasource + " and username " + username + "\n");
        }
        if (GrusProviderFactory.getInstance() != null) {
            // in multitenant or OSGi
            if (transactionContext != -1) {
                gc = GrusProviderFactory.getInstance().requestConnection(transactionContext);
                this.ownConnection = false;
            } else {
                String instance = this.instance;
                if (myAccess != null) {
                    instance = myAccess.getTenant();
                }
                if (GrusProviderFactory.getInstance().threadContainsConnection(instance, datasource)) {
                    logger.debug("Opening yet another connection {} for {} in the same thread!", datasource, instance);
                // gc = GrusProviderFactory.getInstance().requestExistingConnection(instance, datasource);
                // this.ownConnection = false;
                // transactionContext = ((Long) gc.getId()).intValue();
                }
                gc = GrusProviderFactory.getInstance().requestConnection(instance, datasource);
                this.ownConnection = true;
            }
            multiTenantGrusConnection = gc;
        } else {
            myConnectionBroker = null;
            if (fixedBroker != null) {
                myConnectionBroker = fixedBroker.get(this.datasource, null, null);
            }
            if (myConnectionBroker == null) {
                throw new UserException(-1, "Could not create connection to datasource " + this.datasource + ", using username " + this.username + ", fixedBroker = " + fixedBroker + " for tenant: " + instance);
            }
            gc = myConnectionBroker.getGrusConnection();
        }
        if (gc == null) {
            AuditLog.log("SQLMap", "Could (still) not connect to database: " + datasource + " (" + this.username + ")" + ", check your connection", Level.SEVERE);
            throw new UserException(-1, "Could not connect to database: " + datasource + " (" + this.username + ")" + ", check your connection");
        }
        con = gc.getConnection();
        if (con == null) {
            AuditLog.log("SQLMap", "Could (still) not connect to database: " + datasource + " (" + this.username + ")" + ", check your connection", Level.SEVERE);
            throw new UserException(-1, "Could not connect to database: " + datasource + " (" + this.username + ")" + ", check your connection");
        // }
        } else {
            if (this.debug) {
                Access.writeToConsole(myAccess, this.getClass() + ": returned a good connection from the broker manager\n");
            }
        }
        // Set current schema if username was specified...
        if (this.alternativeUsername != null) {
            // Only works for Oracle...
            try {
                // Now set current_schema...
                PreparedStatement stmt = null;
                if (SQLMapConstants.POSTGRESDB.equals(this.getDbIdentifier()) || SQLMapConstants.ENTERPRISEDB.equals(this.getDbIdentifier())) {
                    stmt = con.prepareStatement("SET SEARCH_PATH TO " + this.alternativeUsername + ",public,oracle");
                } else {
                    stmt = con.prepareStatement("ALTER SESSION SET CURRENT_SCHEMA = " + this.alternativeUsername);
                }
                stmt.executeUpdate();
                stmt.close();
            } catch (Exception e) {
                logger.error("Looking for schema based on username: " + this.alternativeUsername, e);
                throw new UserException(-1, "Switching to schema based on username " + this.alternativeUsername + " failed");
            }
        }
        if (con != null && (myConnectionBroker == null || myConnectionBroker.hasAutoCommit())) {
            con.setAutoCommit(autoCommit);
            if (!con.getAutoCommit()) {
                con.commit();
            }
            // con.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
            if (transactionIsolation != -1) {
                con.setTransactionIsolation(transactionIsolation);
            }
        // Set session identification.
        // SessionIdentification.setSessionId(this.getMetaData() != null ? this.getMetaData().getVendor(): "Unknown", con, this.myAccess);
        }
        if (this.con != null) {
            this.connectionId = (int) gc.getId();
            if (this.debug) {
                Access.writeToConsole(myAccess, this.getClass() + ": put connection no. " + this.connectionId + " into the connection map\n");
            }
        }
    }
}
Also used : GrusConnection(org.dexels.grus.GrusConnection) PreparedStatement(java.sql.PreparedStatement) UserException(com.dexels.navajo.script.api.UserException) NavajoException(com.dexels.navajo.document.NavajoException) UserException(com.dexels.navajo.script.api.UserException) MappableException(com.dexels.navajo.script.api.MappableException) SQLException(java.sql.SQLException)

Aggregations

UserException (com.dexels.navajo.script.api.UserException)113 MappableException (com.dexels.navajo.script.api.MappableException)54 IOException (java.io.IOException)33 NavajoException (com.dexels.navajo.document.NavajoException)25 Message (com.dexels.navajo.document.Message)22 SQLException (java.sql.SQLException)19 SystemException (com.dexels.navajo.script.api.SystemException)18 Binary (com.dexels.navajo.document.types.Binary)14 ConditionErrorException (com.dexels.navajo.server.ConditionErrorException)13 Property (com.dexels.navajo.document.Property)12 ArrayList (java.util.ArrayList)12 Navajo (com.dexels.navajo.document.Navajo)11 AuthorizationException (com.dexels.navajo.script.api.AuthorizationException)11 ResultSet (java.sql.ResultSet)11 MappingException (com.dexels.navajo.script.api.MappingException)10 ResultSetMetaData (java.sql.ResultSetMetaData)9 Element (org.w3c.dom.Element)8 CompilationException (com.dexels.navajo.script.api.CompilationException)7 File (java.io.File)7 NodeList (org.w3c.dom.NodeList)7