Example usage for java.sql PreparedStatement setBinaryStream

List of usage examples for java.sql PreparedStatement setBinaryStream

Introduction

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

Prototype

void setBinaryStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException;

Source Link

Document

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

Usage

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

private void updateMenu(User user, CopyContext copyContext, Document doc, boolean useOldKeys)
        throws VerticalUpdateException, VerticalSecurityException {
    Element root_elem = doc.getDocumentElement();

    // get menu key:
    String tmp = root_elem.getAttribute("key");
    SiteKey menuKey = new SiteKey(tmp);

    Connection con = null;//www  .  java2s . co m
    PreparedStatement preparedStmt = null;
    try {
        con = getConnection();

        // Update the main menu table:
        preparedStmt = con.prepareStatement(MENU_UPDATE);

        // firstpage:
        Element tmpElement = XMLTool.getElement(root_elem, "firstpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(1, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(1, Types.INTEGER);
        }

        // loginpage:
        tmpElement = XMLTool.getElement(root_elem, "loginpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(2, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(2, Types.INTEGER);
        }

        // errorpage:
        tmpElement = XMLTool.getElement(root_elem, "errorpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(3, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(3, Types.INTEGER);
        }

        // default pagetemplate:
        tmpElement = XMLTool.getElement(root_elem, "defaultpagetemplate");
        if (tmpElement != null) {
            tmp = tmpElement.getAttribute("pagetemplatekey");
            preparedStmt.setInt(4, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(4, Types.INTEGER);
        }

        SiteData siteData = new SiteData();

        // DeviceClassResolver:
        tmpElement = XMLTool.getElement(root_elem, "deviceclassresolver");
        if (tmpElement != null) {
            String deviceClassResolverUrl = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(deviceClassResolverUrl)) {
                siteData.setDeviceClassResolver(new ResourceKey(deviceClassResolverUrl));
            }
        }

        // default localization resource:
        tmpElement = XMLTool.getElement(root_elem, "defaultlocalizationresource");
        if (tmpElement != null) {
            String defaultLocalizationResource = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(defaultLocalizationResource)) {
                siteData.setDefaultLocalizationResource(new ResourceKey(defaultLocalizationResource));
            }
        }

        // locale resolver:
        tmpElement = XMLTool.getElement(root_elem, "localeresolver");
        if (tmpElement != null) {
            String localeResolver = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(localeResolver)) {
                siteData.setLocaleResolver(new ResourceKey(localeResolver));
            }
        }

        // Path to public home:
        String pathToPublicHome = root_elem.getAttribute("pathtopublichome");
        if (StringUtils.isNotEmpty(pathToPublicHome)) {
            siteData.setPathToPublicResources(new ResourceKey(pathToPublicHome));
        }

        // Path to home:
        String pathToHome = root_elem.getAttribute("pathtohome");
        if (StringUtils.isNotEmpty(pathToHome)) {
            siteData.setPathToResources(new ResourceKey(pathToHome));
        }

        tmpElement = XMLTool.getElement(root_elem, "menudata");
        if (tmpElement != null) {
            parseAndAddMenudataToSiteData(tmpElement, siteData);
        }

        final byte[] xmldata = siteData.getAsBytes();
        preparedStmt.setBinaryStream(5, new ByteArrayInputStream(xmldata), xmldata.length);

        // language key:
        preparedStmt.setInt(6, Integer.parseInt(root_elem.getAttribute("languagekey")));

        Element detailsElement = XMLTool.getElement(root_elem, "details");

        // Statistics URL:
        tmpElement = XMLTool.getElement(detailsElement, "statistics");
        if (tmpElement != null) {
            String name = XMLTool.getElementText(tmpElement);
            if (name != null) {
                preparedStmt.setString(7, name);
            } else {
                preparedStmt.setNull(7, Types.VARCHAR);
            }
        } else {
            preparedStmt.setNull(7, Types.VARCHAR);
        }

        // Run As User:
        String runAsUserKey = root_elem.getAttribute("runas");
        if (StringUtils.isNotEmpty(runAsUserKey)) {
            preparedStmt.setString(8, runAsUserKey);
        } else {
            preparedStmt.setNull(8, Types.VARCHAR);
        }

        // menu key:
        preparedStmt.setInt(9, menuKey.toInt());
        preparedStmt.executeUpdate();
        preparedStmt.close();
        preparedStmt = null;

        // Update the individual menuitems (recursivly):
        try {
            Element[] elems = XMLTool.getElements(XMLTool.getElement(root_elem, "menuitems"));
            for (int i = 0; i < elems.length; i++) {
                String curDeleted = elems[i].getAttribute("deleted");
                if (!"deleted".equals(curDeleted)) {
                    String curKey = elems[i].getAttribute("key");
                    if (curKey == null || curKey.length() == 0 || !useOldKeys) {
                        createMenuItem(user, copyContext, elems[i], menuKey, i, null, useOldKeys);
                    } else {
                        updateMenuItem(user, elems[i], menuKey, i, null, true);
                    }
                }
            }
        } catch (VerticalCreateException vce) {
            VerticalEngineLogger.errorUpdate(this.getClass(), 2, "Failed to create new menuitem: %t", vce);
        }

        // get all deleted menuitems:
        String xpath = "//menuitem[@deleted = 'deleted']";

        try {
            // Search for the xpath:
            NodeList list = XMLTool.selectNodes(doc.getDocumentElement(), xpath);

            // Loop through the results.
            for (int i = 0; i < list.getLength(); i++) {
                Element n = (Element) list.item(i);
                tmp = n.getAttribute("key");
                removeMenuItem(user, Integer.parseInt(tmp));
            }

        } catch (VerticalRemoveException vre) {
            VerticalEngineLogger.errorUpdate(this.getClass(), 3, "Failed to remove menuitem: %t", vre);
        }
    } catch (SQLException sqle) {
        VerticalEngineLogger.errorUpdate(this.getClass(), 5, "A database error occurred: %t", sqle);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

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   ww w  . jav  a2  s  . com*/
 * @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.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Set the Statement column so that the results are mapped correctly.
 *
 * @param statement the prepared statement
 * @param position the position of the column
 * @param value the value of the column//from   ww  w  .j  a  va  2s.  c  om
 */
public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject)
        throws Exception {
    if (value instanceof String) {
        value = ((String) value).trim();
    }
    if (typeObject == null) {
        throw new SQLException("Can't set column because the type is unrecognized");
    }
    if (value == null) {
        /** If the value is null, set the column value null and return **/
        statement.setNull(position, typeObject.intValue());
        return;
    }
    if ("".equals(value)) {
        switch (typeObject.intValue()) {
        case Types.CHAR:
        case Types.CLOB:
        case Types.VARCHAR:
            /** If the value is an empty string and the column is
            a string type, we can continue **/
            break;
        default:
            /** If the value is an empty string and the column
            is something else, we treat it as a null value **/
            statement.setNull(position, typeObject.intValue());
            return;
        }
    }

    File file = null;
    int length = -1;
    InputStream asciiStream = null;

    //System.out.println("========================================================================");
    //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
    switch (typeObject.intValue()) {
    case Types.CLOB:
        //System.out.println("CLOB");
        Clob clob = null;
        if (value instanceof Clob) {
            clob = (Clob) value;
        } else if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new ByteArrayInputStream(asciiText.getBytes());
            length = asciiText.length();
            clob = new ClobHelper(asciiStream, length);
        }

        statement.setClob(position, clob);
        break;
    case Types.CHAR:
        // simple large object, e.g. Informix's TEXT
        //System.out.println("CHAR");

        if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes()));
            length = asciiText.length();
        }

        statement.setAsciiStream(position, asciiStream, length);
        break;
    case Types.BIGINT:
        //System.out.println("BIGINT");
        BigDecimal bd = null;

        if (value instanceof BigDecimal) {
            bd = (BigDecimal) value;
        } else if (value instanceof Number) {
            bd = BigDecimal.valueOf(((Number) value).longValue());
        } else {
            bd = new BigDecimal(value.toString());
        }

        statement.setBigDecimal(position, bd);
        break;
    case Types.TINYINT:
        //System.out.println("TINYINT");
        Byte b = null;

        if (value instanceof Byte) {
            b = (Byte) value;
        } else if (value instanceof Number) {
            b = new Byte(((Number) value).byteValue());
        } else {
            b = new Byte(value.toString());
        }

        statement.setByte(position, b.byteValue());
        break;
    case Types.DATE:
        //System.out.println("DATE");
        Date d = null;

        if (value instanceof Date) {
            d = (Date) value;
        } else if (value instanceof java.util.Date) {
            d = new Date(((java.util.Date) value).getTime());
        } else if (value instanceof Calendar) {
            d = new Date(((Calendar) value).getTime().getTime());
        } else {
            d = Date.valueOf(value.toString());
        }

        statement.setDate(position, d);
        break;
    case Types.DOUBLE:
        //System.out.println("DOUBLE");
        double db;

        if (value instanceof Number) {
            db = (((Number) value).doubleValue());
        } else {
            db = Double.parseDouble(value.toString());
        }
        statement.setDouble(position, db);
        break;
    case Types.FLOAT:
        //System.out.println("FLOAT");
        float f;

        if (value instanceof Number) {
            f = (((Number) value).floatValue());
        } else {
            f = Float.parseFloat(value.toString());
        }
        statement.setFloat(position, f);
        break;
    case Types.NUMERIC:
        //System.out.println("NUMERIC");
        long l;

        if (value instanceof Number) {
            l = (((Number) value).longValue());
        } else {
            l = Long.parseLong(value.toString());
        }

        statement.setLong(position, l);
        break;
    case Types.SMALLINT:
        //System.out.println("SMALLINT");
        Short s = null;

        if (value instanceof Short) {
            s = (Short) value;
        } else if (value instanceof Number) {
            s = new Short(((Number) value).shortValue());
        } else {
            s = new Short(value.toString());
        }

        statement.setShort(position, s.shortValue());
        break;
    case Types.TIME:
        //System.out.println("TIME");
        Time t = null;

        if (value instanceof Time) {
            t = (Time) value;
        } else if (value instanceof java.util.Date) {
            t = new Time(((java.util.Date) value).getTime());
        } else {
            t = Time.valueOf(value.toString());
        }

        statement.setTime(position, t);
        break;
    case Types.TIMESTAMP:
        //System.out.println("TIMESTAMP");
        Timestamp ts = null;

        if (value instanceof Time) {
            ts = (Timestamp) value;
        } else if (value instanceof java.util.Date) {
            ts = new Timestamp(((java.util.Date) value).getTime());
        } else {
            ts = Timestamp.valueOf(value.toString());
        }

        statement.setTimestamp(position, ts);
        break;
    case Types.ARRAY:
        //System.out.println("ARRAY");
        statement.setArray(position, (Array) value); // no way to convert string to array
        break;
    case Types.STRUCT:
        //System.out.println("STRUCT");
    case Types.OTHER:
        //System.out.println("OTHER");
        statement.setObject(position, value);
        break;
    case Types.LONGVARBINARY:
        //System.out.println("LONGVARBINARY");
        statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime()));
        break;
    case Types.VARCHAR:
        //System.out.println("VARCHAR");
        statement.setString(position, value.toString());
        break;
    case Types.BLOB:
        //System.out.println("BLOB");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else {
            Blob blob = null;
            if (value instanceof Blob) {
                blob = (Blob) value;
            } else if (value instanceof File) {
                file = (File) value;
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof String) {
                file = new File((String) value);
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof Part) {
                Part anyFile = (Part) value;
                blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize());
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            statement.setBlob(position, blob);
        }
        break;
    case Types.VARBINARY:
        //System.out.println("VARBINARY");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else if (value instanceof Part) {
            statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize());
        } else {
            if (value instanceof File) {
                file = (File) value;
            } else if (value instanceof String) {
                file = new File((String) value);
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            FileInputStream input = new FileInputStream(file);
            statement.setBinaryStream(position, input, (int) file.length());
        }
        break;
    case Types.INTEGER:
        //System.out.println("INTEGER");
        Integer i = null;
        if (value instanceof Integer) {
            i = (Integer) value;
        } else if (value instanceof Number) {
            i = new Integer(((Number) value).intValue());
        } else {
            i = new Integer(value.toString());
        }
        statement.setInt(position, i.intValue());
        break;
    case Types.BIT:
        //System.out.println("BIT");
        Boolean bo = null;
        if (value instanceof Boolean) {
            bo = (Boolean) value;
        } else if (value instanceof Number) {
            bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1);
        } else {
            bo = BooleanUtils.toBooleanObject(value.toString());
        }
        statement.setBoolean(position, bo.booleanValue());
        break;

    default:
        //System.out.println("default");
        throw new SQLException("Impossible exception - invalid type ");
    }
    //System.out.println("========================================================================");
}

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

