Example usage for java.sql Statement getResultSet

List of usage examples for java.sql Statement getResultSet

Introduction

In this page you can find the example usage for java.sql Statement getResultSet.

Prototype

ResultSet getResultSet() throws SQLException;

Source Link

Document

Retrieves the current result as a ResultSet object.

Usage

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static String createJdbcXmlResult(Statement statement)
        throws SQLException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDocumentResult = builder.newDocument();
    Element resultsElement = xmlDocumentResult.createElement("Results");
    xmlDocumentResult.appendChild(resultsElement);

    if (statement != null) {
        ResultSet resultSet = statement.getResultSet();
        if (resultSet != null) {
            resultSet.setFetchSize(statement.getFetchSize());
            xmlDocumentResult = addResultSetXmlPart(resultsElement, resultSet, xmlDocumentResult);
            while (statement.getMoreResults()) {
                xmlDocumentResult = addResultSetXmlPart(resultsElement, statement.getResultSet(),
                        xmlDocumentResult);
            }//from   w ww .j  a v a  2s  .c om
        } else {
            Element errorElement = xmlDocumentResult.createElement("UpdateCount");
            errorElement
                    .appendChild(xmlDocumentResult.createTextNode(String.valueOf(statement.getUpdateCount())));
            resultsElement.appendChild(errorElement);
        }
    }

    StringWriter out = new StringWriter();

    OutputFormat outputFormat = new OutputFormat(xmlDocumentResult);
    outputFormat.setOmitComments(true);
    outputFormat.setOmitDocumentType(true);
    outputFormat.setOmitXMLDeclaration(true);
    // outputFormat.setLineSeparator( "\n" );
    // add this line //
    // outputFormat.setPreserveSpace( true );
    outputFormat.setIndent(3);
    outputFormat.setIndenting(true);

    try {
        XMLSerializer serializer = new XMLSerializer(new PrintWriter(out), outputFormat);
        serializer.asDOMSerializer();
        serializer.serialize(xmlDocumentResult);
    } catch (IOException e) {
        throw new SoapBuilderException(e);
    }

    return out.toString();
}

From source file:capture.MySQLDatabase.java

