List of usage examples for java.sql PreparedStatement setCharacterStream
void setCharacterStream(int parameterIndex, java.io.Reader reader, long length) throws SQLException;
Reader
object, which is the given number of characters long. From source file:org.jamwiki.db.CacheQueryHandler.java
/** * *//*from w w w .j a va 2 s. c o m*/ @Override public void insertTopicVersions(List<TopicVersion> topicVersions) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; boolean useBatch = (topicVersions.size() > 1); try { conn = DatabaseConnection.getConnection(); if (!this.autoIncrementPrimaryKeys()) { stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION); } else if (useBatch) { // generated keys don't work in batch mode stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION_AUTO_INCREMENT); } else { stmt = conn.prepareStatement(STATEMENT_INSERT_TOPIC_VERSION_AUTO_INCREMENT, Statement.RETURN_GENERATED_KEYS); } int topicVersionId = -1; if (!this.autoIncrementPrimaryKeys() || useBatch) { // manually retrieve next topic version id when using batch // mode or when the database doesn't support generated keys. topicVersionId = DatabaseConnection.executeSequenceQuery(STATEMENT_SELECT_TOPIC_VERSION_SEQUENCE); } for (TopicVersion topicVersion : topicVersions) { if (!this.autoIncrementPrimaryKeys() || useBatch) { // FIXME - if two threads update the database simultaneously then // it is possible that this code could set the topic version ID // to a value that is different from what the database ends up // using. topicVersion.setTopicVersionId(topicVersionId++); } StringReader sr = null; try { int index = 1; stmt.setInt(index++, topicVersion.getTopicVersionId()); if (topicVersion.getEditDate() == null) { topicVersion.setEditDate(new Timestamp(System.currentTimeMillis())); } stmt.setInt(index++, topicVersion.getTopicId()); stmt.setString(index++, topicVersion.getEditComment()); //pass the content into a stream to be passed to Cach sr = new StringReader(topicVersion.getVersionContent()); stmt.setCharacterStream(index++, sr, topicVersion.getVersionContent().length()); if (topicVersion.getAuthorId() == null) { stmt.setNull(index++, Types.INTEGER); } else { stmt.setInt(index++, topicVersion.getAuthorId()); } stmt.setInt(index++, topicVersion.getEditType()); stmt.setString(index++, topicVersion.getAuthorDisplay()); stmt.setTimestamp(index++, topicVersion.getEditDate()); if (topicVersion.getPreviousTopicVersionId() == null) { stmt.setNull(index++, Types.INTEGER); } else { stmt.setInt(index++, topicVersion.getPreviousTopicVersionId()); } stmt.setInt(index++, topicVersion.getCharactersChanged()); stmt.setString(index++, topicVersion.getVersionParamString()); } finally { if (sr != null) { sr.close(); } } if (useBatch) { stmt.addBatch(); } else { stmt.executeUpdate(); } if (this.autoIncrementPrimaryKeys() && !useBatch) { rs = stmt.getGeneratedKeys(); if (!rs.next()) { throw new SQLException("Unable to determine auto-generated ID for database record"); } topicVersion.setTopicVersionId(rs.getInt(1)); } } if (useBatch) { stmt.executeBatch(); } } catch (SQLException e) { throw new UncategorizedSQLException("insertTopicVersions", null, e); } finally { DatabaseConnection.closeConnection(conn, stmt, rs); } }
From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java
private int[] createPageTemplParam(CopyContext copyContext, Document ptpDoc) throws VerticalCreateException { // XML DOM//from w ww. jav a 2 s .c om Element root = ptpDoc.getDocumentElement(); // check: does root element exist? if (root == null) { String message = "Root element does not exist."; VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null); } // check: if root element is not contentrating, throw create exception if (!"pagetemplateparameter".equals(root.getTagName()) && !"pagetemplateparameters".equals(root.getTagName())) { String message = "Root element is not a pagetemplate or pagetemplates element: %0"; VerticalEngineLogger.errorCreate(this.getClass(), 1, message, root.getTagName(), null); } Node[] node; if ("pagetemplateparameters".equals(root.getTagName())) { node = XMLTool.filterNodes(root.getChildNodes(), Node.ELEMENT_NODE); if (node == null || node.length == 0) { String message = "No page template parameters to create"; VerticalEngineLogger.warn(this.getClass(), 2, message, null); } } else { node = new Node[] { root }; } int[] key = new int[node.length]; // connection variables Connection con = null; PreparedStatement preparedStmt = null; try { con = getConnection(); preparedStmt = con.prepareStatement(PTP_CREATE); for (int i = 0; i < node.length; i++) { Element elem = (Element) node[i]; Map<String, Element> subelems = XMLTool.filterElements(elem.getChildNodes()); // attribute: key (generated in database) key[i] = getNextKey(PTP_TABLE); preparedStmt.setInt(1, key[i]); if (copyContext != null) { String keyStr = elem.getAttribute("key"); if (keyStr != null && keyStr.length() > 0) { copyContext.putPageTemplateParameterKey(Integer.parseInt(keyStr), key[i]); } } // element: stylesheet key String tmp = elem.getAttribute("pagetemplatekey"); preparedStmt.setInt(2, Integer.parseInt(tmp)); tmp = elem.getAttribute("multiple"); preparedStmt.setInt(4, Integer.parseInt(tmp)); tmp = elem.getAttribute("override"); preparedStmt.setInt(6, Integer.parseInt(tmp)); // element: name Element subelem = subelems.get("name"); String name = XMLTool.getElementText(subelem); preparedStmt.setCharacterStream(3, new StringReader(name), name.length()); // element: separator subelem = subelems.get("separator"); String separator = XMLTool.getElementText(subelem); if (separator == null || separator.length() == 0) { separator = ""; } preparedStmt.setCharacterStream(5, new StringReader(separator), separator.length()); // element: timestamp (using the database timestamp at creation) /* no code */ preparedStmt.executeUpdate(); } preparedStmt.close(); preparedStmt = null; } catch (SQLException sqle) { String message = "Failed to create page template parameter because of database error: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 4, message, sqle); } catch (NumberFormatException nfe) { String message = "Failed to parse a key field: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 5, message, nfe); } catch (VerticalKeyException gke) { String message = "Failed to generate page template parameter key: %t"; VerticalEngineLogger.errorCreate(this.getClass(), 6, message, gke); } finally { close(preparedStmt); close(con); } return key; }
From source file:helma.objectmodel.db.NodeManager.java
private void setStatementValue(PreparedStatement stmt, int stmtNumber, Property p, int columnType) throws SQLException { if (p.getValue() == null) { stmt.setNull(stmtNumber, columnType); } else {/* w w w .j a v a2 s . co m*/ switch (columnType) { case Types.BIT: case Types.BOOLEAN: stmt.setBoolean(stmtNumber, p.getBooleanValue()); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: stmt.setLong(stmtNumber, p.getIntegerValue()); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: stmt.setDouble(stmtNumber, p.getFloatValue()); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: case Types.BLOB: Object b = p.getJavaObjectValue(); if (b instanceof byte[]) { byte[] buf = (byte[]) b; try { stmt.setBytes(stmtNumber, buf); } catch (SQLException x) { ByteArrayInputStream bout = new ByteArrayInputStream(buf); stmt.setBinaryStream(stmtNumber, bout, buf.length); } } else { throw new SQLException( "expected byte[] for binary column '" + p.getName() + "', found " + b.getClass()); } break; case Types.LONGVARCHAR: try { stmt.setString(stmtNumber, p.getStringValue()); } catch (SQLException x) { String str = p.getStringValue(); Reader r = new StringReader(str); stmt.setCharacterStream(stmtNumber, r, str.length()); } break; case Types.CLOB: String val = p.getStringValue(); Reader isr = new StringReader(val); stmt.setCharacterStream(stmtNumber, isr, val.length()); break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: stmt.setString(stmtNumber, p.getStringValue()); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: stmt.setTimestamp(stmtNumber, p.getTimestampValue()); break; case Types.NULL: stmt.setNull(stmtNumber, 0); break; default: stmt.setString(stmtNumber, p.getStringValue()); break; } } }
From source file:axiom.objectmodel.db.NodeManager.java
private void setStatementValues(PreparedStatement stmt, int stmtNumber, Property p, int columnType) throws SQLException { if (p.getValue() == null) { stmt.setNull(stmtNumber, columnType); } else {//from www. j a v a 2 s . c o m switch (columnType) { case Types.BIT: case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: stmt.setLong(stmtNumber, p.getIntegerValue()); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: stmt.setDouble(stmtNumber, p.getFloatValue()); break; case Types.VARBINARY: case Types.BINARY: case Types.BLOB: stmt.setString(stmtNumber, p.getStringValue()); break; case Types.LONGVARBINARY: case Types.LONGVARCHAR: try { stmt.setString(stmtNumber, p.getStringValue()); } catch (SQLException x) { String str = p.getStringValue(); Reader r = new StringReader(str); stmt.setCharacterStream(stmtNumber, r, str.length()); } break; case Types.CLOB: String val = p.getStringValue(); Reader isr = new StringReader(val); stmt.setCharacterStream(stmtNumber, isr, val.length()); break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: stmt.setString(stmtNumber, p.getStringValue()); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: stmt.setTimestamp(stmtNumber, p.getTimestampValue()); break; case Types.NULL: stmt.setNull(stmtNumber, 0); break; default: stmt.setString(stmtNumber, p.getStringValue()); break; } } }
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;//from w w w. java2 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 void updateMenuItemData(User user, Element menuItemElem, int type, MenuItemKey parent, int order) throws VerticalUpdateException { String tmp;/*ww w . j a va 2 s .c o m*/ boolean modified = "modified".equals(menuItemElem.getAttribute("modified")); Connection con = null; PreparedStatement preparedStmt = null; try { con = getConnection(); // update the main table: int psCounter = 1; if (modified) { preparedStmt = con.prepareStatement(MENU_ITEM_UPDATE); } else { preparedStmt = con.prepareStatement(MENU_ITEM_UPDATE_NO_DATA); } //} // name Element tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_MENUITEM_NAME); String name = XMLTool.getElementText(tmp_elem); validateMenuItemName(name); StringReader sreader = new StringReader(name); preparedStmt.setCharacterStream(psCounter++, sreader, name.length()); if (parent != null) { preparedStmt.setInt(psCounter++, parent.toInt()); } else { preparedStmt.setNull(psCounter++, Types.INTEGER); } // order preparedStmt.setInt(psCounter++, order); Element dataElem; if (modified) { dataElem = XMLTool.getElement(menuItemElem, "data"); // parameters tmp_elem = XMLTool.getElement(menuItemElem, "parameters"); if (tmp_elem != null) { dataElem.appendChild(tmp_elem); } } else { dataElem = null; } // alternative name: tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_MENU_NAME); if (tmp_elem != null) { tmp = XMLTool.getElementText(tmp_elem); preparedStmt.setString(psCounter++, tmp); } else { preparedStmt.setNull(psCounter++, Types.VARCHAR); } // visibility: tmp = menuItemElem.getAttribute("visible"); if ("no".equals(tmp)) { preparedStmt.setInt(psCounter++, 1); } else { preparedStmt.setInt(psCounter++, 0); } // description: tmp_elem = XMLTool.getElement(menuItemElem, "description"); String data = XMLTool.getElementText(tmp_elem); if (data == null) { data = ""; } StringReader reader = new StringReader(data); preparedStmt.setCharacterStream(psCounter++, reader, data.length()); // keywords tmp_elem = XMLTool.getElement(menuItemElem, "keywords"); String keywords = XMLTool.getElementText(tmp_elem); if (keywords == null || keywords.length() == 0) { preparedStmt.setNull(psCounter++, Types.VARCHAR); } else { StringReader keywordReader = new StringReader(keywords); preparedStmt.setCharacterStream(psCounter++, keywordReader, keywords.length()); } // language String lanKey = menuItemElem.getAttribute("languagekey"); if ((lanKey != null) && (lanKey.length() > 0)) { preparedStmt.setInt(psCounter++, Integer.parseInt(lanKey)); } else { preparedStmt.setNull(psCounter++, Types.INTEGER); } // get menuitem key: tmp = menuItemElem.getAttribute("key"); int key = Integer.parseInt(tmp); // owner String ownerKey = menuItemElem.getAttribute("owner"); // modifier String modifierKey = menuItemElem.getAttribute("modifier"); if (modified && type == 4) { //byte[] document = null; Element docElem = XMLTool.getElement(menuItemElem, "document"); dataElem.appendChild(docElem); } preparedStmt.setString(psCounter++, ownerKey); preparedStmt.setString(psCounter++, modifierKey); RunAsType runAs = RunAsType.INHERIT; String runAsStr = menuItemElem.getAttribute("runAs"); if (StringUtils.isNotEmpty(runAsStr)) { runAs = RunAsType.valueOf(runAsStr); } preparedStmt.setInt(psCounter++, runAs.getKey()); // displayname: tmp_elem = XMLTool.getElement(menuItemElem, ELEMENT_NAME_DISPLAY_NAME); if (tmp_elem == null) { throw new IllegalArgumentException("Displayname must be set"); } else { tmp = XMLTool.getElementText(tmp_elem); preparedStmt.setString(psCounter++, tmp); } // data if (modified) { Document dataDoc = XMLTool.createDocument(); dataDoc.appendChild(dataDoc.importNode(dataElem, true)); byte[] bytes = XMLTool.documentToBytes(dataDoc, "UTF-8"); preparedStmt.setBinaryStream(psCounter++, new ByteArrayInputStream(bytes), bytes.length); } preparedStmt.setInt(psCounter, key); preparedStmt.executeUpdate(); if (multicaster.hasListeners()) { int menuKey = getMenuKeyByMenuItem(key); MenuHandlerEvent e = new MenuHandlerEvent(user, menuKey, key, name, this); multicaster.updatedMenuItem(e); } } catch (SQLException sqle) { VerticalEngineLogger.errorUpdate(this.getClass(), 20, "SQL error while updating menuitem data.", sqle); } finally { close(preparedStmt); close(con); } }
From source file: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 www . ja va 2 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: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 ww w . ja v a 2s . co m 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(); }
From source file:nl.b3p.catalog.arcgis.ArcSDE10JDBCHelper.java
@Override public void saveMetadata(ArcSDEJDBCDataset dataset, String metadata) throws Exception { Connection c = getConnection(); PreparedStatement ps = null; try {//www . ja v a 2s. c o m // Sloop encoding uit XML declaratie, anders geeft MSSQL error // "unable to switch the encoding" op column type xml Document doc = DocumentHelper.getMetadataDocument(metadata); metadata = new XMLOutputter(Format.getPrettyFormat().setOmitEncoding(true)).outputString(doc); String sql = "update " + getTableName(TABLE_ITEMS) + " set documentation = ? where objectid = ?"; ps = c.prepareStatement(sql); ps.setCharacterStream(1, new StringReader(metadata), metadata.length()); ps.setObject(2, dataset.getObjectID()); int rowsAffected = ps.executeUpdate(); if (rowsAffected != 1) { throw new Exception("Updating metadata should affect maximum one row; got rows affected count of " + rowsAffected); } } finally { DbUtils.closeQuietly(ps); DbUtils.closeQuietly(c); } }
From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java
/** * Set the given value as a parameter to the statement. *//*from ww w . jav a 2s . c o m*/ public void setCharacterStream(PreparedStatement stmnt, int idx, Reader val, int length, Column col) throws SQLException { stmnt.setCharacterStream(idx, val, length); }