private SiteKey createMenu(User user, CopyContext copyContext, Document doc, boolean useOldKey)
        throws VerticalCreateException, VerticalSecurityException {

    Element rootElement = doc.getDocumentElement();

    // Get site key:
    String tmp;//from   w ww. j  ava2 s. co  m

    // Prepare insertion into the database
    SiteKey siteKey = null;
    Connection con = null;
    PreparedStatement preparedStmt = null;
    try {
        con = getConnection();

        tmp = rootElement.getAttribute("key");
        if (!useOldKey || tmp == null || tmp.length() == 0) {
            // generate key:
            siteKey = new SiteKey(getNextKey(MENU_TABLE));
        } else {
            siteKey = new SiteKey(tmp);
        }

        preparedStmt = con.prepareStatement(MENU_INSERT);

        if (copyContext != null) {
            copyContext.putMenuKey(Integer.parseInt(tmp), siteKey.toInt());
        }
        preparedStmt.setInt(1, siteKey.toInt());

        // name:
        Element tmpElement = XMLTool.getElement(rootElement, "name");
        String name = null;
        if (tmpElement != null) {
            name = XMLTool.getElementText(tmpElement);
        }
        if (name != null) {
            preparedStmt.setString(6, name);
        } else {
            preparedStmt.setNull(6, Types.VARCHAR);
        }

        // firstpage:
        tmpElement = XMLTool.getElement(rootElement, "firstpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(2, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(2, Types.INTEGER);
        }

        // loginpage:
        tmpElement = XMLTool.getElement(rootElement, "loginpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(3, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(3, Types.INTEGER);
        }

        // errorpage:
        tmpElement = XMLTool.getElement(rootElement, "errorpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(4, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(4, Types.INTEGER);
        }

        // default pagetemplate:
        tmpElement = XMLTool.getElement(rootElement, "defaultpagetemplate");
        if (tmpElement != null) {
            tmp = tmpElement.getAttribute("pagetemplatekey");
            if (tmp != null && tmp.length() > 0) {
                preparedStmt.setInt(5, Integer.parseInt(tmp));
            } else {
                preparedStmt.setNull(5, Types.INTEGER);
            }
        } else {
            preparedStmt.setNull(5, Types.INTEGER);
        }

        SiteData siteData = new SiteData();

        // DeviceClassResolver:
        tmpElement = XMLTool.getElement(rootElement, "deviceclassresolver");
        if (tmpElement != null) {
            String deviceClassResolverUrl = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(deviceClassResolverUrl)) {
                siteData.setDeviceClassResolver(new ResourceKey(deviceClassResolverUrl));
            }
        }

        // Default localization resource:
        tmpElement = XMLTool.getElement(rootElement, "defaultlocalizationresource");
        if (tmpElement != null) {
            String defaultLocalizationResource = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(defaultLocalizationResource)) {
                siteData.setDefaultLocalizationResource(new ResourceKey(defaultLocalizationResource));
            }
        }

        // locale resolver
        tmpElement = XMLTool.getElement(rootElement, "localeresolver");
        if (tmpElement != null) {
            String localeResolver = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(localeResolver)) {
                siteData.setLocaleResolver(new ResourceKey(localeResolver));
            }
        }

        // Path to public home:
        String pathToPublicHome = rootElement.getAttribute("path-to-public-home-resources");
        if (StringUtils.isNotEmpty(pathToPublicHome)) {
            siteData.setPathToPublicResources(new ResourceKey(pathToPublicHome));
        }

        // Path to home:
        String pathToHome = rootElement.getAttribute("path-to-home-resources");
        if (StringUtils.isNotEmpty(pathToHome)) {
            siteData.setPathToResources(new ResourceKey(pathToHome));
        }

        tmpElement = XMLTool.getElement(rootElement, "menudata");
        if (tmpElement != null) {
            parseAndAddMenudataToSiteData(tmpElement, siteData);
        }

        final byte[] xmldata = siteData.getAsBytes();
        preparedStmt.setBinaryStream(7, new ByteArrayInputStream(xmldata), xmldata.length);

        // language key:
        preparedStmt.setInt(8, Integer.parseInt(rootElement.getAttribute("languagekey")));

        Element detailsElement = XMLTool.getElement(rootElement, "details");

        // Statistics URL:
        tmpElement = XMLTool.getElement(detailsElement, "statistics");
        if (tmpElement != null) {
            String statisticsURL = XMLTool.getElementText(tmpElement);
            if (statisticsURL != null) {
                preparedStmt.setString(9, statisticsURL);
            } else {
                preparedStmt.setNull(9, Types.VARCHAR);
            }
        } else {
            preparedStmt.setNull(9, Types.VARCHAR);
        }

        // Run As User:
        String runAsUserKey = rootElement.getAttribute("runas");
        if (StringUtils.isNotEmpty(runAsUserKey)) {
            preparedStmt.setString(10, runAsUserKey);
        } else {
            preparedStmt.setNull(10, Types.VARCHAR);
        }

        // insert the data:
        preparedStmt.executeUpdate();

        // create default menu access rights
        GroupHandler groupHandler = getGroupHandler();
        String groupKey = groupHandler.getAdminGroupKey();

        Document tmpDoc = XMLTool.createDocument("accessrights");
        Element root = tmpDoc.getDocumentElement();
        root.setAttribute("type", String.valueOf(AccessRight.MENUITEM_DEFAULT));
        root.setAttribute("key", String.valueOf(siteKey));

        Element accessrightElem = XMLTool.createElement(tmpDoc, root, "accessright");
        accessrightElem.setAttribute("groupkey", groupKey);
        accessrightElem.setAttribute("grouptype", GroupType.ADMINS.toInteger().toString());

        accessrightElem.setAttribute("read", "true");
        accessrightElem.setAttribute("create", "true");
        accessrightElem.setAttribute("update", "true");
        accessrightElem.setAttribute("delete", "true");
        accessrightElem.setAttribute("publish", "true");
        accessrightElem.setAttribute("add", "true");
        accessrightElem.setAttribute("administrate", "true");

        getSecurityHandler().updateAccessRights(user, tmpDoc);

        //////// Create menuitems:
        Element itemsElement = XMLTool.getElement(rootElement, "menuitems");
        if (itemsElement != null) {
            Element[] itemElems = XMLTool.getElements(itemsElement);

            for (int i = 0; i < itemElems.length; i++) {
                createMenuItem(user, copyContext, itemElems[i], siteKey, i, null, useOldKey);
            }
        }
    } catch (SQLException sqle) {
        String msg = "Failed to create menu: %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, msg, sqle);
    } catch (VerticalKeyException gke) {
        String msg = "Unable to generate key for table %0.";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, msg, MENU_TABLE, gke);
    } catch (VerticalUpdateException e) {
        VerticalEngineLogger.errorCreate(this.getClass(), 10, "Error creating default access rights: %t", e);
    } finally {
        close(preparedStmt);
        close(con);
    }

    return siteKey;
}

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

