Example usage for java.sql ResultSet getStatement

List of usage examples for java.sql ResultSet getStatement

Introduction

In this page you can find the example usage for java.sql ResultSet getStatement.

Prototype

Statement getStatement() throws SQLException;

Source Link

Document

Retrieves the Statement object that produced this ResultSet object.

Usage

From source file:org.kawanfw.sql.servlet.sql.ResultSetWriter.java

/**
 * return true if the column is a binary type
 * @param resultSet used to get back the Connection for PostgreSQL meta query
 * @param columnType//from  w  ww  .  java2s  .  c o m
 *            the sql column type
 * @param columnName
 *            the sql column name
 * @param columnTable
 *            the table name of the column
 * @return true if it's a binary type
 */
private boolean isBinaryColumn(ResultSet resultSet, int columnType, String columnName, String columnTable)
        throws SQLException, IOException {
    if (columnType == Types.BINARY || columnType == Types.VARBINARY || columnType == Types.LONGVARBINARY
            || columnType == Types.BLOB) {
        return true;
    } else {

        // Special treatment for PostgreSQL OID which Java long/BIGINT type
        if (isPostgreSQL && columnType == Types.BIGINT) {
            if (typeBigIntColumnNames == null) {
                Connection connection = resultSet.getStatement().getConnection();
                typeBigIntColumnNames = PostgreSqlUtil.getTypeBigIntColumnNames(connection);
            }

            if (typeBigIntColumnNames.contains(columnName.trim().toLowerCase())) {
                return true;
            }
        }

        return false;
    }
}

From source file:org.paxle.data.db.impl.FieldValueUserType.java

