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.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Inserts the photo identified by the given id. The contact is NOT update.
 * Use deleteContactPhoto to update also the contact.
 * @param con the connection to use//from   w w w  .  ja  v a 2 s.  c o m
 * @param contactId the photo id
 * @param photo the Photo to insert
 * @throws com.funambol.foundation.exception.DAOException if an error
 *         occurs
 */
protected void insertPhoto(Connection con, Long contactId, Photo photo) throws DAOException {

    if (!verifyPermission(con, contactId)) {
        throw new DAOException("Contact '" + contactId + " is not a contact of the user '" + userId + "'");
    }

    PreparedStatement stmt = null;

    if (photo == null) {
        return;
    }
    byte[] image = photo.getImage();

    try {
        stmt = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CONTACT_PHOTO);

        stmt.setLong(1, contactId);

        if (photo.getType() == null) {
            stmt.setNull(2, Types.VARCHAR);
        } else {
            stmt.setString(2, photo.getType());
        }

        if (image == null) {
            stmt.setNull(3, Types.BINARY);
        } else {
            stmt.setBinaryStream(3, new ByteArrayInputStream(image), image.length);
        }

        if (photo.getUrl() == null) {
            stmt.setNull(4, Types.VARCHAR);
        } else {
            stmt.setString(4, photo.getUrl());
        }

        stmt.execute();

    } catch (SQLException ex) {
        throw new DAOException("Error storing photo", ex);
    } finally {
        DBTools.close(null, stmt, null);
    }
}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Updates the given photo for the contact identified by the given id using
 * the given connection./*from w  w  w  .  j a va 2  s. co m*/
 * Note the contact is NOT updated accordlying. Use updateContactPhoto to
 * update also the contact.
 * @param con the connection to use
 * @param id the contact id
 * @param photo the photo to update
 * @return true if the photo has been updated, false
 * @throws com.funambol.foundation.exception.DAOException if an error
 *         occurs
 */
protected boolean updatePhoto(Connection con, Long id, Photo photo) throws DAOException {

    if (!verifyPermission(con, id)) {
        throw new DAOException("Contact '" + id + " is not a contact of the user '" + userId + "'");
    }

    PreparedStatement stmt = null;

    byte[] image = null;
    String type = null;
    String url = null;

    if (photo != null) {
        image = photo.getImage();
        type = photo.getType();
        url = photo.getUrl();
    }

    int numUpdatedRows = 0;
    try {

        stmt = con.prepareStatement(SQL_UPDATE_FNBL_PIM_CONTACT_PHOTO);

        if (type == null) {
            stmt.setNull(1, Types.VARCHAR);
        } else {
            stmt.setString(1, type);
        }

        if (url == null) {
            stmt.setNull(2, Types.VARCHAR);
        } else {
            stmt.setString(2, url);
        }

        if (image == null) {
            stmt.setNull(3, Types.BINARY);
        } else {
            stmt.setBinaryStream(3, new ByteArrayInputStream(image), image.length);
        }

        stmt.setLong(4, id);

        numUpdatedRows = stmt.executeUpdate();

    } catch (SQLException ex) {
        throw new DAOException("Error updating photo", ex);
    } finally {
        DBTools.close(null, stmt, null);
    }
    return (numUpdatedRows == 1);
}

From source file:ffsutils.TaskUtils.java