private void updateMenuItemData(User user, Element menuItemElem, int type, MenuItemKey parent, int order)
        throws VerticalUpdateException {

    String tmp;/*from  w  ww . j av  a  2  s  .c o m*/
    boolean modified = "modified".equals(menuItemElem.getAttribute("modified"));

    Connection con = null;
    PreparedStatement preparedStmt = null;
    try {
        con = getConnection();

        // update the main table:
        int psCounter = 1;
        if (modified) {
            preparedStmt = con.prepareStatement(MENU_ITEM_UPDATE);
        } else {
            preparedStmt = con.prepareStatement(MENU_ITEM_UPDATE_NO_DATA);
        }
        //}

        // name
        Element tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_MENUITEM_NAME);
        String name = XMLTool.getElementText(tmp_elem);

        validateMenuItemName(name);

        StringReader sreader = new StringReader(name);
        preparedStmt.setCharacterStream(psCounter++, sreader, name.length());

        if (parent != null) {
            preparedStmt.setInt(psCounter++, parent.toInt());
        } else {
            preparedStmt.setNull(psCounter++, Types.INTEGER);
        }

        // order
        preparedStmt.setInt(psCounter++, order);

        Element dataElem;
        if (modified) {
            dataElem = XMLTool.getElement(menuItemElem, "data");

            // parameters
            tmp_elem = XMLTool.getElement(menuItemElem, "parameters");
            if (tmp_elem != null) {
                dataElem.appendChild(tmp_elem);
            }
        } else {
            dataElem = null;
        }

        // alternative name:
        tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_MENU_NAME);
        if (tmp_elem != null) {
            tmp = XMLTool.getElementText(tmp_elem);
            preparedStmt.setString(psCounter++, tmp);
        } else {
            preparedStmt.setNull(psCounter++, Types.VARCHAR);
        }

        // visibility:
        tmp = menuItemElem.getAttribute("visible");
        if ("no".equals(tmp)) {
            preparedStmt.setInt(psCounter++, 1);
        } else {
            preparedStmt.setInt(psCounter++, 0);
        }

        // description:
        tmp_elem = XMLTool.getElement(menuItemElem, "description");
        String data = XMLTool.getElementText(tmp_elem);
        if (data == null) {
            data = "";
        }
        StringReader reader = new StringReader(data);
        preparedStmt.setCharacterStream(psCounter++, reader, data.length());

        // keywords
        tmp_elem = XMLTool.getElement(menuItemElem, "keywords");
        String keywords = XMLTool.getElementText(tmp_elem);
        if (keywords == null || keywords.length() == 0) {
            preparedStmt.setNull(psCounter++, Types.VARCHAR);
        } else {
            StringReader keywordReader = new StringReader(keywords);
            preparedStmt.setCharacterStream(psCounter++, keywordReader, keywords.length());
        }

        // language
        String lanKey = menuItemElem.getAttribute("languagekey");
        if ((lanKey != null) && (lanKey.length() > 0)) {
            preparedStmt.setInt(psCounter++, Integer.parseInt(lanKey));
        } else {
            preparedStmt.setNull(psCounter++, Types.INTEGER);
        }

        // get menuitem key:
        tmp = menuItemElem.getAttribute("key");
        int key = Integer.parseInt(tmp);

        // owner
        String ownerKey = menuItemElem.getAttribute("owner");

        // modifier
        String modifierKey = menuItemElem.getAttribute("modifier");

        if (modified && type == 4) {
            //byte[] document = null;
            Element docElem = XMLTool.getElement(menuItemElem, "document");
            dataElem.appendChild(docElem);
        }
        preparedStmt.setString(psCounter++, ownerKey);
        preparedStmt.setString(psCounter++, modifierKey);

        RunAsType runAs = RunAsType.INHERIT;
        String runAsStr = menuItemElem.getAttribute("runAs");
        if (StringUtils.isNotEmpty(runAsStr)) {
            runAs = RunAsType.valueOf(runAsStr);
        }
        preparedStmt.setInt(psCounter++, runAs.getKey());

        // displayname:
        tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_DISPLAY_NAME);

        if (tmp_elem == null) {
            throw new IllegalArgumentException("Displayname must be set");
        } else {
            tmp = XMLTool.getElementText(tmp_elem);
            preparedStmt.setString(psCounter++, tmp);
        }

        // data
        if (modified) {
            Document dataDoc = XMLTool.createDocument();
            dataDoc.appendChild(dataDoc.importNode(dataElem, true));

            byte[] bytes = XMLTool.documentToBytes(dataDoc, "UTF-8");
            preparedStmt.setBinaryStream(psCounter++, new ByteArrayInputStream(bytes), bytes.length);
        }

        preparedStmt.setInt(psCounter, key);

        preparedStmt.executeUpdate();

        if (multicaster.hasListeners()) {
            int menuKey = getMenuKeyByMenuItem(key);
            MenuHandlerEvent e = new MenuHandlerEvent(user, menuKey, key, name, this);
            multicaster.updatedMenuItem(e);
        }
    } catch (SQLException sqle) {
        VerticalEngineLogger.errorUpdate(this.getClass(), 20, "SQL error while updating menuitem data.", sqle);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

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

/**
 * Add a Global level throttling policy to database
 *
 * @param policy Global Policy/*from  w  w  w . ja v  a  2  s.co m*/
 * @throws APIManagementException
 */
public void addGlobalPolicy(GlobalPolicy policy) throws APIManagementException {
    Connection conn = null;
    PreparedStatement policyStatement = null;
    try {
        conn = APIMgtDBUtil.getConnection();
        conn.setAutoCommit(false);
        String addQuery = SQLConstants.INSERT_GLOBAL_POLICY_SQL;
        policyStatement = conn.prepareStatement(addQuery);
        policyStatement.setString(1, policy.getPolicyName());
        policyStatement.setInt(2, policy.getTenantId());
        policyStatement.setString(3, policy.getKeyTemplate());
        policyStatement.setString(4, policy.getDescription());

        InputStream siddhiQueryInputStream;
        byte[] byteArray = policy.getSiddhiQuery().getBytes(Charset.defaultCharset());
        int lengthOfBytes = byteArray.length;
        siddhiQueryInputStream = new ByteArrayInputStream(byteArray);
        policyStatement.setBinaryStream(5, siddhiQueryInputStream, lengthOfBytes);
        policyStatement.setBoolean(6, false);
        policyStatement.setString(7, UUID.randomUUID().toString());
        policyStatement.executeUpdate();
        conn.commit();
    } catch (SQLException e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException ex) {

                // rollback failed. exception will be thrown later for upper exception
                log.error("Failed to rollback the add Global Policy: " + policy.toString(), ex);
            }
        }
        handleException("Failed to add Global Policy: " + policy, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(policyStatement, conn, null);
    }
}

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

