Example usage for java.sql PreparedStatement getResultSet

List of usage examples for java.sql PreparedStatement getResultSet

Introduction

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

Prototype

ResultSet getResultSet() throws SQLException;

Source Link

Document

Retrieves the current result as a ResultSet object.

Usage

From source file:org.elissa.server.SimpleStorageServlet.java

public void showProcessList(HttpServletRequest req, HttpServletResponse res)
        throws SQLException, MalformedURLException {

    PreparedStatement stmt = database.prepareStatement("SELECT ID, Name FROM sites");

    PrintWriter out;//www .  j a va 2  s .co m
    try {
        out = res.getWriter();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    res.setContentType("text/html");

    out.println(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");

    out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
    out.println("<head>");

    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>");
    out.println("<title>Oryx - Process Overview</title>");
    out.println("</head>");

    out.println("<body>");
    out.println("<div style=\"text-align: center;\">");

    out.println("<p>");
    out.println("<form action='" + req.getRequestURL() + "' method='get'>");
    out.println("Create a new process:<br/>");
    out.println("<img src='./images/crystal/empty.png' style='float: clear;' width='128' height='128'/><br/>");
    out.println("<input type='text' name='resource' value='' />");

    // get available stencil sets.
    URL base = new URL(req.getRequestURL().toString());
    Map<String, URL> stencilsets = getAvailableStencilsets(base);

    out.println("<select name=\"stencilset\" size=\"1\">");

    for (String name : stencilsets.keySet()) {
        URL url = stencilsets.get(name);
        out.println("<option value=\"" + url.toString() + "\">");
        out.println(name);
        out.println("</option>");
    }
    out.println("</select>");
    out.println("<input type='submit' value='Add' />");

    out.println("</form>");
    out.println("</p>");

    if (stmt.execute()) {

        ResultSet rs = stmt.getResultSet();
        out.println("<div style='text-align:left; float: clear;'>Or review an existing one:<br/></div>");

        while (rs.next()) {

            out.println("<div style='padding: 16px; display: inline; float: left;'>");
            out.println("<div>");
            out.println("<a href='" + req.getRequestURL() + "?resource=" + rs.getString(2)
                    + "' style='text-decoration: none'>");
            out.println("<img src='./images/crystal/misc.png' border='0' width='128' height='128'/><br/>");
            out.println(rs.getString(2));
            out.println("</a>");
            out.println("</div>");
            out.println("</div>");
        }

    } else {
        out.println("There currently are no saved processes.<br/>");
    }

    out.println("</div>");
    out.println("</body>");
    out.println("</html>");
}

From source file:csiro.pidsvc.mappingstore.Manager.java

protected String exportLookupImpl(String ns) throws SQLException {
    PreparedStatement pst = null;
    ResultSet rs = null, rsMap = null;
    String ret = "";

    try {/*from  ww w.  ja  v a  2s  .c om*/
        if (ns == null) {
            // Export all lookup maps.
            pst = _connection
                    .prepareStatement("SELECT ns, type, behaviour_type, behaviour_value FROM lookup_ns;");
        } else {
            // Export a particular lookup map.
            pst = _connection.prepareStatement(
                    "SELECT ns, type, behaviour_type, behaviour_value FROM lookup_ns WHERE ns = ?;");
            pst.setString(1, ns);
        }

        if (pst.execute()) {
            rs = pst.getResultSet();
            boolean dataAvailable = rs.next();

            // Backups may be empty. Otherwise throw an exception.
            if (ns != null && !dataAvailable)
                throw new SQLException("Lookup map configuration cannot be exported. Data may be corrupted.");

            if (dataAvailable) {
                do {
                    String lookupNamespace = rs.getString("ns");
                    String lookupType = rs.getString("type");

                    ret += "<lookup xmlns=\"urn:csiro:xmlns:pidsvc:backup:1.0\">";
                    ret += "<ns>" + StringEscapeUtils.escapeXml(lookupNamespace) + "</ns>";

                    String behaviourValue = rs.getString("behaviour_value");
                    ret += "<default type=\"" + StringEscapeUtils.escapeXml(rs.getString("behaviour_type"))
                            + "\">"
                            + (behaviourValue == null ? "" : StringEscapeUtils.escapeXml(behaviourValue))
                            + "</default>";

                    pst = _connection.prepareStatement("SELECT key, value FROM lookup WHERE ns = ?;");
                    pst.setString(1, lookupNamespace);
                    if (!pst.execute())
                        throw new SQLException(
                                "Lookup map configuration cannot be exported. Data may be corrupted.");
                    rsMap = pst.getResultSet();
                    if (lookupType.equalsIgnoreCase("Static")) {
                        ret += "<Static>";
                        while (rsMap.next()) {
                            ret += "<pair>";
                            ret += "<key>" + StringEscapeUtils.escapeXml(rsMap.getString(1)) + "</key>";
                            ret += "<value>" + StringEscapeUtils.escapeXml(rsMap.getString(2)) + "</value>";
                            ret += "</pair>";
                        }
                        ret += "</Static>";
                    } else if (lookupType.equalsIgnoreCase("HttpResolver")) {
                        ret += "<HttpResolver>";
                        if (!rsMap.next())
                            throw new SQLException(
                                    "Lookup map configuration cannot be exported. Data is corrupted.");

                        final Pattern reType = Pattern.compile("^T:(.+)$",
                                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                        final Pattern reExtract = Pattern.compile("^E:(.+)$",
                                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                        final Pattern reNamespace = Pattern.compile("^NS:(.+?):(.+)$",
                                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                        Matcher m;
                        String namespaces = "";
                        String buf = rsMap.getString(2);

                        ret += "<endpoint>" + StringEscapeUtils.escapeXml(rsMap.getString(1)) + "</endpoint>";

                        // Type.
                        m = reType.matcher(buf);
                        m.find();
                        ret += "<type>" + m.group(1) + "</type>";

                        // Extractor.
                        m = reExtract.matcher(buf);
                        m.find();
                        ret += "<extractor>" + StringEscapeUtils.escapeXml(m.group(1)) + "</extractor>";

                        // Namespaces.
                        m = reNamespace.matcher(buf);
                        while (m.find())
                            namespaces += "<ns prefix=\"" + StringEscapeUtils.escapeXml(m.group(1)) + "\">"
                                    + StringEscapeUtils.escapeXml(m.group(2)) + "</ns>";
                        if (!namespaces.isEmpty())
                            ret += "<namespaces>" + namespaces + "</namespaces>";

                        ret += "</HttpResolver>";
                    }
                    ret += "</lookup>";
                } while (rs.next());
            }
        }
    } finally {
        if (rsMap != null)
            rsMap.close();
        if (rs != null)
            rs.close();
        if (pst != null)
            pst.close();
    }
    return ret;
}

From source file:csiro.pidsvc.mappingstore.Manager.java

private MappingMatchResults findMatchImpl(PreparedStatement pst, URI uri, HttpServletRequest request,
        boolean patternBased)
        throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException,
        IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
    ResultSet rs = null;/*from  w  w w  .j  a  va2s. co  m*/
    int mappingId = MappingMatchResults.NULL;
    int defaultActionId = MappingMatchResults.NULL;
    AbstractCondition retCondition = null;
    Object matchAuxiliaryData = null;
    Pattern re;
    Matcher m;

    MappingParentDescriptorList parents = null;
    boolean isOneToOne = false;

    try {
        if (pst.execute()) {
            rs = pst.getResultSet();
            while (rs.next()) {
                // Check pattern match for pattern based mappings.
                if (!(isOneToOne = rs.getString("type").equalsIgnoreCase("1:1"))) {
                    re = Pattern.compile(rs.getString("mapping_path"),
                            getCaseSensitivity().RegularExpressionFlags);
                    m = re.matcher(uri.getPathNoExtension());
                    if (!m.find())
                        continue;
                }

                // Get mapping hierarchy.
                parents = getParents(rs.getInt("mapping_id"), uri);

                // Break the loop once first matching pattern is found.
                break;
            }

            // If there're no matching pattern based mappings were found then resort to Catch-all.
            if (patternBased && parents == null) {
                MappingParentDescriptor catchAll = getCatchAllDescriptor();
                parents = new MappingParentDescriptorList(1);
                if (catchAll != null)
                    parents.add(catchAll);
            }

            // Iterate through the inheritance tree up to Catch-All mapping to find a matching condition.
            if (parents != null) {
                for (MappingParentDescriptor parent : parents) {
                    // Find matching condition.
                    retCondition = getCondition(parent.MappingId, uri, request, parent.Aux);
                    if (retCondition != null) {
                        mappingId = parent.MappingId;
                        matchAuxiliaryData = parent.Aux;
                        break;
                    }
                }

                // Iterate through the inheritance tree up to Catch-All mapping to find a default action.
                if (retCondition == null) {
                    MappingParentDescriptor defaultActionMapping = parents.getFirstDefaultActionMapping();
                    if (defaultActionMapping != null) {
                        mappingId = defaultActionMapping.MappingId;
                        defaultActionId = defaultActionMapping.DefaultActionId;
                        matchAuxiliaryData = defaultActionMapping.Aux;
                    } else if (isOneToOne) {
                        // Set a flag that one-to-one mapping has been found but neither matching conditions nor
                        // default actions defined.
                        matchAuxiliaryData = true;
                    }
                }
            }
        } //- pst.execute()
    } finally {
        if (rs != null)
            rs.close();
    }
    return new MappingMatchResults(mappingId, defaultActionId, retCondition, matchAuxiliaryData);
}

From source file:org.cloudgraph.rdb.service.JDBCSupport.java

protected List<List<PropertyPair>> fetch(PlasmaType type, StringBuilder sql, Set<Property> props,
        Object[] params, Connection con) {
    List<List<PropertyPair>> result = new ArrayList<List<PropertyPair>>();
    PreparedStatement statement = null;
    ResultSet rs = null;//from   w ww  . j a  v  a  2s.co  m
    try {
        if (log.isDebugEnabled()) {
            if (params == null || params.length == 0) {
                log.debug("fetch: " + sql.toString());
            } else {
                StringBuilder paramBuf = new StringBuilder();
                paramBuf.append(" [");
                for (int p = 0; p < params.length; p++) {
                    if (p > 0)
                        paramBuf.append(", ");
                    paramBuf.append(String.valueOf(params[p]));
                }
                paramBuf.append("]");
                log.debug("fetch: " + sql.toString() + " " + paramBuf.toString());
            }
        }
        statement = con.prepareStatement(sql.toString(), ResultSet.TYPE_FORWARD_ONLY, /*
                                                                                       * ResultSet
                                                                                       * .
                                                                                       * TYPE_SCROLL_INSENSITIVE
                                                                                       * ,
                                                                                       */
                ResultSet.CONCUR_READ_ONLY);

        for (int i = 0; i < params.length; i++)
            statement.setString(i + 1, // FIXME
                    String.valueOf(params[i]));

        statement.execute();
        rs = statement.getResultSet();
        ResultSetMetaData rsMeta = rs.getMetaData();
        int numcols = rsMeta.getColumnCount();

        int count = 0;
        while (rs.next()) {
            List<PropertyPair> row = new ArrayList<PropertyPair>(numcols);
            result.add(row);
            for (int i = 1; i <= numcols; i++) {
                String columnName = rsMeta.getColumnName(i);
                int columnType = rsMeta.getColumnType(i);
                PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName);
                PlasmaProperty valueProp = prop;
                while (!valueProp.getType().isDataType()) {
                    valueProp = getOppositePriKeyProperty(valueProp);
                }
                Object value = converter.fromJDBCDataType(rs, i, columnType, valueProp);
                if (value != null) {
                    PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value);
                    if (!valueProp.equals(prop))
                        pair.setValueProp(valueProp);
                    if (!props.contains(prop))
                        pair.setQueryProperty(false);
                    row.add(pair);
                }
            }
            count++;
        }
        if (log.isDebugEnabled())
            log.debug("returned " + count + " results");
    } catch (Throwable t) {
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java

/**
 * This method returns all the repository IDs of the application.
 *
 * @param versionIDs the list of all the version IDs of the application
 * @return The list of repository IDs that are associated with the given version IDs
 * @throws AppFactoryException if SQL operation fails
 *///  www .  java  2  s  .  co m
private List<Integer> getAllRepositoryIDsOfApplication(String applicationKey, List<Integer> versionIDs)
        throws AppFactoryException {
    List<Integer> allRepositoryIDs = new ArrayList<Integer>();

    // The versionIDs can be empty when there are issues in app creation.
    // Hence if the list of version id are empty, we simply return a empty list.
    if (versionIDs.isEmpty()) {
        handleDebugLog("The list of version IDs are empty for application : " + applicationKey);
        return allRepositoryIDs;
    }
    Connection databaseConnection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        databaseConnection = AppFactoryDBUtil.getConnection();

        // We can not use a batch operation for fetching values. Hence we create the SQL dynamically
        String sqlString = SQLConstants.GET_ALL_APPLICATION_REPOSITORY_ID_SQL.replace("?",
                preparePlaceHolders(versionIDs.size()));
        preparedStatement = databaseConnection.prepareStatement(sqlString);
        int index = 1;
        for (Integer versionID : versionIDs) {
            preparedStatement.setInt(index, versionID);
            index++;
        }
        preparedStatement.execute();
        resultSet = preparedStatement.getResultSet();
        while (resultSet.next()) {
            allRepositoryIDs.add(resultSet.getInt(SQLParameterConstants.COLUMN_NAME_ID));
        }
    } catch (SQLException e) {
        handleException(
                "Error occurred while getting the list of repository IDs of application : " + applicationKey,
                e);
    } finally {
        AppFactoryDBUtil.closeResultSet(resultSet);
        AppFactoryDBUtil.closePreparedStatement(preparedStatement);
        AppFactoryDBUtil.closeConnection(databaseConnection);
    }
    handleDebugLog(
            "The list of repository IDs of application : " + applicationKey + " are : " + allRepositoryIDs);
    return allRepositoryIDs;
}

From source file:csiro.pidsvc.mappingstore.ManagerJson.java

@SuppressWarnings("unchecked")
public JSONObject getMappings(int page, String mappingPath, String type, String creator, int includeDeprecated)
        throws SQLException {
    PreparedStatement pst = null;
    ResultSet rs = null;// w ww.  j  a  va  2  s.  c  om
    JSONObject ret = new JSONObject();
    final int pageSize = 10;
    final String sourceView = (includeDeprecated == 2 ? "vw_deprecated_mapping"
            : (includeDeprecated == 1 ? "vw_latest_mapping" : "vw_active_mapping"));

    try {
        String query = "mapping_path IS NOT NULL";
        if (mappingPath != null && !mappingPath.isEmpty())
            query += " AND (title ILIKE ? OR mapping_path ILIKE ?)";
        if (type != null && !type.isEmpty())
            query += " AND type = ?";
        if (creator != null && !creator.isEmpty())
            query += " AND creator = ?";

        query = "SELECT COUNT(*) FROM " + sourceView + (query.isEmpty() ? "" : " WHERE " + query) + ";\n"
                + "SELECT mapping_id, mapping_path, title, description, creator, type, to_char(date_start, 'DD/MM/YYYY HH24:MI') AS date_start, to_char(date_end, 'DD/MM/YYYY HH24:MI') AS date_end FROM "
                + sourceView + (query.isEmpty() ? "" : " WHERE " + query)
                + " ORDER BY COALESCE(title, mapping_path) LIMIT " + pageSize + " OFFSET "
                + ((page - 1) * pageSize) + ";";

        pst = _connection.prepareStatement(query);

        // Bind parameters twice to two almost identical queries.
        for (int i = 1, j = 0; j < 2; ++j) {
            if (!mappingPath.isEmpty()) {
                pst.setString(i++, "%" + mappingPath.replace("\\", "\\\\") + "%");
                pst.setString(i++, "%" + mappingPath.replace("\\", "\\\\") + "%");
            }
            if (!type.isEmpty())
                pst.setString(i++, type);
            if (!creator.isEmpty())
                pst.setString(i++, creator);
        }

        if (pst.execute()) {
            rs = pst.getResultSet();
            rs.next();
            ret.put("count", rs.getInt(1));
            ret.put("page", page);
            ret.put("pages", (int) Math.ceil(rs.getFloat(1) / pageSize));

            JSONArray jsonArr = new JSONArray();
            for (pst.getMoreResults(), rs = pst.getResultSet(); rs.next();) {
                //               String dateStart = sdf.format(sdfdb.parse(rs.getString("date_start")));
                //               String dateEnd = rs.getString("date_end");
                //               if (dateEnd != null)
                //                  dateEnd = sdf.format(sdfdb.parse(dateEnd));

                jsonArr.add(JSONObjectHelper.create("mapping_id", rs.getString("mapping_id"), "mapping_path",
                        rs.getString("mapping_path"), "title", rs.getString("title"), "description",
                        rs.getString("description"), "creator", rs.getString("creator"), "type",
                        rs.getString("type"), "date_start", rs.getString("date_start"), "date_end",
                        rs.getString("date_end"), "date", ""));
            }
            ret.put("results", jsonArr);
        }
    } finally {
        if (rs != null)
            rs.close();
        if (pst != null)
            pst.close();
    }
    return ret;
}

From source file:org.cloudgraph.rdb.service.GraphQuery.java

private int countResults(Connection con, Query query, PlasmaType type) {
    int result = 0;
    Object[] params = new Object[0];

    StringBuilder sqlQuery = new StringBuilder();
    AliasMap aliasMap = new AliasMap(type);

    // construct a filter adding to alias map
    RDBFilterAssembler filterAssembler = null;
    Where where = query.findWhereClause();
    if (where != null) {
        filterAssembler = new RDBFilterAssembler(where, type, aliasMap);
        params = filterAssembler.getParams();
        if (log.isDebugEnabled()) {
            log.debug("filter: " + filterAssembler.getFilter());
        }/*from   ww w  . ja  va2  s  . c  o m*/
    }

    sqlQuery.append("SELECT COUNT(*)");

    // construct a FROM clause from alias map
    sqlQuery.append(" FROM ");
    Iterator<PlasmaType> it = aliasMap.getTypes();
    int count = 0;
    while (it.hasNext()) {
        PlasmaType aliasType = it.next();
        String alias = aliasMap.getAlias(aliasType);
        if (count > 0)
            sqlQuery.append(", ");
        sqlQuery.append(this.statementUtil.getQualifiedPhysicalName(aliasType));
        sqlQuery.append(" ");
        sqlQuery.append(alias);
        count++;
    }

    if (filterAssembler != null) {
        sqlQuery.append(" ");
        sqlQuery.append(filterAssembler.getFilter());
    }

    if (query.getStartRange() != null && query.getEndRange() != null)
        log.warn("query range (start: " + query.getStartRange() + ", end: " + query.getEndRange()
                + ") ignored for count operation");

    PreparedStatement statement = null;
    ResultSet rs = null;

    try {

        if (log.isDebugEnabled()) {
            log.debug("queryString: " + sqlQuery.toString());
            log.debug("executing...");
        }

        statement = con.prepareStatement(sqlQuery.toString(), ResultSet.TYPE_FORWARD_ONLY, /*
                                                                                            * ResultSet
                                                                                            * .
                                                                                            * TYPE_SCROLL_INSENSITIVE
                                                                                            * ,
                                                                                            */
                ResultSet.CONCUR_READ_ONLY);

        // set params
        // note params are pre-converted
        // to string in filter assembly
        if (filterAssembler != null) {
            params = filterAssembler.getParams();
            if (params != null)
                for (int i = 0; i < params.length; i++)
                    statement.setObject(i + 1, params[i]);
        }

        if (log.isDebugEnabled()) {
            if (params == null || params.length == 0) {
                log.debug("executing: " + sqlQuery.toString());
            } else {
                StringBuilder paramBuf = new StringBuilder();
                paramBuf.append(" [");
                for (int p = 0; p < params.length; p++) {
                    if (p > 0)
                        paramBuf.append(", ");
                    paramBuf.append(String.valueOf(params[p]));
                }
                paramBuf.append("]");
                log.debug("executing: " + sqlQuery.toString() + " " + paramBuf.toString());
            }
        }

        statement.execute();
        rs = statement.getResultSet();
        rs.next();
        result = rs.getInt(1);
    } catch (Throwable t) {
        StringBuffer buf = this.generateErrorDetail(t, sqlQuery.toString(), filterAssembler);
        log.error(buf.toString());
        throw new DataAccessException(t);
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
    return result;
}

From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java

public Map find(String type, String query, Map parameters) throws WGQueryException {

    if (type == null || type.equals("native")) {
        type = "sql";
    }/* w  ww.  j  av  a2 s .  com*/

    List nativeOptions = new ArrayList();
    String nativeOptionsString = (String) parameters.get(WGDatabase.QUERYOPTION_NATIVEOPTIONS);
    if (nativeOptionsString != null) {
        nativeOptions.addAll(WGUtils.deserializeCollection(nativeOptionsString.toLowerCase(), ",", true));
    }

    ResultSet resultSet = null;
    String table = null;
    PreparedStatement stmt;
    Boolean resetAutocommit = null;
    Connection connection = null;
    try {

        // Create statement
        connection = getConnection();
        boolean isUpdate = nativeOptions.contains("update");
        if (isUpdate && !connection.getAutoCommit()) {
            resetAutocommit = connection.getAutoCommit();
            connection.setAutoCommit(true);
        }

        if (type.equals("sql")) {

            stmt = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,
                    (isUpdate ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY));

        } else if (type.startsWith("table:")) {

            table = type.substring(6).trim();
            if (!_tables.keySet().contains(table.toLowerCase())) {
                throw new WGQueryException(query, "Table '" + table + "' does not exist or has no primary key");
            }

            if (query != null && !query.trim().equals("")) {
                query = "SELECT * FROM " + table + " WHERE " + query;
            } else {
                query = "SELECT * FROM " + table;
            }
            stmt = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

        } else {
            throw new WGQueryException(query, "Unknown query type: " + type);
        }

        // Apply parameters
        if (parameters.containsKey(WGDatabase.QUERYOPTION_MAXRESULTS)) {
            stmt.setMaxRows(((Number) parameters.get(WGDatabase.QUERYOPTION_MAXRESULTS)).intValue());
        }

        applyQueryParameters(parameters, stmt, query);

        // Execute and extract data
        stmt.execute();
        resultSet = stmt.getResultSet();
        Map results;
        if (resultSet != null) {
            results = extractRowResults(resultSet, table);
        } else {
            results = new HashMap();
        }

        return results;

    } catch (SQLException e) {
        throw new WGQueryException(query, e.getMessage(), e);
    } finally {
        if (connection != null && resetAutocommit != null) {
            try {
                connection.setAutoCommit(resetAutocommit);
            } catch (SQLException e) {
                throw new WGQueryException(query, "Exception resetting autocommit", e);
            }
        }
        closeResultSet(resultSet);
    }
}

From source file:org.openbravo.erpCommon.ad_forms.ModuleManagement.java

/**
 * Checks if there are local changes in the application
 *//* ww  w .j  av  a 2s  . c  o m*/
private String verifyLocalChanges(VariablesSecureApp vars) {
    Connection connection = OBDal.getInstance().getConnection();
    List<String> tablesModified = new ArrayList<String>();
    PreparedStatement ps = null;
    String localChanges = null;
    try {
        ps = connection.prepareStatement("SELECT ad_db_modified('N') FROM DUAL");
        ps.execute();
        ResultSet rs = ps.getResultSet();
        rs.next();
        String answer = rs.getString(1);
        if (answer.equalsIgnoreCase("Y")) {
            localChanges = Utility.messageBD(this, "ErrorLocalChanges", vars.getLanguage());
            localChanges = localChanges.concat(
                    " <br><br> " + Utility.messageBD(this, "StructuralChangesInDB", vars.getLanguage()));
        }
    } catch (Exception e) {
        log4j.error("Couldn't verify local changes");
    } finally {
        try {
            ps.close();
        } catch (SQLException e) {
            // won't happen
        }
    }
    List<File> modelFiles = new ArrayList<File>();
    String sourcePath = OBPropertiesProvider.getInstance().getOpenbravoProperties().getProperty("source.path");
    File sources = new File(sourcePath);
    // Added file exists condition to check invalid source path
    if (!sources.exists()) {
        throw new OBException(Utility.messageBD(this, "WrongPathError", vars.getLanguage()));
    }
    // Added to check write access
    if (!sources.canWrite()) {
        throw new OBException(Utility.messageBD(this, "NoApplicableModules", vars.getLanguage()));
    }
    File model = new File(sources, "src-db/database/model/tables");
    if (model.exists()) {
        modelFiles.add(model);
    } else {
        throw new OBException(Utility.messageBD(this, "WrongPathError", vars.getLanguage()));
    }
    for (File moduleFile : (new File(sources, "modules").listFiles())) {
        File mmodel = new File(moduleFile, "src-db/database/model/tables");
        if (mmodel.exists()) {
            modelFiles.add(mmodel);
        }
    }
    Database db = DatabaseUtils.readDatabase(modelFiles.toArray(new File[1]));

    Properties obProp = OBPropertiesProvider.getInstance().getOpenbravoProperties();
    String driver = obProp.getProperty("bbdd.driver");
    String url = obProp.getProperty("bbdd.rdbms").equals("POSTGRE")
            ? obProp.getProperty("bbdd.url") + "/" + obProp.getProperty("bbdd.sid")
            : obProp.getProperty("bbdd.url");
    String user = obProp.getProperty("bbdd.user");
    String password = obProp.getProperty("bbdd.password");
    BasicDataSource datasource = DBSMOBUtil.getDataSource(driver, url, user, password);
    final Platform platform = PlatformFactory.createNewPlatformInstance(datasource);

    OBDataset ad = new OBDataset(platform, db, "AD");
    boolean datachange = ad.hasChanged(connection, log4j, tablesModified);
    if (datachange) {
        if (localChanges == null) {
            localChanges = Utility.messageBD(this, "ErrorLocalChanges", vars.getLanguage());
        }
        localChanges = localChanges.concat(
                " <br><br> " + Utility.messageBD(this, "ModifiedTablesInDB", vars.getLanguage()) + " : ");
        localChanges = localChanges.concat(" " + tablesModified.toString());
    }
    return localChanges;
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

/**
 * Execute given query via a PreparedStatement.
 * A list of args can be passed to the query.
 *
 * Example: runQuery("SELECT * FROM example WHERE test = ?", "test");
 *
 * @param query Query that should be executed
 * @param args Long, String, or Object arguments
 *//*from w  w w. jav  a  2s  . co m*/
protected void runQuery(String query, Connection conn, Object... args) {
    PreparedStatement stmt = null;
    try {
        stmt = conn.prepareStatement(query);

        for (int i = 0; i < args.length; ++i) {
            if (args[i] instanceof String) {
                stmt.setString(i + 1, (String) args[i]);
            } else if (args[i] instanceof Long) {
                stmt.setLong(i + 1, (Long) args[i]);
            } else {
                stmt.setObject(i + 1, args[i]);
            }
        }

        if (stmt.execute()) {
            ResultSet rset = stmt.getResultSet();
            int count = 0;
            while (rset.next()) {
                count++;
            }
            LOG.info("QUERY(" + query + ") produced unused resultset with " + count + " rows");
        } else {
            int updateCount = stmt.getUpdateCount();
            LOG.info("QUERY(" + query + ") Update count: " + updateCount);
        }
    } catch (SQLException ex) {
        throw new SqoopException(CommonRepositoryError.COMMON_0000, query, ex);
    } finally {
        closeStatements(stmt);
    }
}