Example usage for java.sql ResultSet getBinaryStream

List of usage examples for java.sql ResultSet getBinaryStream

Introduction

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

Prototype

java.io.InputStream getBinaryStream(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a stream of uninterpreted bytes.

Usage

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

@SuppressWarnings("deprecation")
@Test/*ww w .  j  a  va2s  . c o  m*/
public void testResultSetWhenClosed() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);

    rs.close();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    try {
        rs.getString(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getString("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getBoolean("col1");
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getByte("col1");
        fail();
    } catch (SQLException ignore) {
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    try {
        rs.getDate(1, null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getDate("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTime(1, null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTime("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTimestamp(1, null);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.getTimestamp("col1", null);
        fail();
    } catch (SQLException ignore) {
    }

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

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

    try {
        rs.getUnicodeStream(1);
        fail();
    } catch (SQLException ignore) {
    }

    try {
        rs.getUnicodeStream("col1");
        fail();
    } catch (SQLException ignore) {
    }

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

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

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

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

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

    try {
        rs.setFetchDirection(1);
        fail();
    } catch (SQLException ignore) {
    }

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

    try {
        rs.setFetchSize(100);
        fail();
    } catch (SQLException ignore) {
    }

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

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

    statement.close();
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

private Element buildMenuItemXML(Document doc, Element menuItemsElement, ResultSet result, int tagItem,
        boolean complete, boolean includePageConfig, boolean includeHidden, boolean includeTypeSpecificXML,
        boolean tagItems, int levels) throws SQLException {

    int key = result.getInt("mei_lKey");

    // check if menuitem is hidden:
    int hiddenInt = result.getInt("mei_bHidden");
    boolean hidden = result.wasNull() || hiddenInt == 1;

    // propagate upwards in the XML and tag parents:
    if (key == tagItem) {
        tagParents(menuItemsElement);//from  w w w  .  j a  v a 2s. c o m
    }

    // simply return null if we don't want to include
    // hidden menuitems:
    if ((!includeHidden && hidden) || levels == 0) {
        // special case: if includeHidden is false, we must
        // check to see if the menuitem that is to be tagged
        // is a child of this menuitem
        if (tagItems) {
            if (tagItem != -1 && tagItem != key) {
                if (hasChild(key, tagItem, true)) {
                    tagParents(menuItemsElement);

                    if (hidden) {
                        Node n = menuItemsElement.getParentNode();
                        if (n.getNodeType() == Node.ELEMENT_NODE) {
                            ((Element) n).setAttribute("active", "true");
                        }
                    }
                }
            } else if (tagItem == key) {
                Node n = menuItemsElement.getParentNode();
                if (n.getNodeType() == Node.ELEMENT_NODE) {
                    ((Element) n).setAttribute("active", "true");
                }
            }
        }
        return null;
    }

    ////// + build xml for menu item
    Element menuItemElement = XMLTool.createElement(doc, menuItemsElement, "menuitem");
    menuItemElement.setAttribute("key", String.valueOf(key));

    // tag the menuitem?
    if (tagItem == key && !hidden) {
        menuItemElement.setAttribute("path", "true");
        menuItemElement.setAttribute("active", "true");
    }

    // attribute: owner
    menuItemElement.setAttribute("owner", result.getString("mei_usr_hOwner"));

    // attribute: modifier
    menuItemElement.setAttribute("modifier", result.getString("mei_usr_hModifier"));

    // attribute: order
    menuItemElement.setAttribute("order", result.getString("mei_lOrder"));

    // Add timestamp attribute
    menuItemElement.setAttribute("timestamp",
            CalendarUtil.formatTimestamp(result.getTimestamp("mei_dteTimestamp")));

    // attribute: language
    int lanKey = result.getInt("lan_lKey");
    String lanCode = result.getString("lan_sCode");
    String lanDesc = result.getString("lan_sDescription");
    if (lanDesc != null) {
        menuItemElement.setAttribute("languagekey", String.valueOf(lanKey));
        menuItemElement.setAttribute("languagecode", lanCode);
        menuItemElement.setAttribute("language", lanDesc);
    }

    // attribute menykey:
    int menuKey = result.getInt("mei_men_lkey");
    if (!result.wasNull()) {
        menuItemElement.setAttribute("menukey", String.valueOf(menuKey));
    }

    // attribute parent:
    int parentKey = result.getInt("mei_lParent");
    if (!result.wasNull()) {
        menuItemElement.setAttribute("parent", String.valueOf(parentKey));
    }

    // element: name
    XMLTool.createElement(doc, menuItemElement, "name", result.getString("mei_sName"));

    // display-name
    XMLTool.createElement(doc, menuItemElement, ELEMENT_NAME_DISPLAY_NAME,
            result.getString(COLUMN_NAME_DISPLAY_NAME));

    // short-name:
    String tmp = result.getString(COLUMN_NAME_ALTERNATIVE_NAME);
    if (!result.wasNull() && tmp.length() > 0) {
        XMLTool.createElement(doc, menuItemElement, ELEMENT_NAME_MENU_NAME, tmp);
    }

    menuItemElement.setAttribute("runAs", RunAsType.get(result.getInt("mei_lRunAs")).toString());

    // description:
    String desc = result.getString("mei_sDescription");
    if (!result.wasNull()) {
        XMLTool.createElement(doc, menuItemElement, "description", desc);
    } else {
        XMLTool.createElement(doc, menuItemElement, "description");
    }

    // keywords:
    String keywords = result.getString("mei_sKeywords");
    if (!result.wasNull()) {
        XMLTool.createElement(doc, menuItemElement, "keywords", keywords);
    } else {
        XMLTool.createElement(doc, menuItemElement, "keywords");
    }

    // visibility:
    if (!hidden) {
        menuItemElement.setAttribute("visible", "yes");
    } else {
        menuItemElement.setAttribute("visible", "no");
    }

    // contentkey
    int contentKey = getMenuItemContentKey(key);
    if (contentKey != -1) {
        menuItemElement.setAttribute("contentkey", String.valueOf(contentKey));
    }

    // element menuitemdata:
    InputStream is = result.getBinaryStream("mei_xmlData");
    Element documentElem;
    if (result.wasNull()) {
        XMLTool.createElement(doc, menuItemElement, "parameters");
        documentElem = XMLTool.createElement(doc, "document");
        if (complete) {
            XMLTool.createElement(doc, menuItemElement, "data");
        }
    } else {
        Document dataDoc = XMLTool.domparse(is);
        Element dataElem = (Element) doc.importNode(dataDoc.getDocumentElement(), true);
        Element parametersElem = XMLTool.getElement(dataElem, "parameters");
        dataElem.removeChild(parametersElem);
        menuItemElement.appendChild(parametersElem);
        if (complete) {
            documentElem = XMLTool.getElement(dataElem, "document");
            if (documentElem != null) {
                dataElem.removeChild(documentElem);
                menuItemElement.appendChild(documentElem);
            }
            menuItemElement.appendChild(dataElem);
        } else {
            documentElem = XMLTool.createElement(doc, "document");
        }
    }

    // attribute: menu item type
    MenuItemType menuItemType = MenuItemType.get(result.getInt("mei_mid_lKey"));
    menuItemElement.setAttribute("type", menuItemType.getName());

    if (includeTypeSpecificXML) {
        // build type-specific XML:
        switch (menuItemType) {
        case PAGE:
            buildPageTypeXML(result, doc, menuItemElement, complete && includePageConfig);
            break;

        case URL:
            buildURLTypeXML(result, doc, menuItemElement);
            break;

        case CONTENT:
            MenuItemKey sectionKey = getSectionHandler().getSectionKeyByMenuItem(new MenuItemKey(key));
            if (sectionKey != null) {
                buildSectionTypeXML(key, menuItemElement);
            }
            buildDocumentTypeXML(menuItemElement, documentElem);
            buildPageTypeXML(result, doc, menuItemElement, complete && includePageConfig);
            break;

        case LABEL:
            break;
        case SECTION:
            buildSectionTypeXML(key, menuItemElement);
            break;
        case SHORTCUT:
            buildShortcutTypeXML(key, menuItemElement);
            break;
        }
    }

    return menuItemElement;
}

From source file:com.flexive.core.storage.genericSQL.GenericBinarySQLStorage.java

/**
 * Transfer a binary from the transit to the 'real' binary table
 *
 * @param _con     open and valid connection
 * @param binary  the binary descriptor/*from  www.  j a va2 s  .c o  m*/
 * @param id      desired id
 * @param version desired version
 * @param quality desired quality
 * @return descriptor of final binary
 * @throws FxDbException on errors looking up the sequencer
 */
private BinaryDescriptor binaryTransit(Connection _con, BinaryDescriptor binary, long id, int version,
        int quality) throws FxDbException {
    PreparedStatement ps = null;
    BinaryDescriptor created;
    FileInputStream fis = null;
    boolean dbTransit;
    boolean dbStorage;
    final long dbThreshold;
    final long dbPreviewThreshold;
    final int divisionId = FxContext.get().getDivisionId();
    try {
        final DivisionConfigurationEngine divisionConfig = EJBLookup.getDivisionConfigurationEngine();
        dbTransit = divisionConfig.get(SystemParameters.BINARY_TRANSIT_DB);
        if (id >= 0) {
            dbThreshold = divisionConfig.get(SystemParameters.BINARY_DB_THRESHOLD);
            dbPreviewThreshold = divisionConfig.get(SystemParameters.BINARY_DB_PREVIEW_THRESHOLD);
        } else {
            //force storage of system binaries in the database
            dbThreshold = -1;
            dbPreviewThreshold = -1;
        }
        dbStorage = dbThreshold < 0 || binary.getSize() < dbThreshold;
    } catch (FxApplicationException e) {
        throw e.asRuntimeException();
    }
    Connection con = null;
    try {
        con = Database.getNonTXDataSource(divisionId).getConnection();
        con.setAutoCommit(false);
        double resolution = 0.0;
        int width = 0;
        int height = 0;
        boolean isImage = binary.getMimeType().startsWith("image/");
        if (isImage) {
            try {
                width = Integer
                        .parseInt(defaultString(FxXMLUtils.getElementData(binary.getMetadata(), "width"), "0"));
                height = Integer.parseInt(
                        defaultString(FxXMLUtils.getElementData(binary.getMetadata(), "height"), "0"));
                resolution = Double.parseDouble(
                        defaultString(FxXMLUtils.getElementData(binary.getMetadata(), "xResolution"), "0"));
            } catch (NumberFormatException e) {
                //ignore
                LOG.warn(e, e);
            }
        }
        created = new BinaryDescriptor(CacheAdmin.getStreamServers(), id, version, quality,
                System.currentTimeMillis(), binary.getName(), binary.getSize(), binary.getMetadata(),
                binary.getMimeType(), isImage, resolution, width, height, binary.getMd5sum());
        //we can copy the blob directly into the binary table if the database is used for transit and the final binary is
        //stored in the filesystem
        final boolean copyBlob = dbTransit && dbStorage;
        boolean storePrev1FS = false, storePrev2FS = false, storePrev3FS = false, storePrev4FS = false;
        long prev1Length = -1, prev2Length = -1, prev3Length = -1, prev4Length = -1;
        if (dbPreviewThreshold >= 0) {
            //we have to check if preview should be stored on the filesystem
            ps = con.prepareStatement(BINARY_TRANSIT_PREVIEW_SIZES);
            ps.setString(1, binary.getHandle());
            ResultSet rs = ps.executeQuery();
            if (!rs.next())
                throw new FxDbException("ex.content.binary.transitNotFound", binary.getHandle());
            rs.getLong(1); //check if previewref is null
            if (rs.wasNull()) {
                //if previews are not referenced, check thresholds
                storePrev1FS = (prev1Length = rs.getLong(2)) >= dbPreviewThreshold && !rs.wasNull();
                storePrev2FS = (prev2Length = rs.getLong(3)) >= dbPreviewThreshold && !rs.wasNull();
                storePrev3FS = (prev3Length = rs.getLong(4)) >= dbPreviewThreshold && !rs.wasNull();
                storePrev4FS = (prev4Length = rs.getLong(5)) >= dbPreviewThreshold && !rs.wasNull();
            }
        }
        if (ps != null)
            ps.close();
        String previewSelect = (storePrev1FS ? ",NULL" : ",PREV1") + (storePrev2FS ? ",NULL" : ",PREV2")
                + (storePrev3FS ? ",NULL" : ",PREV3") + (storePrev4FS ? ",NULL" : ",PREV4");
        //check if the binary is to be replaced
        ps = con.prepareStatement(
                "SELECT COUNT(*) FROM " + TBL_CONTENT_BINARY + " WHERE ID=? AND VER=? AND QUALITY=?");
        ps.setLong(1, created.getId());
        ps.setInt(2, created.getVersion()); //version
        ps.setInt(3, created.getQuality()); //quality
        ResultSet rsExist = ps.executeQuery();
        final boolean replaceBinary = rsExist != null && rsExist.next() && rsExist.getLong(1) > 0;
        ps.close();
        int paramIndex = 1;
        if (replaceBinary) {
            ps = con.prepareStatement(BINARY_TRANSIT_REPLACE
                    + (copyBlob ? BINARY_TRANSIT_REPLACE_FBLOB_COPY : BINARY_TRANSIT_REPLACE_FBLOB_PARAM)
                    + BINARY_TRANSIT_REPLACE_PARAMS);
            FxBinaryUtils.removeBinary(divisionId, created.getId());
        } else {
            ps = con.prepareStatement((copyBlob ? BINARY_TRANSIT : BINARY_TRANSIT_FILESYSTEM) + previewSelect
                    + BINARY_TRANSIT_PREVIEW_WHERE);
            ps.setLong(paramIndex++, created.getId());
            ps.setInt(paramIndex++, created.getVersion()); //version
            ps.setInt(paramIndex++, created.getQuality()); //quality
        }
        File binaryTransit = null;
        boolean removeTransitFile = false;
        if (dbTransit) {
            //transit is handled in the database
            try {
                if (!dbStorage) {
                    //binaries are stored on the filesystem
                    binaryTransit = getBinaryTransitFileInfo(binary).getBinaryTransitFile();
                    removeTransitFile = true; //have to clean up afterwards since its a temporary file we get
                }
            } catch (FxApplicationException e) {
                if (e instanceof FxDbException)
                    throw (FxDbException) e;
                throw new FxDbException(e);
            }
        } else {
            //transit file resides on the local file system
            binaryTransit = FxBinaryUtils.getTransitFile(divisionId, binary.getHandle());
            removeTransitFile = true; // temporary transit file can be removed as well
            if (binaryTransit == null)
                throw new FxDbException("ex.content.binary.transitNotFound", binary.getHandle());
        }

        boolean needExplicitBlobInsert = false;
        if (copyBlob && replaceBinary)
            ps.setString(paramIndex++, binary.getHandle());
        if (!copyBlob) {
            //we do not perform a simple blob copy operation in the database
            if (dbStorage) {
                //binary is stored in the database -> copy it from the transit file (might be a temp. file)
                if (blobInsertSelectAllowed()) {
                    fis = new FileInputStream(binaryTransit);
                    ps.setBinaryStream(paramIndex++, fis, (int) binaryTransit.length());
                } else {
                    ps.setNull(paramIndex++, Types.BINARY);
                    needExplicitBlobInsert = true;
                }
            } else {
                //binary is stored on the filesystem -> move transit file to binary storage file
                try {
                    if (!FxFileUtils.moveFile(binaryTransit,
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.ORIGINAL.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed", created.getId());
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError", created.getId(),
                            e.getMessage());
                }
                ps.setNull(paramIndex++, Types.BINARY);
            }
        }

        //            int cnt = paramIndex; //copyBlob ? 4 : 5;
        ps.setString(paramIndex++, created.getName());
        ps.setLong(paramIndex++, created.getSize());
        setBigString(ps, paramIndex++, created.getMetadata());
        ps.setString(paramIndex++, created.getMimeType());
        if (replaceBinary)
            ps.setNull(paramIndex++, java.sql.Types.NUMERIC); //set preview ref to null
        ps.setBoolean(paramIndex++, created.isImage());
        ps.setDouble(paramIndex++, created.getResolution());
        ps.setInt(paramIndex++, created.getWidth());
        ps.setInt(paramIndex++, created.getHeight());
        ps.setString(paramIndex++, created.getMd5sum());
        if (replaceBinary) {
            ps.setLong(paramIndex++, created.getId());
            ps.setInt(paramIndex++, created.getVersion()); //version
            ps.setInt(paramIndex, created.getQuality()); //quality
        } else
            ps.setString(paramIndex, binary.getHandle());
        ps.executeUpdate();
        if (needExplicitBlobInsert) {
            ps.close();
            ps = con.prepareStatement(
                    "UPDATE " + TBL_CONTENT_BINARY + " SET FBLOB=? WHERE ID=? AND VER=? AND QUALITY=?");
            fis = new FileInputStream(binaryTransit);
            ps.setBinaryStream(1, fis, (int) binaryTransit.length());
            ps.setLong(2, created.getId());
            ps.setInt(3, created.getVersion()); //version
            ps.setInt(4, created.getQuality()); //quality
            ps.executeUpdate();
        }
        if (removeTransitFile && binaryTransit != null) {
            //transit file was a temp. file -> got to clean up
            FxFileUtils.removeFile(binaryTransit);
        }

        if (replaceBinary) {
            ps.close();
            //set all preview entries to the values provided by the transit table
            ps = con.prepareStatement("UPDATE " + TBL_CONTENT_BINARY
                    + " SET PREV1=NULL,PREV2=NULL,PREV3=NULL,PREV4=NULL WHERE ID=? AND VER=? AND QUALITY=?");
            ps.setLong(1, created.getId());
            ps.setInt(2, created.getVersion()); //version
            ps.setInt(3, created.getQuality()); //quality
            ps.executeUpdate();
            ps.close();
            ps = con.prepareStatement(
                    "SELECT PREV1_WIDTH,PREV1_HEIGHT,PREV1SIZE,PREV2_WIDTH,PREV2_HEIGHT,PREV2SIZE,PREV3_WIDTH,PREV3_HEIGHT,PREV3SIZE,PREV4_WIDTH,PREV4_HEIGHT,PREV4SIZE FROM "
                            + TBL_BINARY_TRANSIT + " WHERE BKEY=?");
            ps.setString(1, binary.getHandle());
            ResultSet rsPrev = ps.executeQuery();
            if (rsPrev != null && rsPrev.next()) {
                long[] data = new long[12];
                for (int d = 0; d < 12; d++)
                    data[d] = rsPrev.getLong(d + 1);
                ps.close();
                ps = con.prepareStatement("UPDATE " + TBL_CONTENT_BINARY
                        + " SET PREV1_WIDTH=?,PREV1_HEIGHT=?,PREV1SIZE=?,PREV2_WIDTH=?,PREV2_HEIGHT=?,PREV2SIZE=?,PREV3_WIDTH=?,PREV3_HEIGHT=?,PREV3SIZE=?,PREV4_WIDTH=?,PREV4_HEIGHT=?,PREV4SIZE=? WHERE ID=? AND VER=? AND QUALITY=?");
                for (int d = 0; d < 12; d++)
                    ps.setLong(d + 1, data[d]);
                ps.setLong(13, created.getId());
                ps.setInt(14, created.getVersion()); //version
                ps.setInt(15, created.getQuality()); //quality
                ps.executeUpdate();
            }
        }

        //finally fetch the preview blobs from transit and store them on the filesystem if required
        if (storePrev1FS || storePrev2FS || storePrev3FS || storePrev4FS) {
            ps.close();
            previewSelect = (!storePrev1FS ? ",NULL" : ",PREV1") + (!storePrev2FS ? ",NULL" : ",PREV2")
                    + (!storePrev3FS ? ",NULL" : ",PREV3") + (!storePrev4FS ? ",NULL" : ",PREV4");
            ps = con.prepareStatement("SELECT " + previewSelect.substring(1) + BINARY_TRANSIT_PREVIEW_WHERE);
            ps.setString(1, binary.getHandle());
            ResultSet rs = ps.executeQuery();
            if (!rs.next())
                throw new FxDbException("ex.content.binary.transitNotFound", binary.getHandle());
            if (storePrev1FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev1Length, rs.getBinaryStream(1),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.PREVIEW1.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.PREVIEW1.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.PREVIEW1.getBlobIndex() + "]", e.getMessage());
                }
            if (storePrev2FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev2Length, rs.getBinaryStream(2),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.PREVIEW2.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.PREVIEW2.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.PREVIEW2.getBlobIndex() + "]", e.getMessage());
                }
            if (storePrev3FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev3Length, rs.getBinaryStream(3),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.PREVIEW3.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.PREVIEW3.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.PREVIEW3.getBlobIndex() + "]", e.getMessage());
                }
            if (storePrev4FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev4Length, rs.getBinaryStream(4),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.SCREENVIEW.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.SCREENVIEW.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.SCREENVIEW.getBlobIndex() + "]",
                            e.getMessage());
                }
        }
        con.commit();
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
    } catch (FileNotFoundException e) {
        throw new FxDbException(e, "ex.content.binary.IOError", binary.getHandle());
    } finally {
        Database.closeObjects(GenericBinarySQLStorage.class, con, ps);
        FxSharedUtils.close(fis);
    }
    return created;
}

From source file:org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.java

public HashMap<String, String> getURITemplatesPerAPIAsString(APIIdentifier identifier)
        throws APIManagementException {
    Connection conn = null;//from  w w  w .  j  ava2s .  c  o m
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    int apiId;
    HashMap<String, String> urlMappings = new LinkedHashMap<String, String>();
    try {
        conn = APIMgtDBUtil.getConnection();
        apiId = getAPIID(identifier, conn);

        String sqlQuery = SQLConstants.GET_URL_TEMPLATES_SQL;

        ps = conn.prepareStatement(sqlQuery);
        ps.setInt(1, apiId);
        resultSet = ps.executeQuery();
        while (resultSet.next()) {
            String script = null;
            String uriPattern = resultSet.getString("URL_PATTERN");
            String httpMethod = resultSet.getString("HTTP_METHOD");
            String authScheme = resultSet.getString("AUTH_SCHEME");
            String throttlingTier = resultSet.getString("THROTTLING_TIER");
            InputStream mediationScriptBlob = resultSet.getBinaryStream("MEDIATION_SCRIPT");
            if (mediationScriptBlob != null) {
                script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
                // set null if the script is empty. Otherwise ArrayIndexOutOfBoundsException occurs when trying
                // to split by ::
                if (script.isEmpty()) {
                    script = null;
                }
            }
            urlMappings.put(
                    uriPattern + "::" + httpMethod + "::" + authScheme + "::" + throttlingTier + "::" + script,
                    null);
        }
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                log.error("Failed to rollback the add subscription ", e1);
            }
        }
        handleException("Failed to add subscriber data ", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
    }
    return urlMappings;
}

From source file:org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.java

public ArrayList<URITemplate> getAllURITemplatesOldThrottle(String apiContext, String version)
        throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    ArrayList<URITemplate> uriTemplates = new ArrayList<URITemplate>();

    //TODO : FILTER RESULTS ONLY FOR ACTIVE APIs
    String query = SQLConstants.GET_ALL_URL_TEMPLATES_SQL;
    try {/*from w  ww.  j a  va  2s  .  c  o m*/
        connection = APIMgtDBUtil.getConnection();
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, apiContext);
        prepStmt.setString(2, version);

        rs = prepStmt.executeQuery();

        URITemplate uriTemplate;
        while (rs.next()) {
            uriTemplate = new URITemplate();
            String script = null;
            uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
            uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
            uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
            uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
            InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
            if (mediationScriptBlob != null) {
                script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
            }
            uriTemplate.setMediationScript(script);
            uriTemplate.getThrottlingConditions().add("_default");
            uriTemplates.add(uriTemplate);
        }
    } catch (SQLException e) {
        handleException("Error while fetching all URL Templates", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
    return uriTemplates;
}

From source file:org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.java

/**
 * Get all subscription level policeis belongs to specific tenant
 *
 * @param tenantID tenantID filters the polices belongs to specific tenant
 * @return subscriptionPolicy array list
 *//* www.jav  a  2  s. c  om*/
public SubscriptionPolicy[] getSubscriptionPolicies(int tenantID) throws APIManagementException {
    List<SubscriptionPolicy> policies = new ArrayList<SubscriptionPolicy>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICIES;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICIES;
    }

    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        ps.setInt(1, tenantID);
        rs = ps.executeQuery();
        while (rs.next()) {
            SubscriptionPolicy subPolicy = new SubscriptionPolicy(
                    rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
            setCommonPolicyDetails(subPolicy, rs);
            subPolicy.setRateLimitCount(rs.getInt(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_COUNT));
            subPolicy.setRateLimitTimeUnit(rs.getString(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_TIME_UNIT));
            subPolicy.setStopOnQuotaReach(rs.getBoolean(ThrottlePolicyConstants.COLUMN_STOP_ON_QUOTA_REACH));
            subPolicy.setBillingPlan(rs.getString(ThrottlePolicyConstants.COLUMN_BILLING_PLAN));
            InputStream binary = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_CUSTOM_ATTRIB);
            if (binary != null) {
                byte[] customAttrib = APIUtil.toByteArray(binary);
                subPolicy.setCustomAttributes(customAttrib);
            }
            policies.add(subPolicy);
        }
    } catch (SQLException e) {
        handleException("Error while executing SQL", e);
    } catch (IOException e) {
        handleException("Error while converting input stream to byte array", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return policies.toArray(new SubscriptionPolicy[policies.size()]);
}

From source file:org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.java

/**
 * Get a particular Global level policy.
 *
 * @param policyName name of the global polixy
 * @return {@link GlobalPolicy}//from w  ww .jav  a 2 s. c  o  m
 * @throws APIManagementException
 */
public GlobalPolicy getGlobalPolicy(String policyName) throws APIManagementException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String sqlQuery = SQLConstants.GET_GLOBAL_POLICY;

    GlobalPolicy globalPolicy = null;
    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        ps.setString(1, policyName);
        rs = ps.executeQuery();

        if (rs.next()) {
            String siddhiQuery = null;
            globalPolicy = new GlobalPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
            globalPolicy.setDescription(rs.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
            globalPolicy.setPolicyId(rs.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
            globalPolicy.setUUID(rs.getString(ThrottlePolicyConstants.COLUMN_UUID));
            globalPolicy.setTenantId(rs.getShort(ThrottlePolicyConstants.COLUMN_TENANT_ID));
            globalPolicy.setKeyTemplate(rs.getString(ThrottlePolicyConstants.COLUMN_KEY_TEMPLATE));
            globalPolicy.setDeployed(rs.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
            InputStream siddhiQueryBlob = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_SIDDHI_QUERY);
            if (siddhiQueryBlob != null) {
                siddhiQuery = APIMgtDBUtil.getStringFromInputStream(siddhiQueryBlob);
            }
            globalPolicy.setSiddhiQuery(siddhiQuery);
        }
    } catch (SQLException e) {
        handleException("Error while executing SQL", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return globalPolicy;
}

From source file:org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.java

/**
 * Get a particular Global level policy given UUID.
 *
 * @param uuid name of the global polixy
 * @return {@link GlobalPolicy}//w w w.  j  ava  2  s  .co  m
 * @throws APIManagementException
 */
public GlobalPolicy getGlobalPolicyByUUID(String uuid) throws APIManagementException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String sqlQuery = SQLConstants.GET_GLOBAL_POLICY_BY_UUID;

    GlobalPolicy globalPolicy = null;
    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        ps.setString(1, uuid);
        rs = ps.executeQuery();

        if (rs.next()) {
            String siddhiQuery = null;
            globalPolicy = new GlobalPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
            globalPolicy.setDescription(rs.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
            globalPolicy.setPolicyId(rs.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
            globalPolicy.setUUID(rs.getString(ThrottlePolicyConstants.COLUMN_UUID));
            globalPolicy.setTenantId(rs.getShort(ThrottlePolicyConstants.COLUMN_TENANT_ID));
            globalPolicy.setKeyTemplate(rs.getString(ThrottlePolicyConstants.COLUMN_KEY_TEMPLATE));
            globalPolicy.setDeployed(rs.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
            InputStream siddhiQueryBlob = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_SIDDHI_QUERY);
            if (siddhiQueryBlob != null) {
                siddhiQuery = APIMgtDBUtil.getStringFromInputStream(siddhiQueryBlob);
            }
            globalPolicy.setSiddhiQuery(siddhiQuery);
        }
    } catch (SQLException e) {
        handleException("Error while retrieving global policy by uuid " + uuid, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return globalPolicy;
}

From source file:org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.java

/**
 * Get all Global level policeis belongs to specific tenant
 *
 * @param tenantID//from w w w .ja v a2  s .  co m
 * @return
 * @throws APIManagementException
 */
public GlobalPolicy[] getGlobalPolicies(int tenantID) throws APIManagementException {
    List<GlobalPolicy> policies = new ArrayList<GlobalPolicy>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String sqlQuery = SQLConstants.GET_GLOBAL_POLICIES;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.GET_GLOBAL_POLICIES;
    }

    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        ps.setInt(1, tenantID);
        rs = ps.executeQuery();
        while (rs.next()) {
            String siddhiQuery = null;
            GlobalPolicy globalPolicy = new GlobalPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
            globalPolicy.setDescription(rs.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
            globalPolicy.setPolicyId(rs.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
            globalPolicy.setUUID(rs.getString(ThrottlePolicyConstants.COLUMN_UUID));
            globalPolicy.setTenantId(rs.getShort(ThrottlePolicyConstants.COLUMN_TENANT_ID));
            globalPolicy.setKeyTemplate(rs.getString(ThrottlePolicyConstants.COLUMN_KEY_TEMPLATE));
            globalPolicy.setDeployed(rs.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
            InputStream siddhiQueryBlob = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_SIDDHI_QUERY);
            if (siddhiQueryBlob != null) {
                siddhiQuery = APIMgtDBUtil.getStringFromInputStream(siddhiQueryBlob);
            }
            globalPolicy.setSiddhiQuery(siddhiQuery);
            policies.add(globalPolicy);
        }
    } catch (SQLException e) {
        handleException("Error while executing SQL", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return policies.toArray(new GlobalPolicy[policies.size()]);
}

From source file:org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO.java

/**
 * Retrieves {@link SubscriptionPolicy} with name <code>uuid</code>
 *
 * @param uuid name of the policy to retrieve from the database
 * @return {@link SubscriptionPolicy}/*from   www  .j  a v a 2s .  co m*/
 * @throws APIManagementException
 */
public SubscriptionPolicy getSubscriptionPolicyByUUID(String uuid) throws APIManagementException {
    SubscriptionPolicy policy = null;
    Connection connection = null;
    PreparedStatement selectStatement = null;
    ResultSet resultSet = null;

    String sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICY_BY_UUID_SQL;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICY_BY_UUID_SQL;
    }

    try {
        connection = APIMgtDBUtil.getConnection();
        selectStatement = connection.prepareStatement(sqlQuery);
        selectStatement.setString(1, uuid);

        // Should return only single row
        resultSet = selectStatement.executeQuery();
        if (resultSet.next()) {
            policy = new SubscriptionPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
            setCommonPolicyDetails(policy, resultSet);
            policy.setRateLimitCount(resultSet.getInt(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_COUNT));
            policy.setRateLimitTimeUnit(
                    resultSet.getString(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_TIME_UNIT));
            policy.setStopOnQuotaReach(
                    resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_STOP_ON_QUOTA_REACH));
            policy.setBillingPlan(resultSet.getString(ThrottlePolicyConstants.COLUMN_BILLING_PLAN));
            InputStream binary = resultSet.getBinaryStream(ThrottlePolicyConstants.COLUMN_CUSTOM_ATTRIB);
            if (binary != null) {
                byte[] customAttrib = APIUtil.toByteArray(binary);
                policy.setCustomAttributes(customAttrib);
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get subscription policy: " + uuid, e);
    } catch (IOException e) {
        handleException("Error while converting input stream to byte array", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
    }
    return policy;
}