/**
 * Updates global throttle policy in database
 *
 * @param policy updated policy obejct/*  w  w w .jav  a 2s.  c  o m*/
 * @throws APIManagementException
 */
public void updateGlobalPolicy(GlobalPolicy policy) throws APIManagementException {
    Connection connection = null;
    PreparedStatement updateStatement = null;
    InputStream siddhiQueryInputStream;

    try {
        byte[] byteArray = policy.getSiddhiQuery().getBytes(Charset.defaultCharset());
        int lengthOfBytes = byteArray.length;
        siddhiQueryInputStream = new ByteArrayInputStream(byteArray);
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
            updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_POLICY_SQL);
        } else if (!StringUtils.isBlank(policy.getUUID())) {
            updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_POLICY_BY_UUID_SQL);
        } else {
            String errorMsg = "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id"
                    + " should be provided. Name: " + policy.getPolicyName() + ", Tenant Id: "
                    + policy.getTenantId() + ", UUID: " + policy.getUUID();
            log.error(errorMsg);
            throw new APIManagementException(errorMsg);
        }

        updateStatement.setString(1, policy.getDescription());
        updateStatement.setBinaryStream(2, siddhiQueryInputStream, lengthOfBytes);
        updateStatement.setString(3, policy.getKeyTemplate());
        if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
            updateStatement.setString(4, policy.getPolicyName());
            updateStatement.setInt(5, policy.getTenantId());
        } else if (!StringUtils.isBlank(policy.getUUID())) {
            updateStatement.setString(4, policy.getUUID());
        }
        updateStatement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {

                // Rollback failed. Exception will be thrown later for upper exception
                log.error("Failed to rollback the update Global Policy: " + policy.toString(), ex);
            }
        }
        handleException(
                "Failed to update global policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
    }
}

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