@Override
public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
    try {//ww  w  .  j  a v  a  2s. co  m
        return super.get(rs, name);
    } catch (SerializationException s) {
        this.logger.error(
                String.format("Error while loading deserializing field value. The SQL statement was:\r\n%s",
                        rs.getStatement()),
                s);
        return null;
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ResultSetTableModelFactory.java

/**
 * Generates a <code>TableModel</code> that gets its contents filled from a <code>ResultSet</code>. The column names
 * of the <code>ResultSet</code> will form the column names of the table model.
 * <p/>//from   w w w  . ja va2  s . c  om
 * Hint: To customize the names of the columns, use the SQL column aliasing (done with <code>SELECT nativecolumnname
 * AS "JavaColumnName" FROM ....</code>
 *
 * @param rs                the result set.
 * @param columnNameMapping defines, whether to use column names or column labels to compute the column index. If
 *                          true, then we map the Name.  If false, then we map the Label
 * @return a closeable table model.
 * @throws SQLException if there is a problem with the result set.
 */
public CloseableTableModel generateDefaultTableModel(final ResultSet rs, final boolean columnNameMapping)
        throws SQLException {
    try {
        final ResultSetMetaData rsmd = rs.getMetaData();
        final int colcount = rsmd.getColumnCount();
        final Class[] colTypes = TypeMapper.mapTypes(rsmd);
        //final DefaultTableMetaData metaData = new DefaultTableMetaData( colcount );

        // In past many database drivers were returning same value for column label and column name. So it is
        // inconsistent
        // what the database driver will return for column name vs column label.
        // We have a legacy configuration for this. If set, then if column label is null or empty then return column
        // name.
        // Otherwise return column label.
        // If non-legacy mode, then we return exactly what the JDBC driver returns (label for label, name for name)
        // without
        // any interpretation or interpolation.
        final Configuration globalConfig = ClassicEngineBoot.getInstance().getGlobalConfig();
        final boolean useLegacyColumnMapping = "legacy".equalsIgnoreCase( // NON-NLS
                globalConfig.getConfigProperty(
                        "org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ColumnMappingMode",
                        "legacy")); // NON-NLS

        final String[] header = new String[colcount];
        final AttributeMap[] columnMeta = new AttributeMap[colcount];

        for (int columnIndex = 0; columnIndex < colcount; columnIndex++) {
            String columnLabel = rsmd.getColumnLabel(columnIndex + 1);
            if (useLegacyColumnMapping) {
                if ((columnLabel == null) || (columnLabel.isEmpty())) {
                    // We are in legacy mode and column label is either null or empty, we then use column name instead.
                    columnLabel = rsmd.getColumnName(columnIndex + 1);
                }
                header[columnIndex] = columnLabel;
            } else {
                if (columnNameMapping) {
                    header[columnIndex] = rsmd.getColumnName(columnIndex + 1);
                } else {
                    header[columnIndex] = columnLabel;
                }
            }

            columnMeta[columnIndex] = ResultSetTableModelFactory.collectData(rsmd, columnIndex,
                    header[columnIndex]);
        }

        final Object[][] rowMap = produceData(rs, colcount);
        ImmutableTableMetaData metaData = new ImmutableTableMetaData(ImmutableDataAttributes.EMPTY,
                map(columnMeta));
        return new CloseableDefaultTableModel(rowMap, header, colTypes, metaData);
    } finally {
        Statement statement = null;
        try {
            statement = rs.getStatement();
        } catch (SQLException sqle) {
            // yeah, whatever
            logger.warn("Failed to close statement", sqle);
        }
        try {
            rs.close();
        } catch (SQLException sqle) {
            // yeah, whatever
            logger.warn("Failed to close resultset", sqle);
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException sqle) {
            // yeah, whatever
            logger.warn("Failed to close statement", sqle);
        }
    }
}

From source file:org.saiku.olap.util.ObjectUtil.java

@NotNull
public static List<SimpleCubeElement> convert2simple(@Nullable ResultSet rs) {
    try {/*  w  ww  .  j a  v  a2  s  . co m*/
        int width = 0;
        boolean first = true;
        List<SimpleCubeElement> elements = new ArrayList<>();
        if (rs != null) {
            while (rs.next()) {
                if (first) {
                    first = false;
                    width = rs.getMetaData().getColumnCount();
                }
                String[] row = new String[3];
                for (int i = 0; i < width; i++) {
                    row[i] = rs.getString(i + 1);
                }
                SimpleCubeElement s = new SimpleCubeElement(row[0], row[1], row[2]);
                elements.add(s);
            }
        }
        return elements;

    } catch (Exception e) {
        throw new SaikuServiceException("Error converting ResultSet into SimpleCubeElement", e);
    } finally {
        if (rs != null) {
            Statement statement = null;
            Connection con = null;
            try {
                statement = rs.getStatement();

            } catch (Exception e) {
                throw new SaikuServiceException(e);
            } finally {
                try {
                    rs.close();
                    if (statement != null) {
                        statement.close();
                    }
                } catch (Exception ee) {
                    LOG.error("Could not close statement", ee);
                }

                rs = null;
            }
        }
    }
}

From source file:org.saiku.web.rest.resources.QueryResource.java

@GET
@Produces({ "application/json" })
@Path("/{queryname}/drillthrough")
public QueryResult drillthrough(@PathParam("queryname") String queryName,
        @QueryParam("maxrows") @DefaultValue("100") Integer maxrows, @QueryParam("position") String position,
        @QueryParam("returns") String returns) {
    if (log.isDebugEnabled()) {
        log.debug("TRACK\t" + "\t/query/" + queryName + "/drillthrough\tGET");
    }//from ww  w .  j  a  v  a  2 s .  com
    QueryResult rsc;
    ResultSet rs = null;
    try {
        Long start = (new Date()).getTime();
        if (position == null) {
            rs = olapQueryService.drillthrough(queryName, maxrows, returns);
        } else {
            String[] positions = position.split(":");
            List<Integer> cellPosition = new ArrayList<>();

            for (String p : positions) {
                Integer pInt = Integer.parseInt(p);
                cellPosition.add(pInt);
            }

            rs = olapQueryService.drillthrough(queryName, cellPosition, maxrows, returns);
        }
        rsc = RestUtil.convert(rs);
        Long runtime = (new Date()).getTime() - start;
        rsc.setRuntime(runtime.intValue());

    } catch (Exception e) {
        log.error("Cannot execute query (" + queryName + ")", e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        rsc = new QueryResult(error);

    } finally {
        if (rs != null) {
            Statement statement = null;
            Connection con = null;
            try {
                statement = rs.getStatement();
                con = rs.getStatement().getConnection();
            } catch (Exception e) {
                throw new SaikuServiceException(e);
            } finally {
                try {
                    rs.close();
                    if (statement != null) {
                        statement.close();
                    }
                } catch (Exception ee) {
                }

                rs = null;
            }
        }
    }
    return rsc;

}

From source file:org.saiku.web.rest.resources.QueryResource.java

@GET
@Produces({ "text/csv" })
@Path("/{queryname}/drillthrough/export/csv")
public Response getDrillthroughExport(@PathParam("queryname") String queryName,
        @QueryParam("maxrows") @DefaultValue("100") Integer maxrows, @QueryParam("position") String position,
        @QueryParam("returns") String returns) {
    if (log.isDebugEnabled()) {
        log.debug("TRACK\t" + "\t/query/" + queryName + "/drillthrough/export/csv (maxrows:" + maxrows
                + " position" + position + ")\tGET");
    }/*from w w w .ja  v a2s . c o m*/
    ResultSet rs = null;

    try {
        if (position == null) {
            rs = olapQueryService.drillthrough(queryName, maxrows, returns);
        } else {
            String[] positions = position.split(":");
            List<Integer> cellPosition = new ArrayList<>();

            for (String p : positions) {
                Integer pInt = Integer.parseInt(p);
                cellPosition.add(pInt);
            }

            rs = olapQueryService.drillthrough(queryName, cellPosition, maxrows, returns);
        }
        byte[] doc = olapQueryService.exportResultSetCsv(rs);
        String name = SaikuProperties.webExportCsvName;
        return Response.ok(doc, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename = " + name + "-drillthrough.csv")
                .header("content-length", doc.length).build();

    } catch (Exception e) {
        log.error("Cannot export drillthrough query (" + queryName + ")", e);
        return Response.serverError().build();
    } finally {
        if (rs != null) {
            try {
                Statement statement = rs.getStatement();
                statement.close();
                rs.close();
            } catch (SQLException e) {
                throw new SaikuServiceException(e);
            } finally {
                rs = null;
            }
        }
    }

}

From source file:org.sakaiproject.metaobj.shared.IdType.java

public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    String value;//  ww w.j  av a  2s. c o  m
    try {
        value = rs.getString(names[0]);
    } catch (SQLException e) {
        logger.error("Stmt: " + rs.getStatement().toString(), e);
        throw e;
    }
    if (rs.wasNull()) {
        return null;
    }
    return new IdImpl(value, null);
}

From source file:org.sleuthkit.autopsy.recentactivity.Util.java

public static boolean imgpathexists(String path) {
    Case currentCase = Case.getCurrentCase(); // get the most updated case
    SleuthkitCase tempDb = currentCase.getSleuthkitCase();
    Boolean rt = false;/* ww  w .  j  a va  2 s. com*/
    int count = 0;
    try {
        List<FsContent> FFSqlitedb;
        ResultSet rs = tempDb.runQuery("select * from tsk_files where parent_path LIKE '%" + path + "%'");
        FFSqlitedb = tempDb.resultSetToFsContents(rs);
        count = FFSqlitedb.size();
        final Statement s = rs.getStatement();
        rs.close();
        if (s != null) {
            s.close();
        }
        if (count > 0) {
            rt = true;
        } else {
            rt = false;
        }
    } catch (SQLException ex) {
        //logger.log(Level.WARNING, "Error while trying to contact SQLite db.", ex);
    }
    return rt;
}

From source file:org.sleuthkit.autopsy.recentactivity.Util.java

public static long findID(String path) {
    String parent_path = path.replace('\\', '/'); // fix Chrome paths
    if (parent_path.length() > 2 && parent_path.charAt(1) == ':') {
        parent_path = parent_path.substring(2); // remove drive letter (e.g., 'C:')
    }/*from  ww w  . j  av a 2  s.co m*/
    int index = parent_path.lastIndexOf('/');
    String name = parent_path.substring(++index);
    parent_path = parent_path.substring(0, index);
    String query = "select * from tsk_files where parent_path like \"" + parent_path + "\" AND name like \""
            + name + "\"";
    Case currentCase = Case.getCurrentCase();
    SleuthkitCase tempDb = currentCase.getSleuthkitCase();
    try {
        ResultSet rs = tempDb.runQuery(query);
        List<FsContent> results = tempDb.resultSetToFsContents(rs);
        Statement s = rs.getStatement();
        rs.close();
        if (s != null) {
            s.close();
        }
        if (results.size() > 0) {
            return results.get(0).getId();
        }
    } catch (Exception ex) {
        //    logger.log(Level.WARNING, "Error retrieving content from DB", ex);
    }
    return -1;
}

From source file:org.sleuthkit.autopsy.thunderbirdparser.ThunderbirdMboxFileIngestService.java

@Override
public ProcessResult process(AbstractFile fsContent) {
    ThunderbirdEmailParser mbox = new ThunderbirdEmailParser();
    boolean isMbox = false;

    IngestServiceAbstractFile.ProcessResult hashDBResult = managerProxy
            .getAbstractFileServiceResult(hashDBServiceName);

    if (hashDBResult == IngestServiceAbstractFile.ProcessResult.COND_STOP) {
        return ProcessResult.OK; //file is known, stop processing it
    } else if (hashDBResult == IngestServiceAbstractFile.ProcessResult.ERROR) {
        return ProcessResult.ERROR; //file has read error, stop processing it
    }/*from   ww  w  .  j  a v  a  2 s . c o m*/

    try {
        byte[] t = new byte[64];
        if (fsContent.getSize() > 64) {
            int byteRead = fsContent.read(t, 0, 64);
            isMbox = mbox.isValidMimeTypeMbox(t);
        }
    } catch (TskException ex) {
        Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null, ex);
    }

    if (isMbox) {
        managerProxy.postMessage(IngestMessage.createMessage(++messageId, MessageType.INFO, this,
                "Processing " + fsContent.getName()));
        String mboxName = fsContent.getName();
        String msfName = mboxName + ".msf";
        Long mboxId = fsContent.getId();
        String mboxPath = "";
        Long msfId = 0L;
        Case currentCase = Case.getCurrentCase(); // get the most updated case
        SleuthkitCase tskCase = currentCase.getSleuthkitCase();
        try {
            ResultSet rs = tskCase
                    .runQuery("select parent_path from tsk_files where obj_id = '" + mboxId.toString() + "'");
            mboxPath = rs.getString("parent_path");
            Statement s = rs.getStatement();
            rs.close();
            if (s != null) {
                s.close();
            }
            rs.close();
            rs.getStatement().close();

            ResultSet resultset = tskCase.runQuery("select obj_id from tsk_files where parent_path = '"
                    + mboxPath + "' and name = '" + msfName + "'");
            msfId = resultset.getLong("obj_id");
            Statement st = resultset.getStatement();
            resultset.close();
            if (st != null) {
                st.close();
            }
            resultset.close();
            resultset.getStatement().close();

        } catch (SQLException ex) {
            logger.log(Level.WARNING, "Error while trying to get parent path for:" + this.getClass().getName(),
                    ex);
        }

        try {
            Content msfContent = tskCase.getContentById(msfId);
            ContentUtils.writeToFile(msfContent,
                    new File(currentCase.getTempDirectory() + File.separator + msfName));
        } catch (IOException ex) {
            Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null, ex);
        } catch (TskCoreException ex) {
            logger.log(Level.WARNING, "Unable to obtain msf file for mbox parsing:" + this.getClass().getName(),
                    ex);
        }
        int index = 0;
        String replace = "";
        boolean a = mboxPath.indexOf("/ImapMail/") > 0;
        boolean b = mboxPath.indexOf("/Mail/") > 0;
        if (b == true) {
            index = mboxPath.indexOf("/Mail/");
            replace = "/Mail";
        } else if (a == true) {
            index = mboxPath.indexOf("/ImapMail/");
            replace = "/ImapMail";
        } else {
            replace = "";

        }
        String folderPath = mboxPath.substring(index);
        folderPath = folderPath.replaceAll(replace, "");
        folderPath = folderPath + mboxName;
        folderPath = folderPath.replaceAll(".sbd", "");
        //            Reader reader = null;
        //            try {
        //                reader = new FileReader(currentCase.getTempDirectory() + File.separator + msfName);
        //            } catch (FileNotFoundException ex) {
        //                Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null, ex);
        //            }
        //            MorkDocument morkDocument = new MorkDocument(reader);
        //            List<Dict> dicts = morkDocument.getDicts();
        //            for(Dict dict : dicts){
        //            String path = dict.getValue("81").toString();
        //             String account = dict.getValue("8D").toString();
        //                    }
        String emailId = "";
        String content = "";
        String from = "";
        String to = "";
        String stringDate = "";
        Long date = 0L;
        String subject = "";
        String cc = "";
        String bcc = "";
        try {
            ReadContentInputStream contentStream = new ReadContentInputStream(fsContent);
            mbox.parse(contentStream);
            HashMap<String, Map<String, String>> emailMap = new HashMap<String, Map<String, String>>();
            emailMap = mbox.getAllEmails();
            for (Entry<String, Map<String, String>> entry : emailMap.entrySet()) {
                Map<String, String> propertyMap = new HashMap<String, String>();
                emailId = ((entry.getKey() != null) ? entry.getKey() : "Not Available");
                propertyMap = entry.getValue();
                content = ((propertyMap.get("content") != null) ? propertyMap.get("content") : "");
                from = ((propertyMap.get(Metadata.AUTHOR) != null) ? propertyMap.get(Metadata.AUTHOR) : "");
                to = ((propertyMap.get(Metadata.MESSAGE_TO) != null) ? propertyMap.get(Metadata.MESSAGE_TO)
                        : "");
                stringDate = ((propertyMap.get("date") != null) ? propertyMap.get("date") : "");
                if (!"".equals(stringDate)) {
                    date = mbox.getDateCreated(stringDate);
                }
                subject = ((propertyMap.get(Metadata.SUBJECT) != null) ? propertyMap.get(Metadata.SUBJECT)
                        : "");
                cc = ((propertyMap.get(Metadata.MESSAGE_CC) != null) ? propertyMap.get(Metadata.MESSAGE_CC)
                        : "");
                bcc = ((propertyMap.get(Metadata.MESSAGE_BCC) != null) ? propertyMap.get(Metadata.MESSAGE_BCC)
                        : "");

                Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
                bbattributes.add(
                        new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_EMAIL_TO.getTypeID(), classname, "", to));
                bbattributes.add(
                        new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_EMAIL_CC.getTypeID(), classname, "", cc));
                bbattributes.add(
                        new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_EMAIL_BCC.getTypeID(), classname, "", bcc));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_EMAIL_FROM.getTypeID(), classname,
                        "", from));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_EMAIL_CONTENT_PLAIN.getTypeID(),
                        classname, "", content.replaceAll("\\<[^>]*>", "")));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_EMAIL_CONTENT_HTML.getTypeID(),
                        classname, "", content));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_MSG_ID.getTypeID(), classname, "",
                        StringEscapeUtils.escapeHtml(emailId)));
                //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_MSG_REPLY_ID.getTypeID(), classname, "",));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_RCVD.getTypeID(),
                        classname, "", date));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_SENT.getTypeID(),
                        classname, "", date));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SUBJECT.getTypeID(), classname, "",
                        subject));
                bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PATH.getTypeID(), classname, "",
                        folderPath));
                BlackboardArtifact bbart;
                try {
                    bbart = fsContent.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_EMAIL_MSG);
                    bbart.addAttributes(bbattributes);
                } catch (TskCoreException ex) {
                    Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null,
                            ex);
                }
                IngestManagerProxy.fireServiceDataEvent(
                        new ServiceDataEvent(classname, BlackboardArtifact.ARTIFACT_TYPE.TSK_EMAIL_MSG));
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null, ex);
        } catch (TikaException ex) {
            Logger.getLogger(ThunderbirdMboxFileIngestService.class.getName()).log(Level.WARNING, null, ex);
        }
    }

    return ProcessResult.OK;
}