public static ArrayList<TaskImage> getTaskUpImag(Connection connconn, String tranid1, UserAccount userName,
        String Description, String filetype, FileItem thisfile) throws SQLException {

    String tranid2;//from  w w w .j  a  v a  2  s .com
    Integer comp = 2;
    Integer tranlen = tranid1.length();
    int retval = comp.compareTo(tranlen);
    if (retval > 0) {
        tranid2 = "0" + tranid1;
    } else if (retval < 0) {
        tranid2 = tranid1.substring(tranid1.length() - 2);
    } else {
        tranid2 = tranid1;
    }

    System.out.println(
            "getTaskUpImag " + userName + " size " + String.valueOf(thisfile.getSize()) + " " + tranid2);
    PreparedStatement pstm2 = null;
    FileInputStream fis;

    pstm2 = connconn.prepareStatement("insert into " + userName.getcompany() + ".taskimag" + tranid2
            + " (user, dateup,imagedesc, taskid, imagetype, imag1) values (?, current_timestamp, ? , '"
            + tranid1 + "' ,'" + filetype + "', ?)");
    //PreparedStatement pstm2 = connconn.prepareStatement(sql2);
    OutputStream inputstream = null;
    try {
        inputstream = thisfile.getOutputStream();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    pstm2.setString(1, userName.getUserName());
    pstm2.setString(2, Description);
    //pstm2.setBlob(3,inputstream);
    try {
        pstm2.setBinaryStream(3, thisfile.getInputStream(), (int) thisfile.getSize());
    } catch (IOException e) {
        e.printStackTrace();

    }
    // pstm2.setString(1, tranid1);

    Integer temp1 = pstm2.executeUpdate();

    String sql = "Select * from " + userName.getcompany() + ".taskimag" + tranid2 + " a where a.taskid =?";

    PreparedStatement pstm = connconn.prepareStatement(sql);
    pstm.setString(1, tranid1);

    ResultSet rs = pstm.executeQuery();
    ArrayList<TaskImage> list = new ArrayList<TaskImage>();
    while (rs.next()) {
        String Tranid = rs.getString("tranid");
        String User = rs.getString("user");
        String ImageDesc = rs.getString("imagedesc");
        String ImageType = rs.getString("imagetype");

        Date date = new Date();
        Calendar calendar = new GregorianCalendar();

        calendar.setTime(rs.getTimestamp("dateup"));
        String year = Integer.toString(calendar.get(Calendar.YEAR));
        String month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
        String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
        String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
        String minute = Integer.toString(calendar.get(Calendar.MINUTE));
        int length = month.length();
        if (length == 1) {
            month = "0" + month;
        }
        int length2 = day.length();
        if (length2 == 1) {
            day = "0" + day;
        }
        int length3 = hour.length();
        if (length3 == 1) {
            hour = "0" + hour;
        }
        int length4 = minute.length();
        if (length4 == 1) {
            minute = "0" + minute;
        }
        String thistime = year + "/" + month + "/" + day + " " + hour + ":" + minute;
        String DateUp = thistime;

        TaskImage taskimage = new TaskImage();
        taskimage.setTranid(Tranid);
        taskimage.setUser(User);
        taskimage.setImageDesc(ImageDesc);

        taskimage.setImageType(ImageType);
        taskimage.setDateUp(DateUp);

        list.add(taskimage);
    }
    return list;
}

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

public int[] createContentObject(CopyContext copyContext, Document doc, boolean useOldKey)
        throws VerticalCreateException {

    Element docElem = doc.getDocumentElement();
    Element[] contentobjectElems;
    if ("contentobject".equals(docElem.getTagName())) {
        contentobjectElems = new Element[] { docElem };
    } else {//from ww  w. j  a  v  a 2s  .  c  o m
        contentobjectElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    int pos = 0;
    String tmpStr = null;
    TIntArrayList newKeys = new TIntArrayList();

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(COB_CREATE);

        for (Element root : contentobjectElems) {
            Map subelems = XMLTool.filterElements(root.getChildNodes());

            int key, menuKey = -1;
            String styleSheetKey = "", borderStyleSheetKey = "";

            pos = 0;
            String keyStr = root.getAttribute("key");
            if (!useOldKey || tmpStr == null || tmpStr.length() == 0) {
                key = getNextKey(COB_TABLE);
            } else {
                key = Integer.parseInt(tmpStr);
            }
            if (copyContext != null) {
                copyContext.putContentObjectKey(Integer.parseInt(keyStr), key);
            }
            newKeys.add(key);

            pos++;
            // was sitekey

            pos++;
            tmpStr = root.getAttribute("menukey");
            if (tmpStr != null && tmpStr.length() > 0) {
                menuKey = Integer.parseInt(tmpStr);
            } else {
                String message = "No menu key specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            pos++;
            Element subelem = (Element) subelems.get("objectstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    styleSheetKey = tmpStr;
                } else {
                    String message = "No object stylesheet key specified.";
                    VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No object stylesheet specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            pos++;
            subelem = (Element) subelems.get("borderstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    borderStyleSheetKey = tmpStr;
                }
            }

            String name = null;
            byte[] contentobjectdata;

            // element: name
            subelem = (Element) subelems.get("name");
            if (subelem != null) {
                name = XMLTool.getElementText(subelem);
                if (name == null || name.length() == 0) {
                    String message = "Empty stylesheet name.";
                    VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No stylesheet name specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            // element: contentobjectdata (optional)
            subelem = (Element) subelems.get("contentobjectdata");
            if (subelem != null) {
                Document codDoc = XMLTool.createDocument();
                codDoc.appendChild(codDoc.importNode(subelem, true));
                contentobjectdata = XMLTool.documentToBytes(codDoc, "UTF-8");
            } else {
                contentobjectdata = null;
            }

            preparedStmt.setInt(1, key);
            preparedStmt.setInt(2, menuKey);
            preparedStmt.setString(3, styleSheetKey);
            if (borderStyleSheetKey.length() > 0) {
                preparedStmt.setString(4, borderStyleSheetKey);
            } else {
                preparedStmt.setNull(4, Types.VARCHAR);
            }
            preparedStmt.setString(5, name);
            if (contentobjectdata != null) {
                preparedStmt.setBinaryStream(6, new ByteArrayInputStream(contentobjectdata),
                        contentobjectdata.length);
            } else {
                preparedStmt.setNull(6, Types.VARBINARY);
            }

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

            // create content object
            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to create content object, no content object created.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }
        }

        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "Failed to create content object(s): %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse %0: %1";
        Object[] msgData;
        switch (pos) {
        case 1:
            msgData = new Object[] { "site key", tmpStr };
            break;
        case 2:
            msgData = new Object[] { "menu key", tmpStr };
            break;
        case 3:
            msgData = new Object[] { "object stylesheet key", tmpStr };
            break;
        case 4:
            msgData = new Object[] { "border stylesheet key", tmpStr };
            break;
        default:
            msgData = new Object[] { "content object key", tmpStr };
        }
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, msgData, nfe);
    } catch (VerticalKeyException gke) {
        String message = "Failed to generate content object key";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, gke);
    } finally {
        close(preparedStmt);
        close(con);
    }

    return newKeys.toArray();
}

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

public void updateContentObject(Document doc) throws VerticalUpdateException {
    Element docElem = doc.getDocumentElement();
    Element[] contentobjectElems;
    if ("contentobject".equals(docElem.getTagName())) {
        contentobjectElems = new Element[] { docElem };
    } else {//from w ww.j av  a2  s.  co m
        contentobjectElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    int pos = 0;
    String tmpStr = null;

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(COB_UPDATE);

        for (Element root : contentobjectElems) {
            Map subelems = XMLTool.filterElements(root.getChildNodes());

            int key = -1, menuKey = -1;
            ResourceKey styleSheetKey = null, borderStyleSheetKey = null;

            pos = 0;
            tmpStr = root.getAttribute("key");
            if (tmpStr != null && tmpStr.length() > 0) {
                key = Integer.parseInt(tmpStr);
            } else {
                String message = "No content object key specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            // was sitekey

            pos++;
            tmpStr = root.getAttribute("menukey");
            if (tmpStr != null && tmpStr.length() > 0) {
                menuKey = Integer.parseInt(tmpStr);
            } else {
                String message = "No menu key specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            Element subelem = (Element) subelems.get("objectstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    styleSheetKey = new ResourceKey(tmpStr);
                } else {
                    String message = "No object stylesheet key specified.";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No object stylesheet specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            subelem = (Element) subelems.get("borderstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    borderStyleSheetKey = new ResourceKey(tmpStr);
                }
            }

            // element: name
            String name = null;
            subelem = (Element) subelems.get("name");
            if (subelem != null) {
                name = XMLTool.getElementText(subelem);
                if (name == null || name.length() == 0) {
                    String message = "Empty stylesheet name.";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No stylesheet name specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            // element: contentobjectdata (optional)
            byte[] contentobjectdata;
            subelem = (Element) subelems.get("contentobjectdata");
            if (subelem != null) {
                Document codDoc = XMLTool.createDocument();
                codDoc.appendChild(codDoc.importNode(subelem, true));
                contentobjectdata = XMLTool.documentToBytes(codDoc, "UTF-8");
            } else {
                contentobjectdata = null;
            }

            preparedStmt.setInt(7, key);
            preparedStmt.setInt(1, menuKey);
            if (styleSheetKey != null) {
                preparedStmt.setString(2, styleSheetKey.toString());
            } else {
                preparedStmt.setNull(2, Types.VARCHAR);
            }
            if (borderStyleSheetKey != null) {
                preparedStmt.setString(3, borderStyleSheetKey.toString());
            } else {
                preparedStmt.setNull(3, Types.VARCHAR);
            }
            preparedStmt.setCharacterStream(4, new StringReader(name), name.length());
            if (contentobjectdata != null) {
                preparedStmt.setBinaryStream(5, new ByteArrayInputStream(contentobjectdata),
                        contentobjectdata.length);
            } else {
                preparedStmt.setNull(5, Types.VARCHAR);
            }

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

            // update content object
            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to update content object, no content object updated.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }
        }

        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "Failed to update content object(s): %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse %0: %1";
        Object[] msgData;
        switch (pos) {
        case 1:
            msgData = new Object[] { "site key", tmpStr };
            break;
        case 2:
            msgData = new Object[] { "menu key", tmpStr };
            break;
        case 3:
            msgData = new Object[] { "object stylesheet key", tmpStr };
            break;
        case 4:
            msgData = new Object[] { "border stylesheet key", tmpStr };
            break;
        default:
            msgData = new Object[] { "content object key", tmpStr };
        }
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, msgData, nfe);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

From source file:org.opencms.db.generic.CmsVfsDriver.java

/**
 * @see org.opencms.db.I_CmsVfsDriver#createOnlineContent(org.opencms.db.CmsDbContext, org.opencms.util.CmsUUID, byte[], int, boolean, boolean)
 */// ww w  .j a  v a  2 s  . com
public void createOnlineContent(CmsDbContext dbc, CmsUUID resourceId, byte[] contents, int publishTag,
        boolean keepOnline, boolean needToUpdateContent) throws CmsDataAccessException {

    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = m_sqlManager.getConnection(dbc);
        boolean dbcHasProjectId = (dbc.getProjectId() != null) && !dbc.getProjectId().isNullUUID();

        if (needToUpdateContent || dbcHasProjectId) {
            if (dbcHasProjectId || !OpenCms.getSystemInfo().isHistoryEnabled()) {
                // remove the online content for this resource id
                stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_DELETE");
                stmt.setString(1, resourceId.toString());
                stmt.executeUpdate();
                m_sqlManager.closeAll(dbc, null, stmt, null);
            } else {
                // put the online content in the history, only if explicit requested
                stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_HISTORY");
                stmt.setString(1, resourceId.toString());
                stmt.executeUpdate();
                m_sqlManager.closeAll(dbc, null, stmt, null);
            }

            // create new online content
            stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_WRITE");

            stmt.setString(1, resourceId.toString());
            if (contents.length < 2000) {
                stmt.setBytes(2, contents);
            } else {
                stmt.setBinaryStream(2, new ByteArrayInputStream(contents), contents.length);
            }
            stmt.setInt(3, publishTag);
            stmt.setInt(4, publishTag);
            stmt.setInt(5, keepOnline ? 1 : 0);
            stmt.executeUpdate();
            m_sqlManager.closeAll(dbc, null, stmt, null);
        } else {
            // update old content entry
            stmt = m_sqlManager.getPreparedStatement(conn, "C_HISTORY_CONTENTS_UPDATE");
            stmt.setInt(1, publishTag);
            stmt.setString(2, resourceId.toString());
            stmt.executeUpdate();
            m_sqlManager.closeAll(dbc, null, stmt, null);

            if (!keepOnline) {
                // put the online content in the history 
                stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_HISTORY");
                stmt.setString(1, resourceId.toString());
                stmt.executeUpdate();
                m_sqlManager.closeAll(dbc, null, stmt, null);
            }
        }
    } catch (SQLException e) {
        throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e);
    } finally {
        m_sqlManager.closeAll(dbc, conn, stmt, null);
    }
}

From source file:org.moqui.impl.entity.EntityJavaUtil.java

public static void setPreparedStatementValue(PreparedStatement ps, int index, Object value, FieldInfo fi,
        boolean useBinaryTypeForBlob, EntityFacade efi) throws EntityException {
    try {//w w w  .j  a v  a 2s  . c  o  m
        // allow setting, and searching for, String values for all types; JDBC driver should handle this okay
        if (value instanceof CharSequence) {
            ps.setString(index, value.toString());
        } else {
            switch (fi.typeValue) {
            case 1:
                if (value != null) {
                    ps.setString(index, value.toString());
                } else {
                    ps.setNull(index, Types.VARCHAR);
                }
                break;
            case 2:
                if (value != null) {
                    Class valClass = value.getClass();
                    if (valClass == Timestamp.class) {
                        ps.setTimestamp(index, (Timestamp) value, efi.getCalendarForTzLc());
                    } else if (valClass == java.sql.Date.class) {
                        ps.setDate(index, (java.sql.Date) value, efi.getCalendarForTzLc());
                    } else if (valClass == java.util.Date.class) {
                        ps.setTimestamp(index, new Timestamp(((java.util.Date) value).getTime()),
                                efi.getCalendarForTzLc());
                    } else {
                        throw new IllegalArgumentException("Class " + valClass.getName()
                                + " not allowed for date-time (Timestamp) fields, for field " + fi.entityName
                                + "." + fi.name);
                    }
                } else {
                    ps.setNull(index, Types.TIMESTAMP);
                }
                break;
            case 3:
                Time tm = (Time) value;
                // logger.warn("=================== setting time tm=${tm} tm long=${tm.getTime()}, cal=${cal}")
                if (value != null) {
                    ps.setTime(index, tm, efi.getCalendarForTzLc());
                } else {
                    ps.setNull(index, Types.TIME);
                }
                break;
            case 4:
                if (value != null) {
                    Class valClass = value.getClass();
                    if (valClass == java.sql.Date.class) {
                        java.sql.Date dt = (java.sql.Date) value;
                        // logger.warn("=================== setting date dt=${dt} dt long=${dt.getTime()}, cal=${cal}")
                        ps.setDate(index, dt, efi.getCalendarForTzLc());
                    } else if (valClass == Timestamp.class) {
                        ps.setDate(index, new java.sql.Date(((Timestamp) value).getTime()),
                                efi.getCalendarForTzLc());
                    } else if (valClass == java.util.Date.class) {
                        ps.setDate(index, new java.sql.Date(((java.util.Date) value).getTime()),
                                efi.getCalendarForTzLc());
                    } else {
                        throw new IllegalArgumentException("Class " + valClass.getName()
                                + " not allowed for date fields, for field " + fi.entityName + "." + fi.name);
                    }
                } else {
                    ps.setNull(index, Types.DATE);
                }
                break;
            case 5:
                if (value != null) {
                    ps.setInt(index, ((Number) value).intValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 6:
                if (value != null) {
                    ps.setLong(index, ((Number) value).longValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 7:
                if (value != null) {
                    ps.setFloat(index, ((Number) value).floatValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 8:
                if (value != null) {
                    ps.setDouble(index, ((Number) value).doubleValue());
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 9:
                if (value != null) {
                    Class valClass = value.getClass();
                    // most common cases BigDecimal, Double, Float; then allow any Number
                    if (valClass == BigDecimal.class) {
                        ps.setBigDecimal(index, (BigDecimal) value);
                    } else if (valClass == Double.class) {
                        ps.setDouble(index, (Double) value);
                    } else if (valClass == Float.class) {
                        ps.setFloat(index, (Float) value);
                    } else if (value instanceof Number) {
                        ps.setDouble(index, ((Number) value).doubleValue());
                    } else {
                        throw new IllegalArgumentException("Class " + valClass.getName()
                                + " not allowed for number-decimal (BigDecimal) fields, for field "
                                + fi.entityName + "." + fi.name);
                    }
                } else {
                    ps.setNull(index, Types.NUMERIC);
                }
                break;
            case 10:
                if (value != null) {
                    ps.setBoolean(index, (Boolean) value);
                } else {
                    ps.setNull(index, Types.BOOLEAN);
                }
                break;
            case 11:
                if (value != null) {
                    try {
                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(os);
                        oos.writeObject(value);
                        oos.close();
                        byte[] buf = os.toByteArray();
                        os.close();

                        ByteArrayInputStream is = new ByteArrayInputStream(buf);
                        ps.setBinaryStream(index, is, buf.length);
                        is.close();
                    } catch (IOException ex) {
                        throw new EntityException(
                                "Error setting serialized object, for field " + fi.entityName + "." + fi.name,
                                ex);
                    }
                } else {
                    if (useBinaryTypeForBlob) {
                        ps.setNull(index, Types.BINARY);
                    } else {
                        ps.setNull(index, Types.BLOB);
                    }
                }
                break;
            case 12:
                if (value instanceof byte[]) {
                    ps.setBytes(index, (byte[]) value);
                    /*
                    } else if (value instanceof ArrayList) {
                        ArrayList valueAl = (ArrayList) value;
                        byte[] theBytes = new byte[valueAl.size()];
                        valueAl.toArray(theBytes);
                        ps.setBytes(index, theBytes);
                    */
                } else if (value instanceof ByteBuffer) {
                    ByteBuffer valueBb = (ByteBuffer) value;
                    ps.setBytes(index, valueBb.array());
                } else if (value instanceof Blob) {
                    Blob valueBlob = (Blob) value;
                    // calling setBytes instead of setBlob
                    // ps.setBlob(index, (Blob) value)
                    // Blob blb = value
                    ps.setBytes(index, valueBlob.getBytes(1, (int) valueBlob.length()));
                } else {
                    if (value != null) {
                        throw new IllegalArgumentException("Type not supported for BLOB field: "
                                + value.getClass().getName() + ", for field " + fi.entityName + "." + fi.name);
                    } else {
                        if (useBinaryTypeForBlob) {
                            ps.setNull(index, Types.BINARY);
                        } else {
                            ps.setNull(index, Types.BLOB);
                        }
                    }
                }
                break;
            case 13:
                if (value != null) {
                    ps.setClob(index, (Clob) value);
                } else {
                    ps.setNull(index, Types.CLOB);
                }
                break;
            case 14:
                if (value != null) {
                    ps.setTimestamp(index, (Timestamp) value);
                } else {
                    ps.setNull(index, Types.TIMESTAMP);
                }
                break;
            // TODO: is this the best way to do collections and such?
            case 15:
                if (value != null) {
                    ps.setObject(index, value, Types.JAVA_OBJECT);
                } else {
                    ps.setNull(index, Types.JAVA_OBJECT);
                }
                break;
            }
        }
    } catch (SQLException sqle) {
        throw new EntityException("SQL Exception while setting value [" + value + "]("
                + (value != null ? value.getClass().getName() : "null") + "), type " + fi.type + ", for field "
                + fi.entityName + "." + fi.name + ": " + sqle.toString(), sqle);
    } catch (Exception e) {
        throw new EntityException(
                "Error while setting value for field " + fi.entityName + "." + fi.name + ": " + e.toString(),
                e);
    }
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import data from a zip archive to a database table
 *
 * @param stmt               statement to use
 * @param zip                zip archive containing the zip entry
 * @param ze                 zip entry within the archive
 * @param xpath              xpath containing the entries to import
 * @param table              name of the table
 * @param executeInsertPhase execute the insert phase?
 * @param executeUpdatePhase execute the update phase?
 * @param updateColumns      columns that should be set to <code>null</code> in a first pass (insert)
 *                           and updated to the provided values in a second pass (update),
 *                           columns that should be used in the where clause have to be prefixed
 *                           with "KEY:", to assign a default value use the expression "columnname:default value",
 *                           if the default value is "@", it will be a negative counter starting at 0, decreasing.
 *                           If the default value starts with "%", it will be set to the column following the "%"
 *                           character in the first pass
 * @throws Exception on errors/*from   www .  j a v a 2 s  . c  om*/
 */
protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath,
        final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase,
        final String... updateColumns) throws Exception {
    //analyze the table
    final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2");
    StringBuilder sbInsert = new StringBuilder(500);
    StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null;
    if (rs == null)
        throw new IllegalArgumentException("Can not analyze table [" + table + "]!");
    sbInsert.append("INSERT INTO ").append(table).append(" (");
    final ResultSetMetaData md = rs.getMetaData();
    final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0
            ? new HashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0
            ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null;
    //preset to a referenced column (%column syntax)
    final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10)
            : null;
    final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null;
    final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>(
            md.getColumnCount() + (counters != null ? counters.size() : 0));
    int insertIndex = 1;
    int updateSetIndex = 1;
    int updateClauseIndex = 1;
    boolean first = true;
    for (int i = 0; i < md.getColumnCount(); i++) {
        final String currCol = md.getColumnName(i + 1).toLowerCase();
        if (updateColumns.length > 0) {
            boolean abort = false;
            for (String col : updateColumns) {
                if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) {
                    String value = col.substring(col.indexOf(':') + 1);
                    col = col.substring(0, col.indexOf(':'));
                    if ("@".equals(value)) {
                        if (currCol.equalsIgnoreCase(col)) {
                            counters.put(col, 0);
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                        }
                    } else if (value.startsWith("%")) {
                        if (currCol.equalsIgnoreCase(col)) {
                            presetRefColumns.put(col, value.substring(1));
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                            //                                System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1));
                        }
                    } else if (!presetColumns.containsKey(col))
                        presetColumns.put(col, value);
                }
                if (currCol.equalsIgnoreCase(col)) {
                    abort = true;
                    updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++));
                    break;
                }
            }
            if (abort)
                continue;
        }
        if (first) {
            first = false;
        } else
            sbInsert.append(',');
        sbInsert.append(currCol);
        insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
    }
    if (updateColumns.length > 0 && executeUpdatePhase) {
        sbUpdate.append("UPDATE ").append(table).append(" SET ");
        int counter = 0;
        for (String updateColumn : updateSetColumns.keySet()) {
            if (counter++ > 0)
                sbUpdate.append(',');
            sbUpdate.append(updateColumn).append("=?");
        }
        sbUpdate.append(" WHERE ");
        boolean hasKeyColumn = false;
        for (String col : updateColumns) {
            if (!col.startsWith("KEY:"))
                continue;
            hasKeyColumn = true;
            String keyCol = col.substring(4);
            for (int i = 0; i < md.getColumnCount(); i++) {
                if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol))
                    continue;
                updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++));
                sbUpdate.append(keyCol).append("=? AND ");
                break;
            }

        }
        if (!hasKeyColumn)
            throw new IllegalArgumentException("Update columns require a KEY!");
        sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND "
        //"shift" clause indices
        for (String col : updateClauseColumns.keySet()) {
            GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col);
            ci.index += (updateSetIndex - 1);
        }
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(key);
    }
    sbInsert.append(")VALUES(");
    for (int i = 0; i < insertColumns.size(); i++) {
        if (i > 0)
            sbInsert.append(',');
        sbInsert.append('?');
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(presetColumns.get(key));
    }
    sbInsert.append(')');
    if (DBG) {
        LOG.info("Insert statement:\n" + sbInsert.toString());
        if (updateColumns.length > 0)
            LOG.info("Update statement:\n" + sbUpdate.toString());
    }
    //build a map containing all nodes that require attributes
    //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data"
    final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5);
    for (String pElem : xpath.split("/")) {
        if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0))
            continue;
        List<String> att = new ArrayList<String>(5);
        for (String pAtt : pElem.split("@")) {
            if (!(pAtt.indexOf('=') > 0))
                continue;
            att.add(pAtt.substring(0, pAtt.indexOf('=')));
        }
        queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att);
    }
    final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString());
    final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase
            ? stmt.getConnection().prepareStatement(sbUpdate.toString())
            : null;
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            int counter;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            boolean insertMode = true;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                counter = 0;
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void processingInstruction(String target, String data) throws SAXException {
                if (target != null && target.startsWith("fx_")) {
                    if (target.equals("fx_mode"))
                        insertMode = "insert".equals(data);
                } else
                    super.processingInstruction(target, data);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                if (insertMode)
                    LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath
                            + "]");
                else
                    LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpath)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            private void pushPath(String qName, Attributes att) {
                if (att.getLength() > 0 && queryAttributes.containsKey(qName)) {
                    String curr = qName + "[";
                    boolean first = true;
                    final List<String> attList = queryAttributes.get(qName);
                    for (int i = 0; i < att.getLength(); i++) {
                        if (!attList.contains(att.getQName(i)))
                            continue;
                        if (first)
                            first = false;
                        else
                            curr += ',';
                        curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'";
                    }
                    curr += ']';
                    path.add(curr);
                } else
                    path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpath)) {
                    if (DBG)
                        LOG.info("Insert [" + xpath + "]: [" + data + "]");
                    inTag = false;
                    try {
                        if (insertMode) {
                            if (executeInsertPhase) {
                                processColumnSet(insertColumns, psInsert);
                                counter += psInsert.executeUpdate();
                            }
                        } else {
                            if (executeUpdatePhase) {
                                if (processColumnSet(updateSetColumns, psUpdate)) {
                                    processColumnSet(updateClauseColumns, psUpdate);
                                    counter += psUpdate.executeUpdate();
                                }
                            }
                        }
                    } catch (SQLException e) {
                        throw new SAXException(e);
                    } catch (ParseException e) {
                        throw new SAXException(e);
                    }
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            /**
             * Process a column set
             *
             * @param columns the columns to process
             * @param ps prepared statement to use
             * @return if data other than <code>null</code> has been set
             * @throws SQLException on errors
             * @throws ParseException on date/time conversion errors
             */
            private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps)
                    throws SQLException, ParseException {
                boolean dataSet = false;
                for (String col : columns.keySet()) {
                    ColumnInfo ci = columns.get(col);
                    String value = data.get(col);
                    if (insertMode && counters != null && counters.get(col) != null) {
                        final int newVal = counters.get(col) - 1;
                        value = String.valueOf(newVal);
                        counters.put(col, newVal);
                        //                            System.out.println("new value for " + col + ": " + newVal);
                    }
                    if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) {
                        value = data.get(presetRefColumns.get(col));
                        //                            System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]");
                    }

                    if (value == null)
                        ps.setNull(ci.index, ci.columnType);
                    else {
                        dataSet = true;
                        switch (ci.columnType) {
                        case Types.BIGINT:
                        case Types.NUMERIC:
                            if (DBG)
                                LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value));
                            ps.setBigDecimal(ci.index, new BigDecimal(value));
                            break;
                        case java.sql.Types.DOUBLE:
                            if (DBG)
                                LOG.info("Double " + ci.index + "->" + Double.parseDouble(value));
                            ps.setDouble(ci.index, Double.parseDouble(value));
                            break;
                        case java.sql.Types.FLOAT:
                        case java.sql.Types.REAL:
                            if (DBG)
                                LOG.info("Float " + ci.index + "->" + Float.parseFloat(value));
                            ps.setFloat(ci.index, Float.parseFloat(value));
                            break;
                        case java.sql.Types.TIMESTAMP:
                        case java.sql.Types.DATE:
                            if (DBG)
                                LOG.info("Timestamp/Date " + ci.index + "->"
                                        + FxFormatUtils.getDateTimeFormat().parse(value));
                            ps.setTimestamp(ci.index,
                                    new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime()));
                            break;
                        case Types.TINYINT:
                        case Types.SMALLINT:
                            if (DBG)
                                LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value));
                            ps.setInt(ci.index, Integer.valueOf(value));
                            break;
                        case Types.INTEGER:
                        case Types.DECIMAL:
                            try {
                                if (DBG)
                                    LOG.info("Long " + ci.index + "->" + Long.valueOf(value));
                                ps.setLong(ci.index, Long.valueOf(value));
                            } catch (NumberFormatException e) {
                                //Fallback (temporary) for H2 if the reported long is a big decimal (tree...)
                                ps.setBigDecimal(ci.index, new BigDecimal(value));
                            }
                            break;
                        case Types.BIT:
                        case Types.CHAR:
                        case Types.BOOLEAN:
                            if (DBG)
                                LOG.info("Boolean " + ci.index + "->" + value);
                            if ("1".equals(value) || "true".equals(value))
                                ps.setBoolean(ci.index, true);
                            else
                                ps.setBoolean(ci.index, false);
                            break;
                        case Types.LONGVARBINARY:
                        case Types.VARBINARY:
                        case Types.BLOB:
                        case Types.BINARY:
                            ZipEntry bin = zip.getEntry(value);
                            if (bin == null) {
                                LOG.error("Failed to lookup binary [" + value + "]!");
                                ps.setNull(ci.index, ci.columnType);
                                break;
                            }
                            try {
                                ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize());
                            } catch (IOException e) {
                                LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e);
                            }
                            break;
                        case Types.CLOB:
                        case Types.LONGVARCHAR:
                        case Types.VARCHAR:
                        case SQL_LONGNVARCHAR:
                        case SQL_NCHAR:
                        case SQL_NCLOB:
                        case SQL_NVARCHAR:
                            if (DBG)
                                LOG.info("String " + ci.index + "->" + value);
                            ps.setString(ci.index, value);
                            break;
                        default:
                            LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]");
                        }
                    }
                }
                return dataSet;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        handler.processingInstruction("fx_mode", "insert");
        parser.parse(zip.getInputStream(ze), handler);
        if (updateColumns.length > 0 && executeUpdatePhase) {
            handler.processingInstruction("fx_mode", "update");
            parser.parse(zip.getInputStream(ze), handler);
        }
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate);
    }
}

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