/**
 * Adds URI templates define for an API//from  w w w .  ja  v  a 2s. co  m
 *
 * @param apiId
 * @param api
 * @param connection
 * @throws APIManagementException
 */
public void addURLTemplates(int apiId, API api, Connection connection) throws APIManagementException {
    if (apiId == -1) {
        //application addition has failed
        return;
    }
    PreparedStatement prepStmt = null;
    PreparedStatement scopePrepStmt = null;

    String query = SQLConstants.ADD_URL_MAPPING_SQL;
    String scopeQuery = SQLConstants.ADD_OAUTH2_RESOURCE_SCOPE_SQL;
    try {
        //connection = APIMgtDBUtil.getConnection();
        prepStmt = connection.prepareStatement(query);
        scopePrepStmt = connection.prepareStatement(scopeQuery);

        Iterator<URITemplate> uriTemplateIterator = api.getUriTemplates().iterator();
        URITemplate uriTemplate;
        for (; uriTemplateIterator.hasNext();) {
            uriTemplate = uriTemplateIterator.next();

            prepStmt.setInt(1, apiId);
            prepStmt.setString(2, uriTemplate.getHTTPVerb());
            prepStmt.setString(3, uriTemplate.getAuthType());
            prepStmt.setString(4, uriTemplate.getUriTemplate());
            //If API policy is available then set it for all the resources
            if (StringUtils.isEmpty(api.getApiLevelPolicy())) {
                prepStmt.setString(5, uriTemplate.getThrottlingTier());
            } else {
                prepStmt.setString(5, api.getApiLevelPolicy());
            }
            InputStream is;
            if (uriTemplate.getMediationScript() != null) {
                is = new ByteArrayInputStream(
                        uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()));
            } else {
                is = null;
            }
            if (connection.getMetaData().getDriverName().contains("PostgreSQL")
                    || connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                if (uriTemplate.getMediationScript() != null) {
                    prepStmt.setBinaryStream(6, is,
                            uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()).length);
                } else {
                    prepStmt.setBinaryStream(6, is, 0);
                }
            } else {
                prepStmt.setBinaryStream(6, is);
            }
            prepStmt.addBatch();
            if (uriTemplate.getScope() != null) {
                scopePrepStmt.setString(1, APIUtil.getResourceKey(api, uriTemplate));

                if (uriTemplate.getScope().getId() == 0) {
                    String scopeKey = uriTemplate.getScope().getKey();
                    Scope scopeByKey = APIUtil.findScopeByKey(api.getScopes(), scopeKey);
                    if (scopeByKey != null) {
                        if (scopeByKey.getId() > 0) {
                            uriTemplate.getScopes().setId(scopeByKey.getId());
                        }
                    }
                }

                scopePrepStmt.setInt(2, uriTemplate.getScope().getId());
                scopePrepStmt.addBatch();
            }
        }
        prepStmt.executeBatch();
        prepStmt.clearBatch();
        scopePrepStmt.executeBatch();
        scopePrepStmt.clearBatch();
    } catch (SQLException e) {
        handleException("Error while adding URL template(s) to the database for API : " + api.getId(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, null, null);
        APIMgtDBUtil.closeAllConnections(scopePrepStmt, null, null);
    }
}

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

