List of usage examples for java.sql PreparedStatement setBinaryStream
void setBinaryStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException;
From source file:org.quartz.impl.jdbcjobstore.StdJDBCDelegate.java
/** * <p>/*www . j a v a 2 s .co m*/ * Update the blob trigger data. * </p> * * @param conn * the DB Connection * @param trigger * the trigger to insert * @return the number of rows updated */ public int updateBlobTrigger(Connection conn, Trigger trigger) throws SQLException, IOException { PreparedStatement ps = null; ByteArrayOutputStream os = null; try { // update the blob os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(trigger); oos.close(); byte[] buf = os.toByteArray(); ByteArrayInputStream is = new ByteArrayInputStream(buf); ps = conn.prepareStatement(rtp(UPDATE_BLOB_TRIGGER)); ps.setBinaryStream(1, is, buf.length); ps.setString(2, trigger.getName()); ps.setString(3, trigger.getGroup()); return ps.executeUpdate(); } finally { closeStatement(ps); if (os != null) { os.close(); } } }
From source file:org.quartz.impl.jdbcjobstore.StdJDBCDelegate.java
/** * <p>/*from ww w. j a v a2 s . c o m*/ * Insert the blob trigger data. * </p> * * @param conn * the DB Connection * @param trigger * the trigger to insert * @return the number of rows inserted */ public int insertBlobTrigger(Connection conn, Trigger trigger) throws SQLException, IOException { PreparedStatement ps = null; ByteArrayOutputStream os = null; try { // update the blob os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(trigger); oos.close(); byte[] buf = os.toByteArray(); ByteArrayInputStream is = new ByteArrayInputStream(buf); ps = conn.prepareStatement(rtp(INSERT_BLOB_TRIGGER)); ps.setString(1, trigger.getName()); ps.setString(2, trigger.getGroup()); ps.setBinaryStream(3, is, buf.length); return ps.executeUpdate(); } finally { closeStatement(ps); } }
From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java
protected void applyParameters(PreparedStatement statement, ParameterValueList parameters) throws SQLException, SenderException { // statement.clearParameters(); /*// w w w . j a v a2s . c o m // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation. int senderParameterCount = parameters.size(); int statementParameterCount = statement.getParameterMetaData().getParameterCount(); if (statementParameterCount<senderParameterCount) { throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]"); } */ for (int i = 0; i < parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); Object value = pv.getValue(); // log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]"); if (Parameter.TYPE_DATE.equals(paramType)) { if (value == null) { statement.setNull(i + 1, Types.DATE); } else { statement.setDate(i + 1, new java.sql.Date(((Date) value).getTime())); } } else if (Parameter.TYPE_DATETIME.equals(paramType)) { if (value == null) { statement.setNull(i + 1, Types.TIMESTAMP); } else { statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime())); } } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) { if (value == null) { statement.setNull(i + 1, Types.TIMESTAMP); } else { statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime())); } } else if (Parameter.TYPE_TIME.equals(paramType)) { if (value == null) { statement.setNull(i + 1, Types.TIME); } else { statement.setTime(i + 1, new java.sql.Time(((Date) value).getTime())); } } else if (Parameter.TYPE_XMLDATETIME.equals(paramType)) { if (value == null) { statement.setNull(i + 1, Types.TIMESTAMP); } else { statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime())); } } else if (Parameter.TYPE_NUMBER.equals(paramType)) { if (value == null) { statement.setNull(i + 1, Types.NUMERIC); } else { statement.setDouble(i + 1, ((Number) value).doubleValue()); } } else if (Parameter.TYPE_INTEGER.equals(paramType)) { if (value == null) { statement.setNull(i + 1, Types.INTEGER); } else { statement.setInt(i + 1, (Integer) value); } } else if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) { if (value instanceof FileInputStream) { FileInputStream fis = (FileInputStream) value; long len = 0; try { len = fis.getChannel().size(); } catch (IOException e) { log.warn(getLogPrefix() + "could not determine file size", e); } statement.setBinaryStream(i + 1, fis, (int) len); } else if (value instanceof ByteArrayInputStream) { ByteArrayInputStream bais = (ByteArrayInputStream) value; long len = bais.available(); statement.setBinaryStream(i + 1, bais, (int) len); } else { throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass() + "] for parameter [" + pv.getDefinition().getName() + "]"); } } else if ("string2bytes".equals(paramType)) { statement.setBytes(i + 1, ((String) value).getBytes()); } else if ("bytes".equals(paramType)) { statement.setBytes(i + 1, (byte[]) value); } else { statement.setString(i + 1, (String) value); } } }
From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java
private int[] createPageTemplate(CopyContext copyContext, Document doc, boolean useOldKey) throws VerticalCreateException { Element docElem = doc.getDocumentElement(); Element[] pagetemplateElems;/*from w w w . j a va 2s.c o m*/ if ("pagetemplate".equals(docElem.getTagName())) { pagetemplateElems = new Element[] { docElem }; } else { pagetemplateElems = XMLTool.getElements(doc.getDocumentElement()); } Connection con = null; PreparedStatement preparedStmt = null; TIntArrayList newKeys = new TIntArrayList(); try { con = getConnection(); preparedStmt = con.prepareStatement(PAT_CREATE); for (Element root : pagetemplateElems) { Map<String, Element> subelems = XMLTool.filterElements(root.getChildNodes()); // key int key; String keyStr = root.getAttribute("key"); if (!useOldKey || keyStr == null || keyStr.length() == 0) { key = getNextKey(PAT_TABLE); } else { key = Integer.parseInt(keyStr); } if (copyContext != null) { copyContext.putPageTemplateKey(Integer.parseInt(keyStr), key); } newKeys.add(key); preparedStmt.setInt(1, key); // attribute: menukey keyStr = root.getAttribute("menukey"); int menuKey = Integer.parseInt(keyStr); preparedStmt.setInt(3, menuKey); // element: stylesheet Element stylesheet = subelems.get("stylesheet"); String tmp = stylesheet.getAttribute("stylesheetkey"); preparedStmt.setString(2, tmp); // element: name Element subelem = subelems.get("name"); String name = XMLTool.getElementText(subelem); preparedStmt.setString(4, name); // element: name subelem = subelems.get("description"); if (subelem != null) { String description = XMLTool.getElementText(subelem); if (description != null) { preparedStmt.setString(5, description); } else { preparedStmt.setNull(5, Types.VARCHAR); } } else { preparedStmt.setNull(5, Types.VARCHAR); } // element: timestamp (using the database timestamp at creation) /* no code */ // element: datasources subelem = subelems.get("pagetemplatedata"); Document ptdDoc; if (subelem != null) { ptdDoc = XMLTool.createDocument(); ptdDoc.appendChild(ptdDoc.importNode(subelem, true)); } else { ptdDoc = XMLTool.createDocument("pagetemplatedata"); } byte[] ptdBytes = XMLTool.documentToBytes(ptdDoc, "UTF-8"); ByteArrayInputStream byteStream = new ByteArrayInputStream(ptdBytes); preparedStmt.setBinaryStream(6, byteStream, ptdBytes.length); // element: CSS subelem = subelems.get("css"); if (subelem != null) { preparedStmt.setString(7, subelem.getAttribute("stylesheetkey")); } else { preparedStmt.setNull(7, Types.VARCHAR); } // pagetemplate type: PageTemplateType type = PageTemplateType.valueOf(root.getAttribute("type").toUpperCase()); preparedStmt.setInt(8, type.getKey()); RunAsType runAs = RunAsType.INHERIT; String runAsStr = root.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(9, runAs.getKey()); // add int result = preparedStmt.executeUpdate(); if (result == 0) { String message = "Failed to create page template. No page template created."; VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null); } // create page template parameters Element ptpsElem = XMLTool.getElement(root, "pagetemplateparameters"); int[] ptpKeys = null; if (ptpsElem != null) { Element[] ptpElems = XMLTool.getElements(ptpsElem); for (Element ptpElem : ptpElems) { ptpElem.setAttribute("pagetemplatekey", Integer.toString(key)); } Document ptpDoc = XMLTool.createDocument(); Node n = ptpDoc.importNode(ptpsElem, true); ptpDoc.appendChild(n); ptpKeys = createPageTemplParam(copyContext, ptpDoc); } // create all pageconobj entries for page Element contentobjectsElem = XMLTool.getElement(root, "contentobjects"); if (contentobjectsElem != null) { Element[] contentobjectElems = XMLTool.getElements(contentobjectsElem); for (Element contentobjectElem : contentobjectElems) { contentobjectElem.setAttribute("pagetemplatekey", Integer.toString(key)); if (copyContext != null) { keyStr = contentobjectElem.getAttribute("parameterkey"); int newKey = copyContext.getPageTemplateParameterKey(Integer.parseInt(keyStr)); contentobjectElem.setAttribute("parameterkey", String.valueOf(newKey)); } else { int pIndex = Integer .parseInt(contentobjectElem.getAttribute("parameterkey").substring(1)); contentobjectElem.setAttribute("parameterkey", Integer.toString(ptpKeys[pIndex])); } } Document coDoc = XMLTool.createDocument(); coDoc.appendChild(coDoc.importNode(contentobjectsElem, true)); updatePageTemplateCOs(coDoc, key, ptpKeys); } // element: contenttypes subelem = subelems.get("contenttypes"); Element[] ctyElems = XMLTool.getElements(subelem); int[] ctys = new int[ctyElems.length]; for (int j = 0; j < ctyElems.length; j++) { ctys[j] = Integer.parseInt(ctyElems[j].getAttribute("key")); } setPageTemplateContentTypes(key, ctys); } } catch (SQLException sqle) { String message = "Failed to create page template because of database error: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 1, message, sqle); } catch (NumberFormatException nfe) { String message = "Failed to parse a key field: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 2, message, nfe); } catch (VerticalKeyException gke) { String message = "Failed generate page template key: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 3, message, gke); } finally { close(preparedStmt); close(con); } return newKeys.toArray(); }
From source file:pt.iflow.flows.FlowHolderBean.java
private synchronized State insertOrUpdateFlow(UserInfoInterface userInfo, String file, String name, byte[] data, boolean forceCreate, boolean makeVersion, String comment) { // recorrer a um metodo privado para efectuar a actualizacao // propriamente dita. // Esse mesmo metodo sera usado pelo deploy no caso de ser necessario // actualizar o catalogo. State result = new State(); Connection db = null;/* w ww. j a va 2 s. c o m*/ PreparedStatement pst = null; ResultSet rs = null; boolean flowFound = false; int flowid = -1; try { db = Utils.getDataSource().getConnection(); db.setAutoCommit(false); String query = "select flowid,flowversion from flow where flowfile=? and organizationid=?"; Logger.debug(userInfo.getUtilizador(), this, "insertOrUpdateFlow", "Query1: " + query); pst = db.prepareStatement(query); pst.setString(1, file); pst.setString(2, userInfo.getOrganization()); rs = pst.executeQuery(); if (rs.next()) { flowFound = true; flowid = rs.getInt("flowid"); result.version = rs.getInt("flowversion"); } Logger.debug(userInfo.getUtilizador(), this, "insertOrUpdateFlow", "Flow exists " + flowFound + "id: " + flowid + "; version " + result.version); rs.close(); pst.close(); boolean copyToHistory = false; if (flowFound) { int arg = 0; query = "update flow set " + (StringUtils.isNotEmpty(name) ? "flowname=?," : "") + "flowdata=?," + (makeVersion ? "flowversion=flowversion+1," : "") + "modified=? where flowid=?"; Logger.debug(userInfo.getUtilizador(), this, "insertOrUpdateFlow", "Query2a: " + query); pst = db.prepareStatement(query); if (StringUtils.isNotEmpty(name)) pst.setString(++arg, name); pst.setBinaryStream(++arg, new ByteArrayInputStream(data), data.length); pst.setTimestamp(++arg, new Timestamp(System.currentTimeMillis())); pst.setInt(++arg, flowid); int upd = pst.executeUpdate(); pst.close(); result.created = false; copyToHistory = (upd != 0); } else if (forceCreate) { if (null == name) name = file; Timestamp now = new Timestamp(System.currentTimeMillis()); query = DBQueryManager.getQuery("FlowHolder.INSERT_FLOW"); Logger.debug(userInfo.getUtilizador(), this, "insertOrUpdateFlow", "Query2b: " + query); pst = db.prepareStatement(query, new String[] { "flowid" }); pst.setString(1, name); pst.setString(2, file); pst.setTimestamp(3, now); pst.setString(4, userInfo.getOrganization()); pst.setBinaryStream(5, new ByteArrayInputStream(data), data.length); pst.setTimestamp(6, now); pst.executeUpdate(); rs = pst.getGeneratedKeys(); if (rs.next()) { result.version = 1; result.created = true; flowid = rs.getInt(1); copyToHistory = true; } rs.close(); pst.close(); notifyNewFlow(userInfo, flowid); } else { throw new Exception("Cannot create flow."); } if (copyToHistory && makeVersion) { if (null != comment && comment.length() > MAX_COMMENT_SIZE) comment = comment.substring(0, MAX_COMMENT_SIZE); query = DBQueryManager.getQuery("FlowHolder.COPY_FLOW_TO_HISTORY"); Logger.debug(userInfo.getUtilizador(), this, "insertOrUpdateFlow", "Query3: " + query); pst = db.prepareStatement(query); pst.setString(1, comment); pst.setInt(2, flowid); pst.executeUpdate(); pst.close(); result.version++; } db.commit(); result.success = true; } catch (Exception e) { try { db.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); result.success = false; } finally { DatabaseInterface.closeResources(db, pst, rs); } result.flowid = flowid; return result; }
From source file:org.opencms.db.generic.CmsProjectDriver.java
/** * @see org.opencms.db.I_CmsProjectDriver#createPublishJob(org.opencms.db.CmsDbContext, org.opencms.publish.CmsPublishJobInfoBean) *///from ww w. ja va2 s. co m public void createPublishJob(CmsDbContext dbc, CmsPublishJobInfoBean publishJob) throws CmsDataAccessException { Connection conn = null; PreparedStatement stmt = null; try { CmsPublishJobInfoBean currentJob = readPublishJob(dbc, publishJob.getPublishHistoryId()); LOG.error("wanted to write: " + publishJob); LOG.error("already on db: " + currentJob); return; } catch (CmsDbEntryNotFoundException e) { // ok, this is the expected behavior } try { conn = m_sqlManager.getConnection(dbc); stmt = m_sqlManager.getPreparedStatement(conn, "C_PUBLISHJOB_CREATE"); stmt.setString(1, publishJob.getPublishHistoryId().toString()); stmt.setString(2, publishJob.getProjectId().toString()); stmt.setString(3, publishJob.getProjectName()); stmt.setString(4, publishJob.getUserId().toString()); stmt.setString(5, publishJob.getLocale().toString()); stmt.setInt(6, publishJob.getFlags()); stmt.setInt(7, publishJob.getSize()); stmt.setLong(8, publishJob.getEnqueueTime()); stmt.setLong(9, publishJob.getStartTime()); stmt.setLong(10, publishJob.getFinishTime()); byte[] publishList = internalSerializePublishList(publishJob.getPublishList()); if (publishList.length < 2000) { stmt.setBytes(11, publishList); } else { stmt.setBinaryStream(11, new ByteArrayInputStream(publishList), publishList.length); } stmt.executeUpdate(); } catch (SQLException e) { throw new CmsDbSqlException( Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e); } catch (IOException e) { throw new CmsDbIoException(Messages.get().container(Messages.ERR_SERIALIZING_PUBLISHLIST_1, publishJob.getPublishHistoryId().toString()), e); } finally { m_sqlManager.closeAll(dbc, conn, stmt, null); } }
From source file:org.opencms.db.generic.CmsVfsDriver.java
/** * @see org.opencms.db.I_CmsVfsDriver#writeContent(org.opencms.db.CmsDbContext, org.opencms.util.CmsUUID, byte[]) */// w w w . j a v a 2 s .c o m public void writeContent(CmsDbContext dbc, CmsUUID resourceId, byte[] content) throws CmsDataAccessException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(dbc); stmt = m_sqlManager.getPreparedStatement(conn, dbc.currentProject(), "C_OFFLINE_CONTENTS_UPDATE"); // update the file content in the database. if (content.length < 2000) { stmt.setBytes(1, content); } else { stmt.setBinaryStream(1, new ByteArrayInputStream(content), content.length); } stmt.setString(2, resourceId.toString()); stmt.executeUpdate(); } 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.opencms.db.generic.CmsVfsDriver.java
/** * @see org.opencms.db.I_CmsVfsDriver#createContent(CmsDbContext, CmsUUID, CmsUUID, byte[]) *//* w w w . j a va 2s . c om*/ public void createContent(CmsDbContext dbc, CmsUUID projectId, CmsUUID resourceId, byte[] content) throws CmsDataAccessException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(dbc); // create new offline content stmt = m_sqlManager.getPreparedStatement(conn, "C_OFFLINE_CONTENTS_WRITE"); stmt.setString(1, resourceId.toString()); if (content.length < 2000) { stmt.setBytes(2, content); } else { stmt.setBinaryStream(2, new ByteArrayInputStream(content), content.length); } stmt.executeUpdate(); } 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.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
/** * This method bind values to prepared statement. * * @param type data Type// w ww . java 2 s .co m * @param value String value * @param ordinalPosition Ordinal Position * @param sqlStatement Statement * @throws SQLException * @throws ParseException * @throws ODataServiceFault */ private void bindValuesToPreparedStatement(int type, String value, int ordinalPosition, PreparedStatement sqlStatement) throws SQLException, ParseException, ODataServiceFault { byte[] data; try { switch (type) { case Types.INTEGER: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setInt(ordinalPosition, ConverterUtil.convertToInt(value)); } break; case Types.TINYINT: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setByte(ordinalPosition, ConverterUtil.convertToByte(value)); } break; case Types.SMALLINT: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setShort(ordinalPosition, ConverterUtil.convertToShort(value)); } break; case Types.DOUBLE: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setDouble(ordinalPosition, ConverterUtil.convertToDouble(value)); } break; case Types.VARCHAR: /* fall through */ case Types.CHAR: /* fall through */ case Types.LONGVARCHAR: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setString(ordinalPosition, value); } break; case Types.CLOB: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setClob(ordinalPosition, new BufferedReader(new StringReader(value)), value.length()); } break; case Types.BOOLEAN: /* fall through */ case Types.BIT: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setBoolean(ordinalPosition, ConverterUtil.convertToBoolean(value)); } break; case Types.BLOB: /* fall through */ case Types.LONGVARBINARY: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { data = this.getBytesFromBase64String(value); sqlStatement.setBlob(ordinalPosition, new ByteArrayInputStream(data), data.length); } break; case Types.BINARY: /* fall through */ case Types.VARBINARY: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { data = this.getBytesFromBase64String(value); sqlStatement.setBinaryStream(ordinalPosition, new ByteArrayInputStream(data), data.length); } break; case Types.DATE: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setDate(ordinalPosition, DBUtils.getDate(value)); } break; case Types.DECIMAL: /* fall through */ case Types.NUMERIC: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setBigDecimal(ordinalPosition, ConverterUtil.convertToBigDecimal(value)); } break; case Types.FLOAT: /* fall through */ case Types.REAL: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setFloat(ordinalPosition, ConverterUtil.convertToFloat(value)); } break; case Types.TIME: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setTime(ordinalPosition, DBUtils.getTime(value)); } break; case Types.LONGNVARCHAR: /* fall through */ case Types.NCHAR: /* fall through */ case Types.NVARCHAR: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setNString(ordinalPosition, value); } break; case Types.NCLOB: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setNClob(ordinalPosition, new BufferedReader(new StringReader(value)), value.length()); } break; case Types.BIGINT: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setLong(ordinalPosition, ConverterUtil.convertToLong(value)); } break; case Types.TIMESTAMP: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setTimestamp(ordinalPosition, DBUtils.getTimestamp(value)); } break; default: if (value == null) { sqlStatement.setNull(ordinalPosition, type); } else { sqlStatement.setString(ordinalPosition, value); } break; } } catch (DataServiceFault e) { throw new ODataServiceFault(e, "Error occurred while binding values. :" + e.getMessage()); } }
From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java
/** * Update the pagetemplate in the database. * * @param doc The pagetemplate XML document. * @throws VerticalUpdateException Indicates that the update was not successfull. */// w w w. j ava2 s .c o m private void updatePageTemplate(Document doc) throws VerticalUpdateException { Element docElem = doc.getDocumentElement(); Element[] pagetemplateElems; if ("pagetemplate".equals(docElem.getTagName())) { pagetemplateElems = new Element[] { docElem }; } else { pagetemplateElems = XMLTool.getElements(doc.getDocumentElement()); } Connection con = null; PreparedStatement preparedStmt = null; int pageTemplateKey; try { con = getConnection(); preparedStmt = con.prepareStatement(PAT_UPDATE); for (Element root : pagetemplateElems) { Map<String, Element> subelems = XMLTool.filterElements(root.getChildNodes()); // attribute: key String tmp = root.getAttribute("key"); pageTemplateKey = Integer.parseInt(tmp); preparedStmt.setInt(9, pageTemplateKey); // attribute: type PageTemplateType pageTemplateType = PageTemplateType .valueOf(root.getAttribute("type").toUpperCase()); preparedStmt.setInt(7, pageTemplateType.getKey()); RunAsType runAs = RunAsType.INHERIT; String runAsStr = root.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(8, runAs.getKey()); // attribute: menukey tmp = root.getAttribute("menukey"); int menuKey = Integer.parseInt(tmp); preparedStmt.setInt(2, menuKey); // element: stylesheet Element stylesheet = subelems.get("stylesheet"); String styleSheetKey = stylesheet.getAttribute("stylesheetkey"); preparedStmt.setString(1, styleSheetKey); // element: name Element subelem = subelems.get("name"); String name = XMLTool.getElementText(subelem); preparedStmt.setString(3, name); subelem = subelems.get("description"); if (subelem != null) { String description = XMLTool.getElementText(subelem); if (description != null) { preparedStmt.setString(4, description); } else { preparedStmt.setNull(4, Types.VARCHAR); } } else { preparedStmt.setNull(4, Types.VARCHAR); } // element: timestamp (using the database timestamp at creation) /* no code */ // element: contenttypes subelem = subelems.get("contenttypes"); Element[] ctyElems = XMLTool.getElements(subelem); int[] ctys = new int[ctyElems.length]; for (int j = 0; j < ctyElems.length; j++) { ctys[j] = Integer.parseInt(ctyElems[j].getAttribute("key")); } setPageTemplateContentTypes(pageTemplateKey, ctys); // element: datasources subelem = subelems.get("pagetemplatedata"); Document ptdDoc = XMLTool.createDocument(); ptdDoc.appendChild(ptdDoc.importNode(subelem, true)); byte[] ptdBytes = XMLTool.documentToBytes(ptdDoc, "UTF-8"); ByteArrayInputStream byteStream = new ByteArrayInputStream(ptdBytes); preparedStmt.setBinaryStream(5, byteStream, ptdBytes.length); // element: CSS subelem = subelems.get("css"); if (subelem != null) { String foo = subelem.getAttribute("stylesheetkey"); preparedStmt.setString(6, foo); } else { preparedStmt.setNull(6, Types.VARCHAR); } int result = preparedStmt.executeUpdate(); if (result <= 0) { String message = "Failed to update page template. No page template updated."; VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null); } // If page template is of type "section", we need to create sections for menuitems // that does not have one if (pageTemplateType == PageTemplateType.SECTIONPAGE) { int[] menuItemKeys = getMenuItemKeysByPageTemplate(pageTemplateKey); for (int menuItemKey : menuItemKeys) { MenuItemKey sectionKey = getSectionHandler() .getSectionKeyByMenuItem(new MenuItemKey(menuItemKey)); if (sectionKey == null) { getSectionHandler().createSection(menuItemKey, true, ctys); } } } Element contentobjects = XMLTool.getElement(root, "contentobjects"); Element ptp = XMLTool.getElement(root, "pagetemplateparameters"); if (ptp != null) { int[] paramKeys = new int[0]; // update all ptp entries for page try { int[] oldPTPKey = getPageTemplParamKeys(pageTemplateKey); Node[] ptpNode = XMLTool.filterNodes(ptp.getChildNodes(), Node.ELEMENT_NODE); int[] updatedPTPKey = new int[ptpNode.length]; int updatedPTPs = 0, newPTPs = 0; Document updatedPTPDoc = XMLTool.createDocument("pagetemplateparameters"); Element updatedPTP = updatedPTPDoc.getDocumentElement(); Document newPTPDoc = XMLTool.createDocument("pagetemplateparameters"); Element newPTP = newPTPDoc.getDocumentElement(); for (Node aPtpNode : ptpNode) { ptp = (Element) aPtpNode; String keyStr = ptp.getAttribute("key"); int key; if (keyStr != null && keyStr.length() > 0) { key = Integer.parseInt(keyStr); } else { key = -1; } if (key >= 0) { updatedPTP.appendChild(updatedPTPDoc.importNode(ptp, true)); updatedPTPKey[updatedPTPs++] = key; } else { newPTP.appendChild(newPTPDoc.importNode(ptp, true)); newPTPs++; } } // remove old if (updatedPTPs == 0) { PageHandler pageHandler = getPageHandler(); int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey); for (int pageKey : pageKeys) { pageHandler.removePageContentObjects(pageKey, null); } removePageTemplateCOs(pageTemplateKey, null); removePageTemplParams(pageTemplateKey); } else if (updatedPTPs < oldPTPKey.length) { int temp1[] = new int[updatedPTPs]; System.arraycopy(updatedPTPKey, 0, temp1, 0, updatedPTPs); updatedPTPKey = temp1; Arrays.sort(oldPTPKey); oldPTPKey = ArrayUtil.removeDuplicates(oldPTPKey); Arrays.sort(updatedPTPKey); updatedPTPKey = ArrayUtil.removeDuplicates(updatedPTPKey); int temp2[][] = ArrayUtil.diff(oldPTPKey, updatedPTPKey); PageHandler pageHandler = getPageHandler(); int[] contentObjectKeys = pageHandler.getContentObjectKeys(temp2[0]); int[] pageKeys = pageHandler.getPageKeysByPageTemplateKey(pageTemplateKey); if (contentObjectKeys != null && contentObjectKeys.length > 0) { for (int pageKey : pageKeys) { pageHandler.removePageContentObjects(pageKey, contentObjectKeys); } } removePageTemplateCOs(pageTemplateKey, temp2[0]); removePageTemplParams(temp2[0]); } updatePageTemplParam(updatedPTPDoc); if (newPTPs > 0) { paramKeys = createPageTemplParam(null, newPTPDoc); } } catch (VerticalRemoveException vre) { String message = "Failed to remove old page template parameters: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 3, message, vre); } catch (VerticalCreateException vce) { String message = "Failed to create new page template parameters: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 4, message, vce); } if (contentobjects != null) { // update all pageconobj entries for page try { Document cobsDoc = XMLTool.createDocument(); cobsDoc.appendChild(cobsDoc.importNode(contentobjects, true)); updatePageTemplateCOs(cobsDoc, pageTemplateKey, paramKeys); } catch (VerticalCreateException vce) { String message = "Failed to create new link from page template to content objects: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 2, message, vce); } } } } } catch (SQLException sqle) { String message = "Failed to update page template because of database error: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 5, message, sqle); } catch (NumberFormatException nfe) { String message = "Failed to parse a key field: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, nfe); } catch (VerticalCreateException vce) { String message = "Failed to create sections for page template: %t"; VerticalEngineLogger.errorUpdate(this.getClass(), 6, message, vce); } finally { close(preparedStmt); close(con); } }