public boolean getSystemStatus() {
    Connection con = this.getConnection();
    Statement stmt;
    ResultSet rs;//from   www  . j  a  v a  2  s .  c om
    boolean result = true;
    try {
        stmt = con.createStatement();

        //find the oldest operation which still has unvisited urls.
        stmt.executeQuery("SELECT status FROM honeypot WHERE ipaddress=\'"
                + ConfigManager.getInstance().getConfigOption("server-listen-address") + "\'");
        rs = stmt.getResultSet();
        if (rs.next()) {
            if (rs.getString(1).equals("F")) {
                result = false;
            } else {
                result = true;
            }
        }
        stmt.close();
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.agile.CsvTransformGeneratorIT.java

private long getRowCount(String tableName) throws Exception {
    DatabaseMeta databaseMeta = getDatabaseMeta();
    assertNotNull(databaseMeta);/* w  ww.ja  v  a 2  s  .com*/
    Database database = new Database(databaseMeta);
    assertNotNull(database);
    database.connect();

    Connection connection = null;
    Statement stmt = null;
    ResultSet sqlResult = null;
    try {
        connection = database.getConnection();
        assertNotNull(connection);
        stmt = database.getConnection().createStatement();
        boolean ok = stmt.execute("select count(*) from " + tableName);
        assertTrue(ok);
        sqlResult = stmt.getResultSet();
        assertNotNull(sqlResult);
        ok = sqlResult.next();
        assertTrue(ok);
        return sqlResult.getLong(1);
    } finally {
        if (sqlResult != null) {
            sqlResult.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.ibatis.executor.resultset.FastResultSetHandler.java

public List<Object> handleResultSets(Statement stmt) throws SQLException {
    final List<Object> multipleResults = new ArrayList<Object>();
    final List<ResultMap> resultMaps = mappedStatement.getResultMaps();
    int resultMapCount = resultMaps.size();
    int resultSetCount = 0;
    ResultSet rs = stmt.getResultSet();

    while (rs == null) {
        // move forward to get the first resultset in case the driver
        // doesn't return the resultset as the first result (HSQLDB 2.1)
        if (stmt.getMoreResults()) {
            rs = stmt.getResultSet();/*from  w ww. j  a v  a 2  s.c om*/
        } else {
            if (stmt.getUpdateCount() == -1) {
                // no more results. Must be no resultset
                break;
            }
        }
    }

    validateResultMapsCount(rs, resultMapCount);
    while (rs != null && resultMapCount > resultSetCount) {
        final ResultMap resultMap = resultMaps.get(resultSetCount);
        ResultColumnCache resultColumnCache = new ResultColumnCache(rs.getMetaData(), configuration);
        handleResultSet(rs, resultMap, multipleResults, resultColumnCache);
        rs = getNextResultSet(stmt);
        cleanUpAfterHandlingResultSet();
        resultSetCount++;
    }
    return collapseSingleResultList(multipleResults);
}

From source file:mom.trd.opentheso.bdd.helper.LanguageHelper.java

/**
 * Permet de retourner un ArrayList d'objets Language_iso639
 * c'est la liste des langues utilises par un thsaurus / ou null si rien
 * /*from   ww w  .  jav  a  2s .c o m*/
 * @param ds le pool de connexion
 * @param idThesaurus
 * @return Objet Class Thesaurus
 */
public ArrayList<Languages_iso639> getLanguagesOfThesaurus(HikariDataSource ds, String idThesaurus) {

    Connection conn;
    Statement stmt;
    ResultSet resultSet;
    ArrayList<Languages_iso639> language = null;
    try {
        // Get connection from pool
        conn = ds.getConnection();
        try {
            stmt = conn.createStatement();
            try {
                String query1 = "select distinct languages_iso639.iso639_1,"
                        + " languages_iso639.iso639_2, languages_iso639.english_name,"
                        + " languages_iso639.french_name"
                        + " from languages_iso639, thesaurus_label where thesaurus_label.lang = languages_iso639.iso639_1 "
                        + " and thesaurus_label.id_thesaurus ='" + idThesaurus + "';";

                stmt.executeQuery(query1);
                resultSet = stmt.getResultSet();
                if (resultSet != null) {
                    language = new ArrayList<>();
                    while (resultSet.next()) {
                        Languages_iso639 languageTmp = new Languages_iso639();
                        languageTmp.setId_iso639_1(resultSet.getString("iso639_1").trim());
                        languageTmp.setId_iso639_2(resultSet.getString("iso639_2").trim());
                        languageTmp.setFrench_name(resultSet.getString("french_name"));
                        languageTmp.setEnglish_name(resultSet.getString("english_name"));
                        language.add(languageTmp);
                    }
                }

            } finally {
                stmt.close();
            }
        } finally {
            conn.close();
        }
    } catch (SQLException sqle) {
        // Log exception
        log.error("Error while getting languages of thsaurus : " + idThesaurus, sqle);
    }
    return language;
}

From source file:morphy.service.SocketConnectionService.java

protected void handlePasswordPromptText(SocketChannelUserSession userSession, String message) {
    String userPasswordEntered = message;
    String name = userSession.getUser().getUserName();
    boolean isGuest = !userSession.getUser().isRegistered();

    UserService instance = UserService.getInstance();
    /*try { userSession.getChannel().configureBlocking(true); } catch(Exception e) { e.printStackTrace(System.err); }*/

    if (!isGuest) {

        try {/* ww w .  j a  v a  2  s .  c  o  m*/
            DatabaseConnection conn = DatabaseConnectionService.getInstance().getDBConnection();
            java.sql.Statement s = conn.getStatement();
            s.execute("SELECT `password` FROM `users` WHERE `username` = '" + name + "'");
            java.sql.ResultSet r = s.getResultSet();
            if (r.next()) {
                String actualpass = r.getString(1);

                if (!actualpass.equals(userPasswordEntered)) {
                    sendWithoutPrompt("**** Invalid password! ****\n\n"
                            + "If you cannot remember your password, please log in with \"g\" and ask for help\n"
                            + "in channel 4. Type \"tell 4 I've forgotten my password\". If that is not\n"
                            + "possible, please email: support@freechess.org\n\n"
                            + "\tIf you are not a registered player, enter guest or a unique ID.\n"
                            + "\t\t(If your return key does not work, use cntrl-J)\n\nlogin: ", userSession);
                    userSession.setCurrentState(SocketChannelUserSession.UserSessionState.LOGIN_NEED_USERNAME);
                    //userSession.disconnect();
                    return;
                }
            }
        } catch (java.sql.SQLException e) {
            e.printStackTrace(System.err);
        }
    }

    boolean isLoggedIn = instance.isLoggedIn(name);
    if (isLoggedIn) {
        /* this code in this logic block should be commented out to support multiple-login. */
        userSession.send(name + " is already logged in - kicking them out.");

        UserSession sess = instance.getUserSession(name);
        sess.send("**** " + name + " has arrived - you can't both be logged in. ****");
        sess.disconnect();
        isLoggedIn = !isLoggedIn;
    }

    userSession.getUser().setUserName(name);
    userSession.getUser().setPlayerType(PlayerType.Human);
    userSession.getUser().setUserLevel(isGuest ? UserLevel.Guest : UserLevel.Player);
    userSession.getUser().setRegistered(!isGuest);
    userSession.getUser().setUserVars(new morphy.user.UserVars(userSession.getUser()));
    if (isGuest) {
        userSession.getUser().getUserVars().getVariables().put("rated", "0");
    }
    userSession.setCurrentState(SocketChannelUserSession.UserSessionState.LOGGED_IN);
    if (!isLoggedIn) {
        instance.addLoggedInUser(userSession);
    } else {
        // This code is used for multiple-login.
        /*SocketChannelUserSession sess = (SocketChannelUserSession) instance.getUserSession(name);
        sess.addUserOnMultipleLogins(userSession);
        userSession.addParentOnMultipleLogins(sess);*/
    }
    userSession.getUser().setDBID(instance.getDBID(name));

    boolean isHeadAdmin = false;

    if (!isGuest) {
        DatabaseConnection conn = DatabaseConnectionService.getInstance().getDBConnection();

        String query = "SELECT pl.`name`,pe.`value` FROM personallist pl INNER JOIN personallist_entry pe ON (pe.personallist_id = pl.id) WHERE pl.user_id = '"
                + userSession.getUser().getDBID() + "'";
        java.sql.ResultSet rs = conn.executeQueryWithRS(query);
        try {
            while (rs.next()) {
                PersonalList pl = PersonalList.valueOf(rs.getString(1));
                String val = rs.getString(2);
                userSession.getUser().getLists().get(pl).add(val);
                if (pl == PersonalList.channel) {
                    int channelNum = Integer.parseInt(val);
                    Channel c = ChannelService.getInstance().getChannel(channelNum);
                    if (c != null) {
                        c.addListener(userSession);
                    }
                }
            }
        } catch (SQLException e) {
            Morphy.getInstance().onError(e);
        }

        Map<PersonalList, Integer> map = new HashMap<PersonalList, Integer>();
        query = "SELECT `name`,`id` FROM `personallist` WHERE `user_id` = '" + userSession.getUser().getDBID()
                + "'";
        rs = conn.executeQueryWithRS(query);
        try {
            while (rs.next()) {
                map.put(PersonalList.valueOf(rs.getString(1)), rs.getInt(2));
            }
        } catch (SQLException e) {
            Morphy.getInstance().onError(e);
        }
        userSession.getUser().setPersonalListDBIDs(map);

        conn.executeQuery("UPDATE `users` SET `lastlogin` = CURRENT_TIMESTAMP, `ipaddress` = '"
                + SocketUtils.getIpAddress(userSession.getChannel().socket()) + "' WHERE `username` = '" + name
                + "'");
        ResultSet r = conn
                .executeQueryWithRS("SELECT `adminLevel` FROM `users` WHERE `username` = '" + name + "'");
        try {
            if (r.next()) {
                String level = r.getString(1);
                UserLevel val = UserLevel.valueOf(level);
                userSession.getUser().setUserLevel(val);
                if (val == UserLevel.Admin || val == UserLevel.SuperAdmin || val == UserLevel.HeadAdmin) {
                    ServerListManagerService s = ServerListManagerService.getInstance();
                    s.getElements().get(s.getList("admin")).add(name);
                }

                if (val == UserLevel.HeadAdmin) {
                    isHeadAdmin = true;
                }
            }
        } catch (SQLException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unable to set user level from database for name \"" + name + "\"");
                LOG.error(e);
            }
        }
    }

    StringBuilder loginMessage = new StringBuilder(200);
    loginMessage.append(
            formatMessage(userSession, "**** Starting FICS session as " + instance.getTags(name) + " ****\n"));
    if (isHeadAdmin)
        loginMessage.append("\n  ** LOGGED IN AS HEAD ADMIN **\n");
    loginMessage.append(ScreenService.getInstance().getScreen(Screen.SuccessfulLogin));
    userSession.send(loginMessage.toString());

    //         query = "SELECT DISTINCT u.username FROM `morphyics`.`personallist` pl INNER JOIN users u ON (pl.user_id = u.id) WHERE pl.`name` = 'notify'";
    //         rs = dbcs.getDBConnection().executeQueryWithRS(query);
    //         try {
    //            UserService us = UserService.getInstance();
    //            while(rs.next()) {
    //               String username = rs.getString(1);
    //               UserSession sess = us.getUserSession(username);
    //               sess.send("Notification: " + name + " has arrived.");
    //            }
    //         } catch(SQLException e) { Morphy.getInstance().onError(e); }

    UserSession[] sessions = UserService.getInstance().fetchAllUsersWithVariable("pin", "1");
    for (UserSession s : sessions) {
        UserLevel adminLevel = s.getUser().getUserLevel();

        if (adminLevel == UserLevel.Admin || adminLevel == UserLevel.SuperAdmin
                || adminLevel == UserLevel.HeadAdmin) {
            s.send(String.format("[%s (%s: %s) has connected.]", userSession.getUser().getUserName(),
                    !isGuest ? "R" : "U", SocketUtils.getIpAddress(userSession.getChannel().socket())));
        } else {
            s.send(String.format("[%s has connected.]", userSession.getUser().getUserName()));
        }
    }

    DatabaseConnectionService dbcs = DatabaseConnectionService.getInstance();

    java.util.List<String> arrivalNotedBy = new java.util.ArrayList<String>(10);
    // this query gets all usernames with this player on their notify list.
    String query = "SELECT u.username FROM personallist pl INNER JOIN personallist_entry ple ON (pl.id = ple.personallist_id) INNER JOIN users u ON (u.id = pl.user_id) WHERE pl.`name` = 'notify' && ple.`value` LIKE '"
            + userSession.getUser().getUserName() + "';";
    ResultSet rs = dbcs.getDBConnection().executeQueryWithRS(query);
    try {
        UserService us = UserService.getInstance();
        while (rs.next()) {
            String username = rs.getString(1);
            UserSession sess = us.getUserSession(username);
            if (sess != null) {
                UserVars uv = sess.getUser().getUserVars();
                boolean highlight = uv.getVariables().get("highlight").equals("1");
                if (sess != null && sess.isConnected()) {
                    sess.send("Notification: " + (highlight ? ((char) 27) + "[7m" : "") + name
                            + (highlight ? ((char) 27) + "[0m" : "") + " has arrived.");
                    arrivalNotedBy.add(sess.getUser().getUserName());
                }
            }
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }
    if (arrivalNotedBy.size() > 0) {
        userSession.send("Your arrival was noted by: " + MorphyStringUtils
                .toDelimitedString(arrivalNotedBy.toArray(new String[arrivalNotedBy.size()]), " "));
    }

    query = "SELECT ple.`value` FROM personallist pl INNER JOIN personallist_entry ple ON (pl.id = ple.personallist_id) WHERE pl.user_id = "
            + userSession.getUser().getDBID() + " && pl.`name` = 'notify'"; // get this player's notify list
    rs = dbcs.getDBConnection().executeQueryWithRS(query);
    try {
        UserService us = UserService.getInstance();
        while (rs.next()) {
            String username = rs.getString(1);
            if (arrivalNotedBy.contains(username))
                continue;
            UserSession sess = us.getUserSession(username);
            if (sess == null)
                continue;
            UserVars uv = sess.getUser().getUserVars();
            boolean highlight = uv.getVariables().get("highlight").equals("1");
            if (sess != null && sess.isConnected())
                sess.send("Notification: " + (highlight ? ((char) 27) + "[7m" : "") + name
                        + (highlight ? ((char) 27) + "[0m" : "")
                        + " has arrived and isn't on your notify list.");
        }
    } catch (SQLException e) {
        Morphy.getInstance().onError(e);
    }
    // Notification: ChannelBot has arrived and isn't on your notify list.
}

From source file:wikipedia.sql.Links.java

/** Returns titles of destination (to) pages by id of source pages (pl_from), table pagelinks are used. 
 * SQL: SELECT pl_title FROM pagelinks WHERE pl_from IN (18991, 22233) AND pl_namespace = 0;
 *  @param namespace only pages with this namespace will be selected, value defined in PageTable.NS_MAIN, etc.
 *  Return empty array if pl_from={0};/*  w  ww . j  a  v a  2s .com*/
 *
 * SELECT MAX(LENGTH(pl_title)) FROM pagelinks WHERE pl_namespace = 0;
 * ruwiki: 255, real application: 92,52
 *
 * Test size of max_titles_len
 * Robot=11651
 * Russina=8811
 * Todo replace titles ArrayList<String>() by huge static array StringBuffer[][256];
 */
public static String[] getTitleToByIDFrom(SessionHolder session, int[] pl_from, PageNamespace namespace) {
    if (null == pl_from || (1 == pl_from.length && 0 == pl_from[0])) {
        return NULL_STRING_ARRAY;
    }

    Statement s = null;
    ResultSet rs = null;
    List<String> titles = new ArrayList<String>();

    sb.setLength(0);
    sb.append("SELECT pl_title FROM pagelinks WHERE pl_from IN (");

    // Prepare SQL IN(...) via pl_from[].page_id
    for (int i = 0; i < pl_from.length - 1; i++) {
        sb.append(pl_from[i]);
        sb.append(",");
    }
    sb.append(pl_from[pl_from.length - 1]); // skip last comma
    sb.append(") AND pl_namespace=");
    sb.append(namespace.toInt());

    int size, i = 0;
    //String str_sql = null;
    try {
        s = session.connect.conn.createStatement();
        //str_sql = "SELECT pl_title FROM pagelinks WHERE " + sb.toString() + " AND pl_namespace="+namespace;

        //System.out.print("GetTitleToByIDFrom sql="+sb.toString());
        s.executeQuery(sb.toString());
        //GetTitleToByIDFromQuery(rs, s, sb);
        //System.out.println(" OK.");

        rs = s.getResultSet();

        while (rs.next()) {
            Encodings e = session.connect.enc;
            String db_str = Encodings.bytesTo(rs.getBytes("pl_title"), e.GetDBEnc());
            String utf8_str = e.EncodeFromDB(db_str);
            if (!session.skipTitle(utf8_str)) {
                titles.add(utf8_str);
                //titles.add(connect.enc.EncodeFromDB(rs.getString("pl_title")));
            }

            /*if(max_pl_title_len < utf8_str.length()) {
            max_pl_title_len = utf8_str.length();
            System.out.println("GetTitleToByIDFrom max_pl_title_len="+max_pl_title_len);
            }*/
        }
        /*if(max_titles_len < titles.size()) {
        max_titles_len = titles.size();
        System.out.println("GetTitleToByIDFrom max_titles_len="+max_titles_len);
        }*/

    } catch (SQLException ex) {
        System.err.println(
                "SQLException (Links.java GetTitleToByIDFrom): sql='" + sb.toString() + "' " + ex.getMessage());
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) {
            }
            rs = null;
        }
        if (s != null) {
            try {
                s.close();
            } catch (SQLException sqlEx) {
            }
            s = null;
        }
    }
    return (String[]) titles.toArray(NULL_STRING_ARRAY);
}

From source file:de.tudarmstadt.ukp.csniper.ml.JdbcCustomReader.java

private void query() {
    try {/*from   w  ww .  java 2 s  .  c o  m*/
        Statement statement = sqlConnection.createStatement();

        // execute query which sets user variables
        Iterator<String> it = Arrays.asList(StringUtils.split(setterQuery, "\n")).iterator();
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            String line = it.next();
            if (line.trim().startsWith("#")) {
                continue;
            } else if (line.trim().endsWith(";")) {
                sb.append(line);
                statement.addBatch(sb.toString());
                sb = new StringBuilder();
            } else {
                sb.append(line);
            }
        }
        statement.executeBatch();

        statement.executeQuery(query);
        resultSet = statement.getResultSet();
        resultSet.last();
        resultSetSize = resultSet.getRow();
        resultSet.beforeFirst();
        completed = 0;

        // Store available column names
        columnNames = new HashSet<String>();
        ResultSetMetaData meta = resultSet.getMetaData();
        for (int i = 1; i < meta.getColumnCount() + 1; i++) {
            String columnName = meta.getColumnLabel(i);
            columnNames.add(columnName);
            if (!CAS_COLUMNS.contains(columnName)) {
                getLogger().warn("Unknown column [" + columnName + "].");
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException("There was an unrecoverable error executing the specified SQL statement.",
                e);
    }
}

From source file:org.gsoft.admin.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in/* w w w . ja  va 2  s.c  o  m*/
 * 
 * @param conn
 *            - the connection to use for the script
 * @param reader
 *            - the source of the script
 * @throws SQLException
 *             if any SQL errors occur
 * @throws IOException
 *             if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                println(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                println(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}

From source file:org.openmrs.module.formentry.databasechange.MigrateXsltsAndTemplatesChangeset.java

private void migrateResources(JdbcConnection connection, boolean isXslt) throws CustomChangeException {
    Statement selectStmt = null;
    PreparedStatement insertResourcesStmt = null;
    PreparedStatement insertClobsStmt = null;
    Boolean originalAutoCommit = null;
    ResultSet rs = null;//from   w  ww. j a  v a  2s.  c o  m
    String resourceName = (isXslt) ? FormEntryConstants.FORMENTRY_XSLT_FORM_RESOURCE_NAME
            : FormEntryConstants.FORMENTRY_TEMPLATE_FORM_RESOURCE_NAME;
    String columnName = (isXslt) ? "xslt" : "template";

    try {
        originalAutoCommit = connection.getAutoCommit();
        selectStmt = connection.createStatement();
        boolean hasResults = selectStmt.execute("SELECT form_id, " + columnName + " FROM form WHERE "
                + columnName + " IS NOT NULL AND " + columnName + " != ''");
        if (hasResults) {
            rs = selectStmt.getResultSet();
            insertClobsStmt = connection
                    .prepareStatement("INSERT INTO clob_datatype_storage (value, uuid) VALUES(?,?)");
            insertResourcesStmt = connection.prepareStatement(
                    "INSERT INTO form_resource (form_id, name, value_reference, datatype, preferred_handler, uuid) VALUES (?,'"
                            + resourceName + "',?,'" + LongFreeTextDatatype.class.getName() + "','"
                            + LongFreeTextFileUploadHandler.class.getName() + "',?)");

            String defaultXslt = IOUtils
                    .toString(getClass().getClassLoader().getResourceAsStream("default.xslt"));
            //intentionally didn't check for NULL so the exception halts the changeset
            defaultXslt = defaultXslt.trim();

            while (rs.next()) {
                String resourceValue = rs.getString(columnName);
                //if the form has an xslt and it differs from the default one
                if (StringUtils.isNotBlank(resourceValue)
                        && (!isXslt || !resourceValue.trim().equals(defaultXslt))) {
                    //set the clob storage values
                    String clobUuid = UUID.randomUUID().toString();
                    insertClobsStmt.setString(1, resourceValue.trim());
                    insertClobsStmt.setString(2, clobUuid);
                    insertClobsStmt.addBatch();

                    //set the resource column values
                    insertResourcesStmt.setInt(1, rs.getInt("form_id"));
                    insertResourcesStmt.setString(2, clobUuid);
                    insertResourcesStmt.setString(3, UUID.randomUUID().toString());
                    insertResourcesStmt.addBatch();
                }
            }

            boolean successfullyAddedClobs = false;
            int[] clobInsertCounts = insertClobsStmt.executeBatch();
            if (clobInsertCounts != null) {
                for (int i = 0; i < clobInsertCounts.length; i++) {
                    if (clobInsertCounts[i] > -1) {
                        successfullyAddedClobs = true;
                        log.debug("Successfully inserted resource clobs: insert count=" + clobInsertCounts[i]);
                    } else if (clobInsertCounts[i] == Statement.SUCCESS_NO_INFO) {
                        successfullyAddedClobs = true;
                        log.debug("Successfully inserted resource clobs; No Success info");
                    } else if (clobInsertCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to insert resource clobs");
                    }
                }
            }

            if (successfullyAddedClobs) {
                int[] resourceInsertCounts = insertResourcesStmt.executeBatch();
                if (resourceInsertCounts != null) {
                    boolean commit = false;
                    for (int i = 0; i < resourceInsertCounts.length; i++) {
                        if (resourceInsertCounts[i] > -1) {
                            commit = true;
                            log.debug("Successfully inserted " + columnName + " resources: insert count="
                                    + resourceInsertCounts[i]);
                        } else if (resourceInsertCounts[i] == Statement.SUCCESS_NO_INFO) {
                            commit = true;
                            log.debug("Successfully inserted " + columnName + " resources; No Success info");
                        } else if (resourceInsertCounts[i] == Statement.EXECUTE_FAILED) {
                            log.warn("Failed to insert " + columnName + " resources");
                        }
                    }

                    if (commit) {
                        log.debug("Committing " + columnName + " resource inserts...");
                        connection.commit();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.warn("Error generated while processsing generation of " + columnName + " form resources", e);

        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (Exception ex) {
            log.error("Failed to rollback", ex);
        }

        throw new CustomChangeException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }
        if (connection != null && originalAutoCommit != null) {
            try {
                connection.setAutoCommit(originalAutoCommit);
            } catch (DatabaseException e) {
                log.error("Failed to reset auto commit", e);
            }
        }

        closeStatementQuietly(selectStmt);
        closeStatementQuietly(insertClobsStmt);
        closeStatementQuietly(insertResourcesStmt);
    }
}