public void updateMenuData(Document doc) throws VerticalUpdateException, VerticalSecurityException {
    Element root_elem = doc.getDocumentElement();

    // get menu key:
    String tmp = root_elem.getAttribute("key");
    int menuKey = Integer.parseInt(tmp);

    Connection con = null;// ww  w  .j  a v a  2  s.c  o m
    PreparedStatement preparedStmt = null;
    try {
        con = getConnection();

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

        // name:
        Element tmpElement = XMLTool.getElement(root_elem, "name");
        String name = null;
        if (tmpElement != null) {
            name = XMLTool.getElementText(tmpElement);
        }
        if (name != null && name.length() > 0) {
            StringReader sreader = new StringReader(name);
            preparedStmt.setCharacterStream(1, sreader, name.length());
        } else {
            preparedStmt.setNull(1, Types.VARCHAR);
        }

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

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

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

        SiteData siteData = new SiteData();

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

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

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

        // Path to public home:
        String pathToPublicHome = root_elem.getAttribute("pathtopublichome");
        if (pathToPublicHome != null && pathToPublicHome.length() > 0) {
            siteData.setPathToPublicResources(new ResourceKey(pathToPublicHome));
        }

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

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

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

        // Run As User:
        String runAsUserGroupKey = root_elem.getAttribute("runas");
        if (runAsUserGroupKey != null && runAsUserGroupKey.length() > 0) {
            UserKey userKey = getUserKeyFromGroupKey(runAsUserGroupKey);
            preparedStmt.setString(5, userKey != null ? userKey.toString() : null);
        } else {
            preparedStmt.setNull(5, Types.VARCHAR);
        }

        // menu key:
        preparedStmt.setInt(6, menuKey);
        preparedStmt.executeUpdate();
        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "SQL error: %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, sqle);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

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

private int createMenuItem(User user, CopyContext copyContext, Element menuItemElement, SiteKey siteKey,
        int order, MenuItemKey parentKey, boolean useOldKey)
        throws VerticalCreateException, VerticalSecurityException {

    // security check:
    if (!getSecurityHandler().validateMenuItemCreate(user, siteKey.toInt(),
            parentKey == null ? -1 : parentKey.toInt())) {
        VerticalEngineLogger.errorSecurity(this.getClass(), 10,
                "Not allowed to create menuitem in this position.", null);
    }/*from  w w  w .  j a v  a 2  s . c  om*/

    String menuItemName = XMLTool
            .getElementText(XMLTool.getElement(menuItemElement, ELEMENT_NAME_MENUITEM_NAME));

    if (StringUtils.isEmpty(menuItemName)) {
        menuItemName = generateMenuItemName(menuItemElement);
    }

    menuItemName = ensureUniqueMenuItemName(siteKey, parentKey, menuItemName, null);

    // check whether name is unique for this parent
    if (menuItemNameExists(siteKey, parentKey, menuItemName, null)) {
        VerticalEngineLogger.errorCreate(this.getClass(), 20, "Menu item name already exists on this level: %0",
                new Object[] { menuItemName }, null);
    }

    Element tmp_element;
    Hashtable<String, Integer> menuItemTypes = getMenuItemTypesAsHashtable();

    // Get menuitem type:
    String miType = menuItemElement.getAttribute("type");
    Integer type = menuItemTypes.get(miType);
    if (type == null) {
        VerticalEngineLogger.errorCreate(this.getClass(), 20, "Invalid menu item type %0.",
                new Object[] { type }, null);
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    MenuItemKey menuItemKey = null;

    try {
        con = getConnection();

        // key
        String keyStr = menuItemElement.getAttribute("key");
        if (!useOldKey || keyStr == null || keyStr.length() == 0) {
            try {
                menuItemKey = new MenuItemKey(getNextKey(MENU_ITEM_TABLE));
            } catch (VerticalKeyException e) {
                VerticalEngineLogger.errorCreate(this.getClass(), 30, "Error generating key for tMenuItem.", e);
            }
        } else {
            menuItemKey = new MenuItemKey(keyStr);
        }
        if (copyContext != null) {
            copyContext.putMenuItemKey(Integer.parseInt(keyStr), menuItemKey.toInt());
        }

        String tmp;

        preparedStmt = con.prepareStatement(MENU_ITEM_INSERT);

        preparedStmt.setInt(1, menuItemKey.toInt());

        // element: name
        validateMenuItemName(menuItemName);
        preparedStmt.setString(2, menuItemName);

        // menu key:
        preparedStmt.setInt(3, siteKey.toInt());

        // attribute: menu item type
        preparedStmt.setInt(4, type);

        // parent
        if (parentKey == null) {
            preparedStmt.setNull(5, Types.INTEGER);
        } else {
            preparedStmt.setInt(5, parentKey.toInt());
        }

        // order:
        preparedStmt.setInt(6, order);

        // pre-fetch data element
        Element dataElem = XMLTool.getElement(menuItemElement, "data");

        // element: parameters
        tmp_element = XMLTool.getElement(menuItemElement, "parameters");
        if (tmp_element != null) {
            dataElem.appendChild(tmp_element);
        }

        // alternative name:
        tmp_element = XMLTool.getElement(menuItemElement, ELEMENT_NAME_MENU_NAME);
        if (tmp_element != null) {
            tmp = XMLTool.getElementText(tmp_element);
            preparedStmt.setString(7, tmp);
        } else {
            preparedStmt.setNull(7, Types.VARCHAR);
        }

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

        // description:
        tmp_element = XMLTool.getElement(menuItemElement, "description");
        String data = XMLTool.getElementText(tmp_element);
        if (data != null) {
            StringReader reader = new StringReader(data);
            preparedStmt.setCharacterStream(9, reader, data.length());
        } else {
            preparedStmt.setNull(9, Types.VARCHAR);
        }

        if (type == 4) {
            Element docElem = XMLTool.getElement(menuItemElement, "document");

            if (docElem != null) {
                dataElem.appendChild(docElem);
            }
        }

        // attribute: owner/modifier
        String ownerKey = menuItemElement.getAttribute("owner");
        preparedStmt.setString(10, ownerKey);
        preparedStmt.setString(11, ownerKey);

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

            byte[] bytes = XMLTool.documentToBytes(dataDoc, "UTF-8");
            preparedStmt.setBinaryStream(12, new ByteArrayInputStream(bytes), bytes.length);
        } else {
            preparedStmt.setNull(12, Types.BLOB);
        }

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

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

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

        // Display-name
        String displayName = getElementValue(menuItemElement, ELEMENT_NAME_DISPLAY_NAME);
        preparedStmt.setString(16, displayName);

        // execute statement:
        preparedStmt.executeUpdate();

        // Create type specific data.
        switch (type) {
        case 1:
            // page
            createPage(con, menuItemElement, type, menuItemKey);
            break;

        case 2:
            // URL
            createOrUpdateURL(con, menuItemElement, menuItemKey);
            break;

        case 4:
            // document: nothing
            // page
            Element pageElem = XMLTool.getElement(menuItemElement, "page");
            PageTemplateKey pageTemplateKey = new PageTemplateKey(pageElem.getAttribute("pagetemplatekey"));
            PageTemplateType pageTemplateType = getPageTemplateHandler().getPageTemplateType(pageTemplateKey);
            if (pageTemplateType == PageTemplateType.SECTIONPAGE
                    || pageTemplateType == PageTemplateType.NEWSLETTER) {
                createSection(menuItemElement, menuItemKey);
            }
            createPage(con, menuItemElement, type, menuItemKey);
            break;

        case 5:
            // label
            break;

        case 6:
            // section
            createSection(menuItemElement, menuItemKey);
            break;

        case 7:
            // shortcut
            createOrOverrideShortcut(menuItemElement, menuItemKey);
            break;

        default:
            VerticalEngineLogger.errorCreate(this.getClass(), 70, "Unknown menuitem type: %0",
                    new Object[] { type }, null);
        }

        // set contentkey if present
        String contentKeyStr = menuItemElement.getAttribute("contentkey");
        if (contentKeyStr.length() == 0) {
            contentKeyStr = "-1";
        }
        setMenuItemContentKey(menuItemKey, Integer.parseInt(contentKeyStr));

        // fire event
        if (multicaster.hasListeners() && copyContext == null) {
            MenuHandlerEvent e = new MenuHandlerEvent(user, siteKey.toInt(), menuItemKey.toInt(), menuItemName,
                    this);
            multicaster.createdMenuItem(e);
        }

        UserSpecification userSpecification = new UserSpecification();
        userSpecification.setDeletedState(UserSpecification.DeletedState.ANY);
        userSpecification.setKey(new UserKey(ownerKey));
        UserEntity owner = userDao.findSingleBySpecification(userSpecification);
        String ownerGroupKey = null;
        if (owner.getUserGroup() != null) {
            ownerGroupKey = owner.getUserGroup().getGroupKey().toString();
        }

        getSecurityHandler().inheritMenuItemAccessRights(siteKey.toInt(),
                parentKey == null ? -1 : parentKey.toInt(), menuItemKey.toInt(), ownerGroupKey);

        // Create other
        Element menuItemsElement = XMLTool.getElement(menuItemElement, "menuitems");
        if (menuItemsElement != null) {
            Element[] elems = XMLTool.getElements(menuItemsElement);
            for (int i = 0; i < elems.length; i++) {
                createMenuItem(user, copyContext, elems[i], siteKey, i, menuItemKey, useOldKey);
            }
        }
    } catch (SQLException e) {
        VerticalEngineLogger.errorCreate(this.getClass(), 40, "A database error occurred: %t", e);
    } finally {
        close(preparedStmt);
        close(con);
    }

    return menuItemKey.toInt();
}