Example usage for java.sql SQLException toString

List of usage examples for java.sql SQLException toString

Introduction

In this page you can find the example usage for java.sql SQLException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.etudes.component.app.jforum.dao.generic.UserDaoGeneric.java

/**
 * Mark user all read time /*  ww  w  . j ava  2s. c  o m*/
 * 
 * @param siteId   Site id
 * 
 * @param userId   user id
 * 
 * @param markAllTime   Mark all time
 */
protected void markAllReadTimeTx(final String siteId, final int userId, final Date markAllTime) {
    this.sqlService.transact(new Runnable() {
        public void run() {
            try {
                String sql;
                Object[] fields;
                int i = 0;

                sql = "SELECT course_id, user_id, visit_time, markall_time FROM jforum_sakai_sessions WHERE course_id = ? AND user_id = ?";

                fields = new Object[2];
                fields[i++] = siteId;
                fields[i++] = userId;

                final List<Date> markReadTime = new ArrayList<Date>();

                sqlService.dbRead(sql, fields, new SqlReader() {
                    public Object readSqlResultRecord(ResultSet result) {
                        try {
                            markReadTime.add(result.getTimestamp("markall_time"));
                            return null;
                        } catch (SQLException e) {
                            if (logger.isWarnEnabled()) {
                                logger.warn("selectMarkAllReadTime: " + e, e);
                            }
                            return null;
                        }
                    }
                });

                boolean dataExist = false;
                if (markReadTime.size() > 0) // there should be only one record
                {
                    dataExist = true;
                }

                sql = null;

                if (!dataExist) {
                    // add user site mark all read time
                    sql = "INSERT INTO jforum_sakai_sessions (course_id, user_id, visit_time, markall_time) VALUES (?, ?, ?, ?)";

                    i = 0;
                    fields = new Object[4];

                    fields[i++] = siteId;
                    fields[i++] = userId;
                    fields[i++] = new Timestamp(new Date().getTime());
                    fields[i++] = new Timestamp(markAllTime.getTime());
                } else {
                    // update user site mark all read time                  
                    sql = "UPDATE jforum_sakai_sessions SET markall_time = ? WHERE course_id = ? AND user_id = ?";

                    i = 0;
                    fields = new Object[3];

                    fields[i++] = new Timestamp(markAllTime.getTime());
                    ;
                    fields[i++] = siteId;
                    fields[i++] = userId;
                }

                try {
                    sqlService.dbWrite(sql.toString(), fields);
                } catch (Exception e) {
                    if (logger.isErrorEnabled()) {
                        logger.error(e, e);
                    }
                }

                // mark all marked unread topic's to read
                sql = "SELECT tm.topic_id, tm.user_id, tm.mark_time, tm.is_read FROM jforum_sakai_course_categories scc, jforum_forums f, jforum_topics t, jforum_topics_mark tm "
                        + "WHERE scc.categories_id = f.categories_id AND f.forum_id = t.forum_id AND t.topic_id = tm.topic_id AND tm.user_id = ? AND tm.is_read = ? AND scc.course_id = ?";
                i = 0;
                fields = new Object[3];
                fields[i++] = userId;
                fields[i++] = 1;
                fields[i++] = siteId;

                sqlService.dbRead(sql, fields, new SqlReader() {
                    public Object readSqlResultRecord(ResultSet result) {
                        try {
                            int topicId = result.getInt("topic_id");
                            int userId = result.getInt("user_id");
                            topicDao.updateTopicMarkTime(topicId, userId, new Date(), true);
                            return null;
                        } catch (SQLException e) {
                            if (logger.isWarnEnabled()) {
                                logger.warn("selectTopicsMarkedUnread-markTopicRead: " + e, e);
                            }
                            return null;
                        }
                    }
                });
            } catch (Exception e) {
                if (logger.isErrorEnabled()) {
                    logger.error(e.toString(), e);
                }

                throw new RuntimeException("Error while adding or updating user mark all read time.", e);
            }
        }
    }, "markUserAllReadTime: " + siteId + ":" + userId);
}

From source file:fi.helsinki.lib.simplerest.CommunitiesResource.java

