Example usage for java.sql ResultSet getBytes

List of usage examples for java.sql ResultSet getBytes

Introduction

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

Prototype

byte[] getBytes(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a byte array in the Java programming language.

Usage

From source file:org.torproject.ernie.web.DescriptorServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    /* Measure how long it takes to process this request. */
    long started = System.currentTimeMillis();

    /* Get print writer and start writing response. */
    PrintWriter out = response.getWriter();
    writeHeader(out);/*from  w  w  w .j  a va 2 s. com*/

    /* Check desc-id parameter. */
    String descIdParameter = request.getParameter("desc-id");
    String descId = null;
    if (descIdParameter != null && descIdParameter.length() >= 8 && descIdParameter.length() <= 40) {
        Pattern descIdPattern = Pattern.compile("^[0-9a-f]{8,40}$");
        if (descIdPattern.matcher(descIdParameter.toLowerCase()).matches()) {
            descId = descIdParameter.toLowerCase();
        }
    }
    if (descId == null) {
        out.write("    <br/><p>Sorry, \"" + descIdParameter + "\" is not a "
                + "valid descriptor identifier. Please provide at least the "
                + "first 8 hex characters of a descriptor identifier.</p>\n");
        writeFooter(out);
        return;
    }

    /* If we were only given a partial descriptor identifier, look up all
     * descriptor identifiers starting with that part to see if it's
     * unique. */
    if (descId.length() < 40) {
        SortedSet<String> allDescIds = new TreeSet<String>();
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            String query = "SELECT DISTINCT descriptor FROM statusentry " + "WHERE descriptor LIKE '" + descId
                    + "%'";
            ResultSet rs = statement.executeQuery(query);
            while (rs.next()) {
                allDescIds.add(rs.getString(1));
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                    + "experienced an unknown database problem while looking up "
                    + "descriptors with identifier starting with " + descId
                    + ". If this problem persists, please "
                    + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
            writeFooter(out);
            return;
        }
        if (allDescIds.size() == 0) {
            out.write("<p>No descriptor found " + (descId.length() < 40 ? "starting " : "") + "with identifier "
                    + descId + ".</p>");
            writeFooter(out);
            return;
        } else if (allDescIds.size() > 1) {
            out.println("<p>The descriptor identifier part " + descIdParameter
                    + " is not unique. Please choose one of the following " + "descriptors:</p><ul>");
            for (String f : allDescIds) {
                out.println("<li><a href=\"descriptor.html?desc-id=" + f + "\">" + f + "</a></li>");
            }
            out.write("</ul><br/>");
            writeFooter(out);
            return;
        } else {
            descId = allDescIds.first();
        }
    }

    /* Look up descriptor in the database. */
    String descriptor = null, nickname = null, published = null, extrainfo = null;
    byte[] rawDescriptor = null, rawExtrainfo = null;
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT descriptor, nickname, published, extrainfo, "
                + "rawdesc FROM descriptor WHERE descriptor = '" + descId + "'";
        ResultSet rs = statement.executeQuery(query);
        if (rs.next()) {
            descriptor = rs.getString(1);
            nickname = rs.getString(2);
            published = rs.getTimestamp(3).toString().substring(0, 19);
            extrainfo = rs.getString(4);
            rawDescriptor = rs.getBytes(5);
        }
        query = "SELECT rawdesc FROM extrainfo WHERE extrainfo = '" + extrainfo + "'";
        rs = statement.executeQuery(query);
        if (rs.next()) {
            rawExtrainfo = rs.getBytes(1);
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        out.write("<br/><p><font color=\"red\"><b>Warning: </b></font>"
                + "Internal server error when looking up descriptor. If this " + "problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
        writeFooter(out);
        return;
    }

    /* If no descriptor was found, stop here. */
    if (descriptor == null) {
        out.write("<p>No descriptor found " + (descIdParameter.length() < 40 ? "starting " : "")
                + "with identifier " + descIdParameter + ".</p>");
        writeFooter(out);
        return;
    }

    /* Print out both server and extra-info descriptor. */
    out.write("<br/><p>The following server descriptor was published by " + "relay " + nickname + " at "
            + published + " UTC:</p>");
    BufferedReader br = new BufferedReader(new StringReader(new String(rawDescriptor, "US-ASCII")));
    String line = null;
    while ((line = br.readLine()) != null) {
        out.println("        <tt>" + line + "</tt><br/>");
    }
    br.close();
    if (rawExtrainfo != null) {
        out.println("<br/><p>Together with this server descriptor, the "
                + "relay published the following extra-info descriptor:</p>");
        br = new BufferedReader(new StringReader(new String(rawExtrainfo, "US-ASCII")));
        line = null;
        while ((line = br.readLine()) != null) {
            out.println("        <tt>" + line + "</tt><br/>");
        }
    }

    /* Print out in which consensuses this descriptor is referenced. */
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT validafter, rawdesc FROM statusentry " + "WHERE descriptor = '" + descriptor
                + "' ORDER BY validafter " + "DESC";
        ResultSet rs = statement.executeQuery(query);
        boolean printedDescription = false;
        while (rs.next()) {
            if (!printedDescription) {
                out.println("<br/><p>This server descriptor is referenced from "
                        + "the following network status consensuses:</p>");
                printedDescription = true;
            }
            String validAfter = rs.getTimestamp(1).toString().substring(0, 19);
            out.println("        <br/><tt>valid-after " + "<a href=\"consensus?valid-after="
                    + validAfter.replaceAll(":", "-").replaceAll(" ", "-") + "\" target=\"_blank\">"
                    + validAfter + "</a></tt><br/>");
            byte[] rawStatusEntry = rs.getBytes(2);
            br = new BufferedReader(new StringReader(new String(rawStatusEntry, "US-ASCII")));
            line = null;
            while ((line = br.readLine()) != null) {
                out.println("        <tt>" + line + "</tt><br/>");
            }
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                + "experienced an unknown database problem while looking up "
                + "the network status consensuses referencing descriptor " + descId
                + ". If this problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
    }

    /* Provide links to raw descriptors, too. */
    out.println("<br/><p>Note that the descriptor" + (rawExtrainfo != null ? "s have" : " has")
            + " been converted to ASCII and reformatted "
            + "for display purposes. You may also download the raw " + "<a href=\"serverdesc?desc-id="
            + descriptor + "\" target=\"_blank\">server " + "descriptor</a>"
            + (extrainfo != null
                    ? " and <a href=\"extrainfodesc?desc-id=" + extrainfo
                            + "\" target=\"_blank\">extra-info descriptor</a>"
                    : "")
            + " as " + (extrainfo != null ? "they were" : "it was")
            + " published to the directory authorities.</p>");

    /* Display total lookup time on the results page. */
    long searchTime = System.currentTimeMillis() - started;
    out.write("        <br/><p>Looking up this descriptor took us "
            + String.format("%d.%03d", searchTime / 1000, searchTime % 1000) + " seconds.</p>\n");

    /* Finish writing response. */
    writeFooter(out);
}

From source file:com.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * Returns the blob as an array of bytes.
 * //from w  w  w.  j  av a 2s.  c o  m
 * @param table
 * @param columnName
 * @param id
 * @return The byte array value of this blob attribute.
 */
@Override
public long getBlobSize(String table, String columnName, String id) {
    Connection conn = Database.getConnection();
    Statement statement = null;
    ResultSet resultSet = null;
    long size = 0;
    try {
        // get the blob
        statement = conn.createStatement();
        String query = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '"
                + id + "'";
        resultSet = statement.executeQuery(query);
        resultSet.next();

        byte[] bytes = resultSet.getBytes(columnName);

        if (bytes != null) {
            size = resultSet.getBytes(columnName).length;
        }
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            this.closeConnection(conn);
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
    return size;
}

From source file:com.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * Returns the value of a blob as a byte array. It is up to the client to
 * close the database connection.// www. j a  v  a 2  s  .c o m
 * 
 * @param table
 * @param columnName
 * @param id
 * @param conn
 * @return byte[] value of the blob.
 */
public byte[] getBlobAsBytes(String table, String columnName, String id, Connection conn) {
    Statement statement = null;
    ResultSet resultSet = null;
    byte[] returnBytes = null;
    try {
        // get the blob
        statement = conn.createStatement();
        String query = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '"
                + id + "'";
        resultSet = statement.executeQuery(query);

        if (resultSet.next()) {
            returnBytes = resultSet.getBytes(columnName);
        } else {
            returnBytes = new byte[0];
        }

    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
    return returnBytes;
}

From source file:com.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * Returns the value of a blob as a byte array. This method allows you to
 * specify a start position in the blob (where the first element starts at
 * position 1 to comply with the JDBC 3.0 API) and the total length
 * (inclusive) beyond the start position to return.
 * /*ww w . j ava 2  s.  com*/
 * @param table
 * @param columnName
 * @param id
 * @param pos
 * @param length
 * @return
 */
public byte[] getBlobAsBytes(String table, String columnName, String id, long pos, int length) {
    Connection conn = Database.getConnection();
    Statement statement = null;
    ResultSet resultSet = null;
    byte[] returnBytes = null;
    try {
        // get the blob
        statement = conn.createStatement();
        String query = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '"
                + id + "'";
        resultSet = statement.executeQuery(query);
        resultSet.next();

        byte[] resultBytes = resultSet.getBytes(columnName);
        byte[] temp = new byte[length];
        pos = pos - 1;
        for (int i = 0; i < length; i++) {
            temp[i] = resultBytes[(int) pos];
            pos++;
        }
        returnBytes = temp;
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            this.closeConnection(conn);
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
    return returnBytes;
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * {@inheritDoc}/*  w w w.j  ava2  s  .co  m*/
 */
public void checkConsistency(String[] uuids, boolean recursive, boolean fix) {
    log.info("{}: checking workspace consistency...", name);

    int count = 0;
    int total = 0;
    Collection modifications = new ArrayList();

    if (uuids == null) {
        // get all node bundles in the database with a single sql statement,
        // which is (probably) faster than loading each bundle and traversing the tree
        ResultSet rs = null;
        try {
            String sql = "select count(*) from " + schemaObjectPrefix + "BUNDLE";
            Statement stmt = connectionManager.executeStmt(sql, new Object[0]);
            try {
                rs = stmt.getResultSet();
                if (!rs.next()) {
                    log.error("Could not retrieve total number of bundles. empty result set.");
                    return;
                }
                total = rs.getInt(1);
            } finally {
                closeResultSet(rs);
            }
            if (getStorageModel() == SM_BINARY_KEYS) {
                sql = "select NODE_ID from " + schemaObjectPrefix + "BUNDLE";
            } else {
                sql = "select NODE_ID_HI, NODE_ID_LO from " + schemaObjectPrefix + "BUNDLE";
            }
            stmt = connectionManager.executeStmt(sql, new Object[0]);
            rs = stmt.getResultSet();

            // iterate over all node bundles in the db
            while (rs.next()) {
                NodeId id;
                if (getStorageModel() == SM_BINARY_KEYS) {
                    id = new NodeId(new UUID(rs.getBytes(1)));
                } else {
                    id = new NodeId(new UUID(rs.getLong(1), rs.getLong(2)));
                }

                // issuing 2nd statement to circumvent issue JCR-1474
                ResultSet bRs = null;
                byte[] data = null;
                try {
                    Statement bSmt = connectionManager.executeStmt(bundleSelectSQL, getKey(id.getUUID()));
                    bRs = bSmt.getResultSet();
                    if (!bRs.next()) {
                        throw new SQLException("bundle cannot be retrieved?");
                    }
                    Blob blob = bRs.getBlob(1);
                    data = getBytes(blob);
                } finally {
                    closeResultSet(bRs);
                }

                try {
                    // parse and check bundle
                    // checkBundle will log any problems itself
                    DataInputStream din = new DataInputStream(new ByteArrayInputStream(data));
                    if (binding.checkBundle(din)) {
                        // reset stream for readBundle()
                        din = new DataInputStream(new ByteArrayInputStream(data));
                        NodePropBundle bundle = binding.readBundle(din, id);
                        checkBundleConsistency(id, bundle, fix, modifications);
                    } else {
                        log.error("invalid bundle '" + id + "', see previous BundleBinding error log entry");
                    }
                } catch (Exception e) {
                    log.error("Error in bundle " + id + ": " + e);
                }
                count++;
                if (count % 1000 == 0) {
                    log.info(name + ": checked " + count + "/" + total + " bundles...");
                }
            }
        } catch (Exception e) {
            log.error("Error loading bundle", e);
        } finally {
            closeResultSet(rs);
            total = count;
        }
    } else {
        // check only given uuids, handle recursive flag

        // 1) convert uuid array to modifiable list
        // 2) for each uuid do
        //     a) load node bundle
        //     b) check bundle, store any bundle-to-be-modified in collection
        //     c) if recursive, add child uuids to list of uuids

        List uuidList = new ArrayList(uuids.length);
        // convert uuid string array to list of UUID objects
        for (int i = 0; i < uuids.length; i++) {
            try {
                uuidList.add(new UUID(uuids[i]));
            } catch (IllegalArgumentException e) {
                log.error("Invalid uuid for consistency check, skipping: '" + uuids[i] + "': " + e);
            }
        }

        // iterate over UUIDs (including ones that are newly added inside the loop!)
        for (int i = 0; i < uuidList.size(); i++) {
            final UUID uuid = (UUID) uuidList.get(i);
            try {
                // load the node from the database
                NodeId id = new NodeId(uuid);
                NodePropBundle bundle = loadBundle(id, true);

                if (bundle == null) {
                    log.error("No bundle found for uuid '" + uuid + "'");
                    continue;
                }

                checkBundleConsistency(id, bundle, fix, modifications);

                if (recursive) {
                    Iterator iter = bundle.getChildNodeEntries().iterator();
                    while (iter.hasNext()) {
                        NodePropBundle.ChildNodeEntry entry = (NodePropBundle.ChildNodeEntry) iter.next();
                        uuidList.add(entry.getId().getUUID());
                    }
                }

                count++;
                if (count % 1000 == 0) {
                    log.info(name + ": checked " + count + "/" + uuidList.size() + " bundles...");
                }
            } catch (ItemStateException e) {
                // problem already logged (loadBundle called with logDetailedErrors=true)
            }
        }

        total = uuidList.size();
    }

    // repair collected broken bundles
    if (fix && !modifications.isEmpty()) {
        log.info(name + ": Fixing " + modifications.size() + " inconsistent bundle(s)...");
        Iterator iterator = modifications.iterator();
        while (iterator.hasNext()) {
            NodePropBundle bundle = (NodePropBundle) iterator.next();
            try {
                log.info(name + ": Fixing bundle '" + bundle.getId() + "'");
                bundle.markOld(); // use UPDATE instead of INSERT
                storeBundle(bundle);
                evictBundle(bundle.getId());
            } catch (ItemStateException e) {
                log.error(name + ": Error storing fixed bundle: " + e);
            }
        }
    }

    log.info(name + ": checked " + count + "/" + total + " bundles.");
}

From source file:com.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * Sets the value of this blob as the specified bytes. This method works the
 * same as the Blob.setBytes(long pos, byte[], int offset, int length) as
 * specified in the JDBC 3.0 API. Because of this, the first element in the
 * bytes to write to is actually element 1 (as opposed to the standard array
 * treatment where the first element is at position 0).
 * //from   w  ww  .  j  a  v a 2  s. co m
 * @param table
 * @param columnName
 * @param id
 * @param pos
 * @param bytes
 * @param offset
 * @param length
 * @return
 */
public int setBlobAsBytes(String table, String columnName, String id, long pos, byte[] bytes, int offset,
        int length) {
    Connection conn = Database.getConnection();
    Statement statement = null;
    ResultSet resultSet = null;
    int written = 0;
    try {
        // get the blob
        statement = conn.createStatement();
        String select = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '"
                + id + "'";
        String update = "UPDATE " + table + " SET " + columnName + " = " + "? WHERE " + EntityDAOIF.ID_COLUMN
                + " = '" + id + "'";
        resultSet = statement.executeQuery(select);
        resultSet.next();
        byte[] resultBytes = resultSet.getBytes(columnName);

        // null check
        if (resultBytes == null) {
            // because this method is used to place byte in specific positions, it
            // wouldn't
            // make sense to insert the bytes into a null columnName as it defeats
            // the
            // purpose of
            // this method. Just return a write count of 0 and don't do anything
            // else.
            return written;
        } else {
            // modify the blob
            written = length;
            byte[] setBytes = null;

            pos = pos - 1; // subtract one to use positioning like a normal array

            // check to see if the bytes will run longer than the current length of
            // the blob length.
            if ((pos + length) > resultBytes.length) {
                byte[] temp = new byte[(int) (pos + length)];
                // get the old bytes, up until pos
                for (int i = 0; i < pos; i++) {
                    temp[i] = resultBytes[i];
                }

                // set the new bytes
                for (int i = 0; i < length; i++) {
                    temp[(int) pos] = bytes[offset];
                    offset++;
                    pos++;
                    written++;
                }
                setBytes = temp;
            } else {
                // set the new bytes
                for (int i = 0; i < length; i++) {
                    resultBytes[(int) pos] = bytes[offset];
                    offset++;
                    pos++;
                    written++;
                }
                setBytes = resultBytes;
            }

            // save the changes to the blob
            PreparedStatement prepared = conn.prepareStatement(update);
            prepared.setBytes(1, setBytes);
            prepared.executeUpdate();
        }
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            this.closeConnection(conn);
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
    return written;
}

From source file:org.apache.tajo.catalog.store.AbstractDBStore.java

private CatalogProtos.PartitionMethodProto resultToPartitionMethodProto(final String databaseName,
        final String tableName, final ResultSet res) throws SQLException {

    CatalogProtos.PartitionMethodProto.Builder partBuilder;
    try {/*w  w w.  jav a  2  s  . com*/
        partBuilder = CatalogProtos.PartitionMethodProto.newBuilder();
        partBuilder.setTableIdentifier(CatalogUtil.buildTableIdentifier(databaseName, tableName));
        partBuilder.setPartitionType(CatalogProtos.PartitionType.valueOf(res.getString("partition_type")));
        partBuilder.setExpression(res.getString("expression"));
        partBuilder.setExpressionSchema(SchemaProto.parseFrom(res.getBytes("expression_schema")));
    } catch (InvalidProtocolBufferException e) {
        throw new TajoInternalError(e);
    }
    return partBuilder.build();
}

From source file:com.chaosinmotion.securechat.server.messages.NotificationSocket.java

/**
 * Validate username/password and start message pump
 * @param username/*ww  w.j  ava 2 s .  co m*/
 * @param password
 * @return
 */
private int validate(String username, String password, String deviceid) {
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    int dev = 0;

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT Users.password, Devices.deviceid " + "FROM Users, Devices "
                + "WHERE Users.username = ? " + "  AND Devices.userid = Users.userid "
                + "  AND Devices.deviceuuid = ?");
        ps.setString(1, username);
        ps.setString(2, deviceid);
        rs = ps.executeQuery();

        if (rs.next()) {
            /*
             * If the result is found, hash the entry in the way it would
             * be hashed by the front end, and compare to see if the
             * hash codes match. (This requires that the hashed password
             * stored in the back-end has a consistent capitalization.
             * We arbitrarily pick lower-case for our SHA-256 hex string.
             */
            String spassword = rs.getString(1);
            dev = rs.getInt(2);

            /*
             * Encrypt password with token and salt
             */

            spassword = spassword + Constants.SALT + token;
            spassword = Hash.sha256(spassword);

            /*
             * Compare; if matches, then return the user info record
             * so we can store away. While the SHA256 process returns
             * consistent case, we compare ignoring case anyway, just
             * because. :-)
             */

            if (!spassword.equalsIgnoreCase(password)) {
                /*
                 * This fails to run.
                 */

                return 1;
            }
        } else {
            return 2;
        }

        /*
         * At this point we're logged in. Register for real time messages
         * and send all of the stored messages for this device
         */

        rs.close();
        rs = null;
        ps.close();
        ps = null;

        /*
         * Register for real-time messages. There is a small window in
         * which we may write messages out of order. We rely on the
         * client to sort the messages correctly.
         */

        deviceID = dev;
        MessageQueue.getInstance().registerNotification(dev, NotificationSocket.this);

        /*
         * Run query to get messages, and send them to the calling
         * device. 
         */

        ps = c.prepareStatement("SELECT Messages.messageid, " + "    Messages.senderid, "
                + "    Users.username, " + "    Messages.toflag, " + "    Messages.received, "
                + "    Messages.message " + "FROM Messages, Users " + "WHERE Messages.deviceid = ? "
                + "  AND Messages.senderid = Users.userid");
        ps.setInt(1, deviceID);

        rs = ps.executeQuery();
        while (rs.next()) {
            int messageID = rs.getInt(1);
            int senderID = rs.getInt(2);
            String senderName = rs.getString(3);
            boolean toflag = rs.getBoolean(4);
            Timestamp received = rs.getTimestamp(5);
            byte[] message = rs.getBytes(6);

            sendMessage(messageID, senderID, senderName, toflag, received, message);
        }
    } catch (Exception ignore) {
        return 3;
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
            if (c != null)
                c.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return 0;
}

From source file:org.torproject.ernie.web.RelayServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    /* Measure how long it takes to process this request. */
    long started = System.currentTimeMillis();

    /* Get print writer and start writing response. */
    PrintWriter out = response.getWriter();
    writeHeader(out);/*from w w  w.j  a  v a 2  s .co m*/

    /* Check fingerprint parameter. */
    String fingerprintParameter = request.getParameter("fingerprint");
    boolean validParameter = true;
    if (fingerprintParameter == null || fingerprintParameter.length() < 8
            || fingerprintParameter.length() > 40) {
        validParameter = false;
    } else {
        Pattern fingerprintPattern = Pattern.compile("^[0-9a-f]{8,40}$");
        if (!fingerprintPattern.matcher(fingerprintParameter.toLowerCase()).matches()) {
            validParameter = false;
        }
    }
    if (!validParameter) {
        out.write("    <br/><p>Sorry, \"" + fingerprintParameter
                + "\" is not a valid relay fingerprint. Please provide at "
                + "least the first 8 hex characters of a relay " + "fingerprint.</p>\n");
        writeFooter(out);
        return;
    }

    /* If we were only given a partial fingerprint, look up all
     * fingerprints starting with that part to see if it's unique in the
     * last 30 days. */
    String fingerprint = fingerprintParameter.toLowerCase();
    if (fingerprint.length() < 40) {
        SortedSet<String> allFingerprints = new TreeSet<String>();
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            String query = "SELECT DISTINCT fingerprint FROM statusentry " + "WHERE validafter >= '"
                    + this.dayFormat.format(started - 30L * 24L * 60L * 60L * 1000L)
                    + " 00:00:00' AND fingerprint LIKE '" + fingerprint + "%'";
            ResultSet rs = statement.executeQuery(query);
            while (rs.next()) {
                allFingerprints.add(rs.getString(1));
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                    + "experienced an unknown database problem while looking up "
                    + "the relay with fingerprint starting with " + fingerprintParameter
                    + ". If this problem persists, please "
                    + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
            writeFooter(out);
            return;
        }
        if (allFingerprints.size() == 0) {
            out.write("<p>No relay found with fingerprint starting with " + fingerprintParameter
                    + " in the last 30 days.</p>");
            writeFooter(out);
            return;
        } else if (allFingerprints.size() > 1) {
            out.println("<p>The fingerprint part " + fingerprintParameter
                    + " is not unique for relays running in the last 30 days. "
                    + "Please choose one of the following fingerprints:</p><ul>");
            for (String f : allFingerprints) {
                out.println("<li><a href=\"relay.html?fingerprint=" + f + "\">" + f + "</a></li>");
            }
            out.write("</ul><br/>");
            writeFooter(out);
            return;
        } else {
            fingerprint = allFingerprints.first();
        }
    }

    /* Print out in which consensuses this relay was last contained. */
    boolean foundRelay = false;
    String lastDescriptor = null;
    try {
        Connection conn = this.ds.getConnection();
        Statement statement = conn.createStatement();
        String query = "SELECT validafter, rawdesc FROM statusentry WHERE " + "validafter >= '"
                + this.dayFormat.format(started - 30L * 24L * 60L * 60L * 1000L)
                + " 00:00:00' AND fingerprint = '" + fingerprint + "' ORDER BY validafter DESC LIMIT 3";
        ResultSet rs = statement.executeQuery(query);
        boolean printedDescription = false;
        while (rs.next()) {
            foundRelay = true;
            if (!printedDescription) {
                out.println("<p>The relay with fingerprint "
                        + (fingerprintParameter.length() < 40 ? "starting " : "") + "with "
                        + fingerprintParameter + " was last " + "referenced in the following relay lists:</p>");
                printedDescription = true;
            }
            String validAfter = rs.getTimestamp(1).toString().substring(0, 19);
            out.println("        <br/><tt>valid-after " + "<a href=\"consensus?valid-after="
                    + validAfter.replaceAll(":", "-").replaceAll(" ", "-") + "\" target=\"_blank\">"
                    + validAfter + "</a></tt><br/>");
            byte[] rawStatusEntry = rs.getBytes(2);
            try {
                String statusEntryLines = new String(rawStatusEntry, "US-ASCII");
                String[] lines = statusEntryLines.split("\n");
                for (String line : lines) {
                    if (line.startsWith("r ")) {
                        String[] parts = line.split(" ");
                        String descriptor = String.format("%040x",
                                new BigInteger(1, Base64.decodeBase64(parts[3] + "==")));
                        if (lastDescriptor == null) {
                            lastDescriptor = descriptor;
                        }
                        out.println("    <tt>r " + parts[1] + " " + parts[2] + " "
                                + "<a href=\"descriptor.html?desc-id=" + descriptor + "\" target=\"_blank\">"
                                + parts[3] + "</a> " + parts[4] + " " + parts[5] + " " + parts[6] + " "
                                + parts[7] + " " + parts[8] + "</tt><br/>");
                    } else {
                        out.println("    <tt>" + line + "</tt><br/>");
                    }
                }
            } catch (UnsupportedEncodingException e) {
                /* This shouldn't happen, because we know that ASCII is
                 * supported. */
            }
        }
        rs.close();
        statement.close();
        conn.close();
    } catch (SQLException e) {
        out.println("<p><font color=\"red\"><b>Warning: </b></font>We "
                + "experienced an unknown database problem while looking up " + "the relay with fingerprint "
                + (fingerprintParameter.length() < 40 ? "starting with " : "") + fingerprintParameter
                + ". If this problem persists, please "
                + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
        writeFooter(out);
        return;
    }

    /* If we didn't find this relay, stop here. */
    if (!foundRelay) {
        out.write("<p>No relay found with fingerprint "
                + (fingerprintParameter.length() < 40 ? "starting with " : "") + fingerprintParameter
                + " in the last 30 days.</p>");
        writeFooter(out);
        return;
    }

    /* Look up last server and extra-info descriptor in the database. */
    String query = null, descriptor = null, nickname = null, published = null, extrainfo = null;
    byte[] rawDescriptor = null, rawExtrainfo = null;
    if (lastDescriptor != null) {
        try {
            Connection conn = this.ds.getConnection();
            Statement statement = conn.createStatement();
            query = "SELECT descriptor, nickname, published, extrainfo, "
                    + "rawdesc FROM descriptor WHERE descriptor = '" + lastDescriptor + "'";
            ResultSet rs = statement.executeQuery(query);
            if (rs.next()) {
                descriptor = rs.getString(1);
                nickname = rs.getString(2);
                published = rs.getTimestamp(3).toString().substring(0, 19);
                extrainfo = rs.getString(4);
                rawDescriptor = rs.getBytes(5);
                query = "SELECT rawdesc FROM extrainfo WHERE extrainfo = '" + extrainfo + "'";
                rs = statement.executeQuery(query);
                if (rs.next()) {
                    rawExtrainfo = rs.getBytes(1);
                }
            }
            rs.close();
            statement.close();
            conn.close();
        } catch (SQLException e) {
            out.write("<br/><p><font color=\"red\"><b>Warning: </b></font>"
                    + "Internal server error when looking up descriptor. The " + "query was '" + query
                    + "'. If this problem persists, " + "please "
                    + "<a href=\"mailto:tor-assistants@freehaven.net\">let us " + "know</a>!</p>\n");
            writeFooter(out);
            return;
        }
    }

    /* If no descriptor was found, stop here. */
    if (descriptor == null) {
        out.write("<p>No descriptor found with identifier " + descriptor
                + " which was referenced in the last relay list.</p>");
        writeFooter(out);
        return;
    }

    /* Print out both server and extra-info descriptor. */
    out.write("<br/><p>The last referenced server descriptor published " + "by this relay is:</p>");
    BufferedReader br = new BufferedReader(new StringReader(new String(rawDescriptor, "US-ASCII")));
    String line = null;
    while ((line = br.readLine()) != null) {
        out.println("        <tt>" + line + "</tt><br/>");
    }
    br.close();
    if (rawExtrainfo != null) {
        out.println("<br/><p>Together with this server descriptor, the "
                + "relay published the following extra-info descriptor:</p>");
        br = new BufferedReader(new StringReader(new String(rawExtrainfo, "US-ASCII")));
        line = null;
        while ((line = br.readLine()) != null) {
            out.println("        <tt>" + line + "</tt><br/>");
        }
    }

    /* Provide links to raw descriptors, too. */
    out.println("<br/><p>Note that the descriptor" + (rawExtrainfo != null ? "s have" : " has")
            + " been converted to ASCII and reformatted "
            + "for display purposes. You may also download the raw " + "<a href=\"serverdesc?desc-id="
            + descriptor + "\" target=\"_blank\">server " + "descriptor</a>"
            + (extrainfo != null
                    ? " and <a href=\"extrainfodesc?desc-id=" + extrainfo
                            + "\" target=\"_blank\">extra-info descriptor</a>"
                    : "")
            + " as " + (extrainfo != null ? "they were" : "it was")
            + " published to the directory authorities.</p>");

    /* Display total lookup time on the results page. */
    long searchTime = System.currentTimeMillis() - started;
    out.write("        <br/><p>Looking up this relay took us "
            + String.format("%d.%03d", searchTime / 1000, searchTime % 1000) + " seconds.</p>\n");

    /* Finish writing response. */
    writeFooter(out);
}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

private void assertWrongValueFormatColumn(final ResultSet rs) throws Exception {
    assertFalse(rs.getBoolean(2));//from w  ww . j a  v a  2  s .com
    assertFalse(rs.getBoolean("ename"));

    try {
        rs.getShort(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getShort("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getInt("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getLong("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getFloat("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDouble("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBigDecimal("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBytes("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate(2, Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getDate("ename", Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime(2, Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTime("ename", Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp(2, Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getTimestamp("ename", Calendar.getInstance());
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getAsciiStream("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBinaryStream("ename");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream(2);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getCharacterStream("ename");
        fail();
    } catch (SQLException ignore) {
    }

}