List of usage examples for org.w3c.dom Element getTagName
public String getTagName();
From source file:edu.indiana.lib.twinpeaks.search.singlesearch.musepeer.Query.java
/** * Initial response validation and command cleanup/post-processing activities. * <ul>/*from www. j a v a 2s . co m*/ * <li>Verify the response format (an ERROR?) * <li>If no error, perform any cleanup required for the command in question * </ul> *<p> * @param action Server activity (SEARCH, LOGON, etc) */ private void validateResponse(String action) throws SearchException { Document document; Element element; String message, errorText; _log.debug("VALIDATE: " + action); /* * Verify this response corresponds to anticipated server activity */ document = getResponseDocument(); element = document.getDocumentElement(); if ((element != null) && (element.getTagName().equals(action))) { /* * Success - handle any post-processing required for this action */ if (action.equals("LOGON")) { String sessionId; /* * We just logged in. Save the session ID. */ element = DomUtils.getElement(element, "SESSION_ID"); sessionId = DomUtils.getText(element); setSessionId(sessionId); _log.debug("Saved Muse session ID \"" + sessionId + "\""); return; } if (action.equals("SEARCH") || action.equals("MORE")) { Element searchElement; String id; /* * A search (or "more results") command. Save the reference ID. */ searchElement = element; element = DomUtils.getElement(element, "REFERENCE_ID"); id = DomUtils.getText(element); setReferenceId(id); _log.debug("Saved search reference ID \"" + getReferenceId() + "\""); /* * For the initial search, save the result set name as well. */ if (action.equals("SEARCH")) { element = DomUtils.getElement(searchElement, "RESULT_SET_NAME"); id = DomUtils.getText(element); setResultSetName(id); _log.debug("Saved result set name \"" + getResultSetName() + "\""); } return; } /* * No cleanup activities for this action */ _log.debug("No \"cleanup\" activities implemented for " + action); return; } /* * An error - see if we can decipher it */ element = document.getDocumentElement(); if ((element != null) && (element.getTagName().equals("ERROR"))) { element = DomUtils.getElement(element, "MESSAGE"); } if (element == null) { errorText = action + ": Unexpected document format"; LogUtils.displayXml(_log, errorText, document); StatusUtils.setGlobalError(getSessionContext(), errorText); throw new SearchException(errorText); } /* * Format and log the error */ message = DomUtils.getText(element); errorText = action + " error: " + (StringUtils.isNull(message) ? "*unknown*" : message); LogUtils.displayXml(_log, errorText, document); /* * Session timeout is a special case * * -- Re-initialize (clear the query URL) * -- Set "global failure" status * -- Throw the timeout exception */ if (message.endsWith(NO_SESSION)) { removeQueryUrl(APPLICATION); StatusUtils.setGlobalError(getSessionContext(), "Session timed out"); throw new SessionTimeoutException(); } /* * Set final status, abort */ StatusUtils.setGlobalError(getSessionContext(), errorText); throw new SearchException(errorText); }
From source file:com.streamsets.pipeline.stage.processor.xmlflattener.XMLFlatteningProcessor.java
@Override public void process(Record record, SingleLaneBatchMaker singleLaneBatchMaker) throws StageException { if (keepExistingFields && !record.get().getType().isOneOf(Field.Type.MAP, Field.Type.LIST_MAP)) { String errorValue;/*from www .j a va 2 s. c om*/ if (record.get().getType() == Field.Type.LIST) { errorValue = record.get().getValueAsList().toString(); } else { errorValue = record.get().toString(); } throw new OnRecordErrorException(CommonError.CMN_0100, record.get().getType().toString(), errorValue, record.toString()); } Field original = record.get(fieldPath); String xmlData = null; if (original != null) { try { if (original.getType() != Field.Type.STRING) { throw new OnRecordErrorException(CommonError.CMN_0100, original.getType().toString(), original.getValue().toString(), record.toString()); } xmlData = record.get(fieldPath).getValueAsString().trim(); Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xmlData.getBytes())); doc.getDocumentElement().normalize(); Element root = doc.getDocumentElement(); // If we are have a delimiter we are in a record, so just add everything as fields. boolean currentlyInRecord = false; Record newR = null; String prefix = null; List<Record> results = new LinkedList<>(); if (recordDelimiter == null || recordDelimiter.isEmpty() || root.getNodeName().equals(recordDelimiter)) { currentlyInRecord = true; //Increment record count. flattenerPerRecordCount++; if (keepExistingFields) { newR = getContext().cloneRecord(record, String.valueOf(flattenerPerRecordCount)); } else { newR = getContext().createRecord(record, String.valueOf(flattenerPerRecordCount)); newR.set(Field.create(new HashMap<String, Field>())); } ensureOutputFieldExists(newR); prefix = root.getTagName(); addAttrs(newR, root, prefix); results.add(newR); } processXML(newR, currentlyInRecord, new XMLNode(root, prefix), results, record); for (Record result : results) { singleLaneBatchMaker.addRecord(result); } } catch (OnRecordErrorException ex) { errorRecordHandler.onError(new OnRecordErrorException(record, ex.getErrorCode(), ex.getParams())); } catch (Exception ex) { errorRecordHandler .onError(new OnRecordErrorException(record, DataFormatErrors.DATA_FORMAT_303, xmlData, ex)); } finally { //Reset record count flattenerPerRecordCount = 0; } } }
From source file:org.apache.taverna.activities.wsdl.T2WSDLSOAPInvoker.java
@Override protected void addSoapHeader(SOAPEnvelope envelope) throws SOAPException { if (wsrfEndpointReference != null) { // Extract elements // Add WSA-stuff // Add elements Document wsrfDoc;/*from w ww . j a v a 2 s . c o m*/ try { wsrfDoc = parseWsrfEndpointReference(wsrfEndpointReference); } catch (Exception e) { logger.warn("Could not parse endpoint reference, ignoring:\n" + wsrfEndpointReference, e); return; } Element wsrfRoot = wsrfDoc.getDocumentElement(); Element endpointRefElem = null; if (!wsrfRoot.getNamespaceURI().equals(WSA200403NS) || !wsrfRoot.getLocalName().equals(ENDPOINT_REFERENCE)) { // Only look for child if the parent is not an EPR NodeList nodes = wsrfRoot.getChildNodes(); for (int i = 0, n = nodes.getLength(); i < n; i++) { Node node = nodes.item(i); if (Node.ELEMENT_NODE == node.getNodeType() && node.getLocalName().equals(ENDPOINT_REFERENCE) && node.getNamespaceURI().equals(WSA200403NS)) { // Support wrapped endpoint reference for backward compatibility // and convenience (T2-677) endpointRefElem = (Element) node; break; } } } if (endpointRefElem == null) { logger.warn("Unexpected element name for endpoint reference, but inserting anyway: " + wsrfRoot.getTagName()); endpointRefElem = wsrfRoot; } Element refPropsElem = null; NodeList nodes = endpointRefElem.getChildNodes(); for (int i = 0, n = nodes.getLength(); i < n; i++) { Node node = nodes.item(i); if (Node.ELEMENT_NODE == node.getNodeType() && node.getLocalName().equals(REFERENCE_PROPERTIES) && node.getNamespaceURI().equals(WSA200403NS)) { refPropsElem = (Element) node; break; } } if (refPropsElem == null) { logger.warn("Could not find " + REFERENCE_PROPERTIES); return; } SOAPHeader header = envelope.getHeader(); if (header == null) { header = envelope.addHeader(); } NodeList refProps = refPropsElem.getChildNodes(); for (int i = 0, n = refProps.getLength(); i < n; i++) { Node node = refProps.item(i); if (Node.ELEMENT_NODE == node.getNodeType()) { SOAPElement soapElement = SOAPFactory.newInstance().createElement((Element) node); header.addChildElement(soapElement); Iterator<SOAPHeaderElement> headers = header.examineAllHeaderElements(); while (headers.hasNext()) { SOAPHeaderElement headerElement = headers.next(); if (headerElement.getElementQName().equals(soapElement.getElementQName())) { headerElement.setMustUnderstand(false); headerElement.setActor(null); } } } } } }
From source file:com.twinsoft.convertigo.beans.transactions.HtmlTransaction.java
@Override public void parseInputDocument(com.twinsoft.convertigo.engine.Context context) throws EngineException { super.parseInputDocument(context); // TODO : voir si on garde cela // Overrides statefull mode using given __statefull request parameter NodeList stateNodes = context.inputDocument.getElementsByTagName("statefull"); if (stateNodes.getLength() == 1) { Element node = (Element) stateNodes.item(0); String value = node.getAttribute("value"); if (!value.equals("")) { setStateFull(value.equalsIgnoreCase("true")); }// w ww .j av a 2 s . co m } stateNodes = context.inputDocument.getElementsByTagName("webviewer-action"); if (stateNodes.getLength() == 1 && stateNodes.item(0).getChildNodes().getLength() > 0) { Element webviewerAction = (Element) stateNodes.item(0); IdToXpathManager idToXpathManager = context.getIdToXpathManager(); NodeList fieldNodes = context.inputDocument.getElementsByTagName("field"); wcEvent = null; wcTrigger = null; wcFields = new ArrayList<AbstractEvent>(fieldNodes.getLength()); for (int i = 0; i < fieldNodes.getLength(); i++) { Element field = (Element) fieldNodes.item(i); String id = field.getAttribute("name"); id = id.substring(id.lastIndexOf('_') + 1, id.length()); String value = field.getAttribute("value"); String xPath = idToXpathManager.getXPath(id); Node node = idToXpathManager.getNode(id); if (node != null && node instanceof Element) { Element el = (Element) node; String tagname = el.getTagName(); AbstractEvent evt = null; if (tagname.equalsIgnoreCase("input")) { String type = el.getAttribute("type"); if (type.equalsIgnoreCase("checkbox") || type.equalsIgnoreCase("radio")) { evt = new InputCheckEvent(xPath, true, Boolean.valueOf(value).booleanValue()); } else { evt = new InputValueEvent(xPath, true, value); } } else if (tagname.equalsIgnoreCase("select")) { evt = new InputSelectEvent(xPath, true, InputSelectEvent.MOD_INDEX, value.split(";")); } else if (tagname.equalsIgnoreCase("textarea")) { evt = new InputValueEvent(xPath, true, value); } if (evt != null) { wcFields.add(evt); Engine.logBeans.trace("Xpath: " + xPath + " will be set to :" + value); } } } NodeList actionNodes = webviewerAction.getElementsByTagName("action"); if (actionNodes.getLength() == 1) { String action = ((Element) actionNodes.item(0)).getAttribute("value"); if (action.equals("click")) { int screenX, screenY, clientX, clientY; screenX = screenY = clientX = clientY = -1; boolean ctrlKey, altKey, shiftKey, metKey; ctrlKey = altKey = shiftKey = metKey = false; short button = 0; String xPath = null; NodeList eventNodes = webviewerAction.getElementsByTagName("event"); for (int i = 0; i < eventNodes.getLength(); i++) { String name = ((Element) eventNodes.item(i)).getAttribute("name"); String value = ((Element) eventNodes.item(i)).getAttribute("value"); if (name.equals("x") || name.equals("y") || name.startsWith("client")) { int valueInt = Integer.parseInt(value); if (name.equals("x")) screenX = valueInt; else if (name.equals("y")) screenY = valueInt; else if (name.equals("clientX")) clientX = valueInt; else if (name.equals("clientY")) clientY = valueInt; } else if (name.endsWith("Key")) { boolean valueBool = Boolean.getBoolean(value); if (name.equals("ctrlKey")) ctrlKey = valueBool; else if (name.equals("altKey")) altKey = valueBool; else if (name.equals("shiftKey")) altKey = valueBool; else if (name.equals("metKey")) altKey = valueBool; } else if (name.equals("srcid")) { xPath = idToXpathManager.getXPath(value); } } if (xPath != null) { wcEvent = new MouseEvent(xPath, action, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metKey, button); Engine.logBeans.debug("Created an click event from webviewer-action on : " + xPath); } } else if (action.startsWith("navbar_")) { action = action.substring(7, action.length()); wcEvent = new NavigationBarEvent(action); } else { String xPath = null; NodeList eventNodes = webviewerAction.getElementsByTagName("event"); for (int i = 0; i < eventNodes.getLength(); i++) { String name = ((Element) eventNodes.item(i)).getAttribute("name"); String value = ((Element) eventNodes.item(i)).getAttribute("value"); if (name.equals("srcid")) xPath = idToXpathManager.getXPath(value); } if (xPath != null) wcEvent = new SimpleEvent(xPath, action); } bDispatching = (wcEvent != null); if (bDispatching && wcTrigger == null) // wcTrigger = new WaitTimeTrigger(2000); // wcTrigger = new XpathTrigger("*", 10000); // wcTrigger = new DocumentCompletedTrigger(1, 10000); wcTrigger = getTrigger().getTrigger(); } } }
From source file:com.concursive.connect.web.modules.api.beans.TransactionItem.java
public TransactionItem(Element objectElement, PacketContext packetContext, TransactionContext context) { try {// ww w. java2s. c o m this.setAction(objectElement); this.setPacketContext(packetContext); this.setObject(objectElement, packetContext.getObjectMap()); this.objectElement = objectElement; this.transactionContext = context; // Populate just the meta-data here if ("meta".equals(name)) { ignoredProperties = XMLUtils.populateObject(object, objectElement); } } catch (Exception e) { LOG.debug("Error instantiating TransactionItem for: " + objectElement.getTagName(), e); appendErrorMessage("Invalid element: " + objectElement.getTagName()); } }
From source file:com.igormaznitsa.mvngolang.AbstractGolangMojo.java
@Nonnull private String extractSDKFileName(@Nonnull final Document doc, @Nonnull final String sdkBaseName, @Nonnull @MustNotContainNull final String[] allowedExtensions) throws IOException { getLog().debug("Looking for SDK started with base name : " + sdkBaseName); final Set<String> variants = new HashSet<String>(); for (final String ext : allowedExtensions) { variants.add(sdkBaseName + '.' + ext); }/*from www . j a v a 2s .c om*/ final List<String> listedSdk = new ArrayList<String>(); final Element root = doc.getDocumentElement(); if ("ListBucketResult".equals(root.getTagName())) { final NodeList list = root.getElementsByTagName("Contents"); for (int i = 0; i < list.getLength(); i++) { final Element element = (Element) list.item(i); final NodeList keys = element.getElementsByTagName("Key"); if (keys.getLength() > 0) { final String text = keys.item(0).getTextContent(); if (variants.contains(text)) { logOptionally("Detected compatible SDK in the SDK list : " + text); return text; } else { listedSdk.add(text); } } } getLog().error("Can't find any SDK to be used as " + sdkBaseName); getLog().error("GoLang list contains listed SDKs"); getLog().error(".................................................."); for (final String s : listedSdk) { getLog().error(s); } throw new IOException("Can't find SDK : " + sdkBaseName); } else { throw new IOException("It is not a ListBucket file [" + root.getTagName() + ']'); } }
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;/* w w w.j a v a 2s. co 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:autohit.creator.compiler.SimCompiler.java
/** * Processes info section tags. /*w w w . j a va 2 s . c o m*/ */ private void processItem(Element en) throws Exception { String tempText; String name; //runtimeDebug("ENTER --- " + en.getTagName()); name = en.getTagName().toLowerCase(); NodeList itemTreeChildren; int idx; Node sNode; // Parse the token and call a handler if (name.charAt(0) == 'n') { if (name.charAt(1) == 'a') { //NAME tempText = getText(en.getFirstChild()); if (tempText == null) { runtimeError("Empty <name> tag."); } else { ob.exec.name = tempText; runtimeDebug("TAG <name> name= " + ob.exec.name); } // optional uid attribute if (en.hasAttribute(ATTR_UID)) { ob.exec.uid = en.getAttribute(ATTR_UID); localname = ob.exec.uid; runtimeDebug("TAG <name> uid= " + ob.exec.uid); } } else { // NOTE - optional tempText = getText(en.getFirstChild()); ob.exec.note = tempText; } } else if (name.charAt(0) == 'v') { // VERSION ob.exec.major = 0; try { if (en.hasAttribute(ATTR_VERSIONNUMBER)) { tempText = en.getAttribute(ATTR_VERSIONNUMBER); ob.exec.major = Integer.parseInt(tempText); runtimeDebug("TAG <version> num= " + ob.exec.major); } else { runtimeError("ERROR: TAG<version> Attr num not present."); } } catch (Exception e) { runtimeError("ERROR: TAG<version> Could not parse value for Attr num."); } } else if (name.charAt(0) == 'i') { if (name.charAt(1) == 'o') { // IO - Recurse with it's children. itemTreeChildren = en.getChildNodes(); for (idx = 0; idx < itemTreeChildren.getLength(); idx++) { sNode = itemTreeChildren.item(idx); if (sNode instanceof Element) { processItem((Element) sNode); } } } else { // INPUT - NOT SUPPORTED } } else if (name.charAt(0) == 'b') { // BUFFER - NOT SUPPORTED } else if (name.charAt(0) == 'o') { ob.exec.output = new NVPair(); // OUTPUT - Specifies the output variable ob.exec.output.name = en.getAttribute(ATTR_NAME); if (en.hasAttribute(ATTR_TYPE)) { ob.exec.output.value = en.getAttribute(ATTR_TYPE); } } else { runtimeError("Software Detected Fault: creator.compiler.SimCompiler.processItem(). The textual token [" + en.getNodeName() + "] should have NOT reached this code. Check the XML DTD associated with the SimCompiler."); throw (new Exception("Software Detected Fault in creator.compiler.SimCompiler.processItem().")); } //DEBUG //runtimeDebug("EXIT --- " + en.getTagName()); }
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. *//*ww w .j av a2s. co 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); } }
From source file:ai.aitia.meme.paramsweep.intellisweepPlugin.JgapGAPlugin.java
private Map<String, String> readProperties(final Node node) { final Map<String, String> prop = new HashMap<String, String>(); final NodeList nodes = node.getChildNodes(); if (nodes != null) { for (int i = 0; i < nodes.getLength(); ++i) { if (!(nodes.item(i) instanceof Element)) continue; final Element element = (Element) nodes.item(i); if (!element.getTagName().equals(PROPERTY)) continue; final String key = element.getAttribute(KEY); final Text text = (Text) element.getChildNodes().item(0); if (text == null) { prop.put(key.trim(), ""); } else { final String value = text.getNodeValue(); prop.put(key.trim(), value.trim()); }/* w w w .j av a 2 s. c om*/ } } return prop; }