@Post
public Representation addCommunity(InputRepresentation rep) {
    Context c = null;/*  ww w.j  a  v a 2s.co  m*/
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }
    } catch (SQLException e) {
        return errorInternal(c, "SQLException");
    }

    String msg = null;
    String url = baseUrl();
    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        // Logo
        String bitstreamMimeType = null;
        byte[] logoBytes = null;

        // Community
        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = null;

        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8");

                if (key.equals("name")) {
                    name = value;
                } else if (key.equals("short_description")) {
                    shortDescription = value;
                } else if (key.equals("introductory_text")) {
                    introductoryText = value;
                } else if (key.equals("copyright_text")) {
                    copyrightText = value;
                } else if (key.equals("side_bar_text")) {
                    sideBarText = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (logoBytes != null) {
                    return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // TODO: Refer to comments in....
                String fileName = fileItemStream.getName();
                if (fileName.length() == 0) {
                    continue;
                }
                int lastDot = fileName.lastIndexOf('.');
                if (lastDot != -1) {
                    String extension = fileName.substring(lastDot + 1);
                    extension = extension.toLowerCase();
                    if (extension.equals("jpg") || extension.equals("jpeg")) {
                        bitstreamMimeType = "image/jpeg";
                    } else if (extension.equals("png")) {
                        bitstreamMimeType = "image/png";
                    } else if (extension.equals("gif")) {
                        bitstreamMimeType = "image/gif";
                    }
                }
                if (bitstreamMimeType == null) {
                    String err = "The logo filename extension was not recognised.";
                    return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST);
                }

                InputStream inputStream = fileItemStream.openStream();
                logoBytes = IOUtils.toByteArray(inputStream);
            }
        }

        msg = "Community created.";
        Community subCommunity = community.createSubcommunity();
        subCommunity.setMetadata("name", name);
        subCommunity.setMetadata("short_description", shortDescription);
        subCommunity.setMetadata("introductory_text", introductoryText);
        subCommunity.setMetadata("copyright_text", copyrightText);
        subCommunity.setMetadata("side_bar_text", sideBarText);
        if (logoBytes != null) {
            ByteArrayInputStream byteStream;
            byteStream = new ByteArrayInputStream(logoBytes);
            subCommunity.setLogo(byteStream);
        }

        subCommunity.update();
        Bitstream logo = subCommunity.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }
        url += CommunityResource.relativeUrl(subCommunity.getID());
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated(msg, url);
}

From source file:fi.helsinki.lib.simplerest.CollectionsResource.java

@Post
public Representation addCollection(InputRepresentation rep) {
    Context c = null;//from   www  .ja v  a 2 s . com
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }
    } catch (SQLException e) {
        return errorInternal(c, "SQLException");
    }

    String msg = null;
    String url = baseUrl();
    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        // Logo
        String bitstreamMimeType = null;
        byte[] logoBytes = null;

        // Collection
        String name = null;
        String shortDescription = null;
        String introductoryText = null;
        String copyrightText = null;
        String sideBarText = null;
        String provenanceDescription = null;
        String license = null;

        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8");

                if (key.equals("name")) {
                    name = value;
                } else if (key.equals("short_description")) {
                    shortDescription = value;
                } else if (key.equals("introductory_text")) {
                    introductoryText = value;
                } else if (key.equals("copyright_text")) {
                    copyrightText = value;
                } else if (key.equals("side_bar_text")) {
                    sideBarText = value;
                } else if (key.equals("provenance_description")) {
                    provenanceDescription = value;
                } else if (key.equals("license")) {
                    license = value;
                } else {
                    return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (logoBytes != null) {
                    return error(c, "The collection can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST);
                }

                // TODO: Refer to comments in....
                String fileName = fileItemStream.getName();
                if (fileName.length() == 0) {
                    continue;
                }
                int lastDot = fileName.lastIndexOf('.');
                if (lastDot != -1) {
                    String extension = fileName.substring(lastDot + 1);
                    extension = extension.toLowerCase();
                    if (extension.equals("jpg") || extension.equals("jpeg")) {
                        bitstreamMimeType = "image/jpeg";
                    } else if (extension.equals("png")) {
                        bitstreamMimeType = "image/png";
                    } else if (extension.equals("gif")) {
                        bitstreamMimeType = "image/gif";
                    }
                }
                if (bitstreamMimeType == null) {
                    String err = "The logo filename extension was not recognised.";
                    return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST);
                }

                InputStream inputStream = fileItemStream.openStream();
                logoBytes = IOUtils.toByteArray(inputStream);
            }
        }

        Collection collection = community.createCollection();
        collection.setMetadata("name", name);
        collection.setMetadata("short_description", shortDescription);
        collection.setMetadata("introductory_text", introductoryText);
        collection.setMetadata("copyright_text", copyrightText);
        collection.setMetadata("side_bar_text", sideBarText);
        collection.setMetadata("provenance_description", provenanceDescription);
        collection.setMetadata("license", license);
        if (logoBytes != null) {
            ByteArrayInputStream byteStream;
            byteStream = new ByteArrayInputStream(logoBytes);
            collection.setLogo(byteStream);
        }

        collection.update();
        Bitstream logo = collection.getLogo();
        if (logo != null) {
            BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType);
            logo.setFormat(bf);
            logo.update();
        }
        url += CollectionResource.relativeUrl(collection.getID());
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated("Collection created.", url);
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