/**
 * Updates Subscription level policy.//from  w  w  w  .  j av a2s  .c  om
 * <p>policy name and tenant id should be specified in <code>policy</code></p>
 *
 * @param policy updated policy object
 * @throws APIManagementException
 */
public void updateSubscriptionPolicy(SubscriptionPolicy policy) throws APIManagementException {
    Connection connection = null;
    PreparedStatement updateStatement = null;
    boolean hasCustomAttrib = false;
    String updateQuery;

    try {
        if (policy.getCustomAttributes() != null) {
            hasCustomAttrib = true;
        }
        if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
            updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_SQL;
            if (hasCustomAttrib) {
                updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL;
            }
        } else if (!StringUtils.isBlank(policy.getUUID())) {
            updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_BY_UUID_SQL;
            if (hasCustomAttrib) {
                updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL;
            }
        } else {
            String errorMsg = "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id"
                    + " should be provided. Name: " + policy.getPolicyName() + ", Tenant Id: "
                    + policy.getTenantId() + ", UUID: " + policy.getUUID();
            log.error(errorMsg);
            throw new APIManagementException(errorMsg);
        }

        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        updateStatement = connection.prepareStatement(updateQuery);
        if (!StringUtils.isEmpty(policy.getDisplayName())) {
            updateStatement.setString(1, policy.getDisplayName());
        } else {
            updateStatement.setString(1, policy.getPolicyName());
        }
        updateStatement.setString(2, policy.getDescription());
        updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType());

        if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
            RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
            updateStatement.setLong(4, limit.getRequestCount());
            updateStatement.setString(5, null);
        } else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
            BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
            updateStatement.setLong(4, limit.getDataAmount());
            updateStatement.setString(5, limit.getDataUnit());
        }

        updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
        updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
        updateStatement.setInt(8, policy.getRateLimitCount());
        updateStatement.setString(9, policy.getRateLimitTimeUnit());
        updateStatement.setBoolean(10, policy.isStopOnQuotaReach());
        updateStatement.setString(11, policy.getBillingPlan());

        if (hasCustomAttrib) {
            long lengthOfStream = policy.getCustomAttributes().length;
            updateStatement.setBinaryStream(12, new ByteArrayInputStream(policy.getCustomAttributes()),
                    lengthOfStream);
            if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
                updateStatement.setString(13, policy.getPolicyName());
                updateStatement.setInt(14, policy.getTenantId());
            } else if (!StringUtils.isBlank(policy.getUUID())) {
                updateStatement.setString(13, policy.getUUID());
            }
        } else {
            if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
                updateStatement.setString(12, policy.getPolicyName());
                updateStatement.setInt(13, policy.getTenantId());
            } else if (!StringUtils.isBlank(policy.getUUID())) {
                updateStatement.setString(12, policy.getUUID());
            }
        }
        updateStatement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {

                // Rollback failed. Exception will be thrown later for upper exception
                log.error("Failed to rollback the update Subscription Policy: " + policy.toString(), ex);
            }
        }
        handleException(
                "Failed to update subscription policy: " + policy.getPolicyName() + '-' + policy.getTenantId(),
                e);
    } finally {
        APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
    }
}