protected void setDelimitedCase(DatabaseMetaData metaData) {
    try {/*from   w w w.j a va  2s .  c  o m*/
        if (metaData.storesMixedCaseQuotedIdentifiers()) {
            delimitedCase = SCHEMA_CASE_PRESERVE;
        } else if (metaData.storesUpperCaseQuotedIdentifiers()) {
            delimitedCase = SCHEMA_CASE_UPPER;
        } else if (metaData.storesLowerCaseQuotedIdentifiers()) {
            delimitedCase = SCHEMA_CASE_LOWER;
        }
    } catch (SQLException e) {
        getLog().warn("cannot-determine-identifier-case");
        if (getLog().isTraceEnabled()) {
            getLog().trace(e.toString(), e);
        }
    }
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Required prior to using any other methods within this class. This method
 * checks for the existence of the pool attached to the Servlet Context.
 * Once the pool is successfully created subsequent invocations perform no
 * action. The method is static and synchronized to allow for possible
 * multiple invocations of the Sentinel Tool simultaneously. Although the
 * data referenced is not static we don't want to take the chance that the
 * ServletContext.getAttribute() is called, we loose the time slice and upon
 * return from the VM one invocation thinks the pool is missing when another
 * invocation has just successfully created it. This is only called from the
 * Logon Action currently so the overhead inherit with synchronized
 * functions is minimized./*from w  w w  .j  a va  2 s. com*/
 * <p>
 * To use this from a browser servlet, use the method which requires an
 * HttpServletRequest as the first argument to the method.
 *
 * @param dsurl_
 *        The URL entry for the desired database.
 * @param username_
 *        The default database user logon id.
 * @param password_
 *        The password to match the user.
 * @return 0 if successful, otherwise the Oracle error code.
 */
private static synchronized OracleConnectionPoolDataSource setupPool(String dsurl_, String username_,
        String password_) {
    // First register the database driver.
    OracleConnectionPoolDataSource ocpds = null;
    int rc = 0;
    String rcTxt = null;
    try {
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    } catch (SQLException ex) {
        rc = ex.getErrorCode();
        rcTxt = rc + ": " + ex.toString();
    }

    try {
        // Create an the connection pool data source and set the parameters.
        ocpds = new OracleConnectionPoolDataSource();
        if (dsurl_.indexOf(':') > 0) {
            String parts[] = dsurl_.split("[:]");
            ocpds.setDriverType("thin");
            ocpds.setServerName(parts[0]);
            ocpds.setPortNumber(Integer.parseInt(parts[1]));
            ocpds.setServiceName(parts[2]);
        } else {
            ocpds.setDriverType("oci8");
            ocpds.setTNSEntryName(dsurl_);
        }
        ocpds.setUser(username_);
        ocpds.setPassword(password_);
    } catch (SQLException ex) {
        // We have a problem.
        rc = ex.getErrorCode();
        rcTxt = rc + ": " + ex.toString();
        ocpds = null;
    }

    if (rc != 0) {
        // Send a user friendly message to the Logon window and the more
        // detailed
        // message to the console.
        _logger.error(rcTxt);
    }
    return ocpds;
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Create a connection from the pool. This is not part of the constructor to
 * allow the method to have return codes that can be interrogated by the
 * caller. If Exception are desired, appropriate wrapper methods can be
 * created to provide both features and give the caller the flexibility to
 * use either without additional coding.
 * <p>/*from ww  w.  ja  v a 2s .  c  o m*/
 * Be sure to call DBAlert.close() to complete the request before returning
 * to the client or loosing the object focus in the caller to "new
 * DBAlert()".
 *
 * @param ds_
 *        The datasource for database connections.
 * @param user_
 *        The database user logon id.
 * @return 0 if successful, otherwise the error code.
 * @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
 */
public int open(DataSource ds_, String user_) {
    try {
        _user = user_;
        _conn = ds_.getConnection();
        _conn.setAutoCommit(false);
        _needCommit = false;
    } catch (SQLException ex) {
        _logger.error(ex.toString(), ex);
        return ex.getErrorCode();
    }
    return 0;
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * A utility function that will modify the "in" clause on a SQL select to
 * contain the correct number of argument replacements to match the value
 * array provided.// w w w  . j a va2 s.co  m
 *
 * @param select_
 *        The SQL select that must contain a single "?" replacement within
 *        an "in" clause as this is the placeholder for expansion to the
 *        appropriate number of "?" arguments to match the length of the
 *        values array. Of course if the array only has a single value the
 *        "in" can be an "=" (equals) operator.
 * @param values_
 *        The array of values to use as bind arguments in the select.
 * @param flag_
 *        The separator to use in the concatenated string.
 * @return The comma separated string containing the concatenated results
 *         from the select query.
 */
private String selectText(String select_, String values_[], int flag_) {
    // There must be a single "?" in the select to start the method.
    int pos = select_.indexOf('?');
    if (pos < 0)
        return "";

    // As one "?" is already in the select we only add more if the array
    // length is greater than 1.
    String tSelect = select_.substring(0, pos + 1);
    for (int ndx = 1; ndx < values_.length; ++ndx)
        tSelect = tSelect + ",?";
    tSelect = tSelect + select_.substring(pos + 1);

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        // Now bind each value in the array to the expanded "?" list.
        pstmt = _conn.prepareStatement(tSelect);
        for (int ndx = 0; ndx < values_.length; ++ndx) {
            pstmt.setString(ndx + 1, values_[ndx]);
        }
        rs = pstmt.executeQuery();

        // Concatenate the results into a single comma separated string.
        tSelect = "";
        String sep = (flag_ == 0) ? ", " : "\" OR \"";
        while (rs.next()) {
            tSelect = tSelect + sep + rs.getString(1).replaceAll("[\\r\\n]", " ");
        }

        // We always start the string with a comma so be sure to remove it
        // before returning.
        if (tSelect.length() > 0) {
            tSelect = tSelect.substring(sep.length());
            if (flag_ == 1)
                tSelect = "\"" + tSelect + "\"";
        } else
            tSelect = "\"(unknown)\"";
    } catch (SQLException ex) {
        tSelect = ex.toString();
        _errorCode = DBAlertUtil.getSQLErrorCode(ex);
        _errorMsg = _errorCode + ": " + select_ + "\n\n" + tSelect;
        _logger.error(_errorMsg);
    } finally {
        closeCursors(pstmt, rs);
    }
    return tSelect;
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Run a specific SELECT for the testDBdependancies() method.
 *
 * @param select_//  w  ww  .  j a  va 2  s.c  om
 *        The select statement.
 * @return >0 if successful with the number of rows returned, otherwise
 *         failed.
 */
private int testDB(String select_) {
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    int rows = 0;
    try {
        pstmt = _conn.prepareStatement(select_);
        rs = pstmt.executeQuery();
        for (rows = 0; rs.next(); ++rows)
            ;
    } catch (SQLException ex) {
        _errorCode = DBAlertUtil.getSQLErrorCode(ex);
        _errorMsg = select_ + "\n" + ex.toString();
        rows = -1;
    } finally {
        closeCursors(pstmt, rs);
    }
    return rows;
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Run a specific SELECT for the testDBdependancies() method.
 *
 * @param select_/*from   w  ww. jav a  2  s .  c o m*/
 *        The select statement.
 * @return the first row found
 */
private String testDB2(String select_) {
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    String result = null;
    try {
        pstmt = _conn.prepareStatement(select_);
        rs = pstmt.executeQuery();
        result = null;
        int rows;
        for (rows = 0; rs.next(); ++rows)
            result = rs.getString(1);
    } catch (SQLException ex) {
        _errorCode = DBAlertUtil.getSQLErrorCode(ex);
        _errorMsg = select_ + "\n" + ex.toString();
    } finally {
        closeCursors(pstmt, rs);
    }
    return result;
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

/**
 * Perform an update on the complete record. No attempt is made to isolate
 * the specific changes so many times values will not actually be changed.
 *
 * @param rec_//from ww w  .ja va2  s . c o m
 *        The record containing the updated information. All data elements
 *        must be populated and correct.
 * @return 0 if successful, otherwise the Oracle error code.
 */
public int updateAlert(AlertRec rec_) {
    // Ensure data is clean.
    rec_.setDependancies();

    // Update database.
    try {
        int xxx = updateProperties(rec_);
        if (xxx != 0)
            return xxx;
        xxx = updateReport(rec_);
        if (xxx != 0)
            return xxx;
        xxx = updateRecipients(rec_);
        if (xxx != 0)
            return xxx;
        return updateQuery(rec_);
    } catch (SQLException ex) {
        _errorCode = DBAlertUtil.getSQLErrorCode(ex);
        _errorMsg = _errorCode + ": " + ex.toString();
        _logger.error(_errorMsg);
        return _errorCode;
    }
}