List of usage examples for org.w3c.dom Element getAttribute
public String getAttribute(String name);
From source file:com.aurel.track.admin.customize.category.report.ReportBL.java
public static Map<String, Object> getTemplateDescription(InputStream is) { Map<String, Object> description = new HashMap<String, Object>(); try {//ww w .j a v a 2s .c o m DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); doc.getDocumentElement().normalize(); try { NodeList nl = doc.getElementsByTagName("locale"); for (int s = 0; s < nl.getLength(); s++) { Node localeNode = nl.item(s); if (localeNode.getNodeType() == Node.ELEMENT_NODE) { Map<String, String> localizedStuff = new HashMap<String, String>(); String value = ""; String descript = ""; String listing = ""; String toolTip = ""; Element element = (Element) localeNode; descript = getTagValue("description", element).trim(); listing = getTagValue("listing", element).trim(); toolTip = getTagValue("tool-tip", element).trim(); value = element.getAttribute("value"); if (value == null) { value = ""; } localizedStuff.put("listing", listing); localizedStuff.put("description", descript); localizedStuff.put("tool-tip", toolTip); description.put("locale_" + value, localizedStuff); } } } catch (Exception e) { LOGGER.error("Getting the locale elements failed with " + e.getMessage()); } NodeList nl = doc.getDocumentElement().getChildNodes(); for (int s = 0; s < nl.getLength(); s++) { if (nl.item(s).getNodeType() == Node.ELEMENT_NODE) { description.put(nl.item(s).getNodeName(), nl.item(s).getChildNodes().item(0).getNodeValue()); } } } catch (Exception e) { LOGGER.error(e.getMessage()); } return description; }
From source file:edu.indiana.lib.twinpeaks.search.SearchSource.java
/** * Locate a handler specification/* w w w . java 2 s.co m*/ * @param parent Parent element for this search * @param handlerName Handler to look up * @return Class name for this handler */ private static String parseHandler(Element parent, String handlerName) { Element element; String handler; if ((element = DomUtils.getElement(parent, handlerName)) == null) { return null; } handler = element.getAttribute("name"); return (StringUtils.isNull(handler)) ? null : handler; }
From source file:at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient.java
public static List<MISMandate> sendGetMandatesRequest(String webServiceURL, String sessionId, SSLSocketFactory sSLSocketFactory) throws MISSimpleClientException { if (webServiceURL == null) { throw new NullPointerException("Argument webServiceURL must not be null."); }//from w w w . j a va 2s . com if (sessionId == null) { throw new NullPointerException("Argument sessionId must not be null."); } // ssl settings if (sSLSocketFactory != null) { SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory); Protocol.registerProtocol("https", new Protocol("https", fac, 443)); } try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element mirElement = doc.createElementNS(MIS_NS, "MandateIssueRequest"); Element sessionIdElement = doc.createElementNS(MIS_NS, "SessionID"); sessionIdElement.appendChild(doc.createTextNode(sessionId)); mirElement.appendChild(sessionIdElement); // send soap request Element mandateIssueResponseElement = sendSOAPRequest(webServiceURL, mirElement); // check for error checkForError(mandateIssueResponseElement); // check for session id NodeList mandateElements = XPathAPI.selectNodeList(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:Mandates/mis:Mandate", NS_NODE); if (mandateElements == null || mandateElements.getLength() == 0) { throw new MISSimpleClientException("No mandates found in response."); } ArrayList<MISMandate> foundMandates = new ArrayList<MISMandate>(); for (int i = 0; i < mandateElements.getLength(); i++) { Element mandate = (Element) mandateElements.item(i); MISMandate misMandate = new MISMandate(); if (mandate.hasAttribute("ProfessionalRepresentative")) { // System.out.println("OID: " + mandate.getAttribute("ProfessionalRepresentative")); misMandate.setProfRep(mandate.getAttribute("ProfessionalRepresentative")); } if (mandate.hasAttribute("OWbPK")) { misMandate.setOWbPK(mandate.getAttribute("OWbPK")); // System.out.println("OWBPK: " + mandate.getAttribute("OWbPK")); } //misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate))); misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate).getBytes())); misMandate.setFullMandateIncluded(true); foundMandates.add(misMandate); } return foundMandates; } catch (ParserConfigurationException e) { throw new MISSimpleClientException("service.06", e); } catch (DOMException e) { throw new MISSimpleClientException("service.06", e); } catch (TransformerException e) { throw new MISSimpleClientException("service.06", e); } }
From source file:it.intecs.pisa.toolbox.util.URLReader.java
public static void writeURLContentToXML(String infoXmlFile, String fileName) throws Exception { try {//www .j a v a2s .co m String host = null; String url = null; int port = 0; Element infoXml = new DOMUtil().fileToDocument(new File(infoXmlFile)).getDocumentElement(); if (infoXml != null) { host = infoXml.getAttribute("newVersionHost"); url = infoXml.getAttribute("newVersionUrl"); String portStr = infoXml.getAttribute("newVersionPort"); Integer portInt = new Integer(portStr); port = portInt.intValue(); } String fileContent = (String) getURLContent(host, url, port); if (fileContent == null) return; fileContent = fileContent.substring(fileContent.indexOf("<"), fileContent.lastIndexOf(">") + 1); File newFile = new File(fileName); FileWriter fw = new FileWriter(newFile); fw.write(fileContent); fw.close(); } catch (Exception e) { e.printStackTrace(System.out); return; } }
From source file:com.twinsoft.convertigo.engine.migration.Migration7_0_0.java
public static Element migrate(Document document, Element projectNode) throws EngineException { try {//w ww. j a va 2s . com NodeList mobileDevicesNodeList = XMLUtils.findElements(projectNode, "/mobiledevice"); if (mobileDevicesNodeList != null) { MobileApplication mobileApplication = new MobileApplication(); Element mobileApplicationElement = mobileApplication.toXml(document); projectNode.appendChild(mobileApplicationElement); Node[] mobileDeviceNodes = XMLUtils.toNodeArray(mobileDevicesNodeList); boolean hasAndroid = false; boolean hasIOs = false; for (Node mobileDeviceNode : mobileDeviceNodes) { Element mobileDevice = (Element) mobileDeviceNode; String classname = mobileDevice.getAttribute("classname"); if (classname == null) { // may never arrived } else if (classname.equals("com.twinsoft.convertigo.beans.mobiledevices.Android")) { hasAndroid = true; } else if (classname.startsWith("com.twinsoft.convertigo.beans.mobiledevices.IP")) { hasIOs = true; } projectNode.removeChild(mobileDevice); } if (hasAndroid) { mobileApplicationElement.appendChild(new Android().toXml(document)); } if (hasIOs) { mobileApplicationElement.appendChild(new IOs().toXml(document)); } if (hasAndroid && hasIOs) { mobileApplicationElement.appendChild(new WindowsPhone8().toXml(document)); mobileApplicationElement.appendChild(new Windows().toXml(document)); } String projectName = "" + XMLUtils.findPropertyValue(projectNode, "name"); File mobileFolder = new File(Engine.PROJECTS_PATH + "/" + projectName + "/DisplayObjects/mobile"); if (mobileFolder.exists()) { FileUtils.write(new File(mobileFolder, "mobile_project_migrated.txt"), "Your mobile project has been migrated.\n" + "Now, we make per platform configuration and resources.\n" + "You may customize your config.xml (the existing one will never used) and dispatch your existing specific resources per platform (see the 'platforms' folder).\n" + "You can delete this file after reading it.", "UTF-8"); } } } catch (Exception e) { throw new EngineException("[Migration 7.0.0] Unable to migrate project", e); } return projectNode; }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java
private static void readTaskConfiguration(Document xmlConfiguration) { taskProgressInterval = null;/*from w w w. j a va 2 s. c o m*/ taskLinesToSave = null; Element doc = xmlConfiguration.getDocumentElement(); // task progress interval NodeList taskProgressIntervalNodes = doc.getElementsByTagName("progressInterval"); Node taskProgressIntervalNode = taskProgressIntervalNodes.item(0); if (taskProgressIntervalNode instanceof Element) { Element taskProgressIntervalElement = (Element) taskProgressIntervalNode; String taskProgressIntervalValue = taskProgressIntervalElement.getAttribute("value"); if (!StringUtils.isEmpty(taskProgressIntervalValue)) { taskProgressInterval = Integer.parseInt(taskProgressIntervalValue); } } // task lines to save NodeList taskLinesToSaveNodes = doc.getElementsByTagName("linesToSave"); Node taskLinesToSaveNode = taskLinesToSaveNodes.item(0); if (taskLinesToSaveNode instanceof Element) { Element taskLinesToSaveElement = (Element) taskLinesToSaveNode; String linesToSaveValue = taskLinesToSaveElement.getAttribute("value"); if (!StringUtils.isEmpty(linesToSaveValue)) { taskLinesToSave = Integer.parseInt(linesToSaveValue); } } }
From source file:it.intecs.pisa.toolbox.util.URLReader.java
public static boolean isVersionToUpdate(String newVersionFile, String currentVersionFile) throws Exception { String thisLine = null;/*from ww w . ja v a 2s .c o m*/ String currentVersion = null; String newVersion = null; try { Element infoXml = new DOMUtil().fileToDocument(new File(currentVersionFile)).getDocumentElement(); if (infoXml != null) { currentVersion = infoXml.getAttribute("toolboxVersion"); } Element tbUpgradeXml = new DOMUtil().fileToDocument(new File(newVersionFile)).getDocumentElement(); if (tbUpgradeXml != null) { newVersion = tbUpgradeXml.getAttribute("version"); } return compareVersions(newVersion, currentVersion, false); } catch (Exception e) { e.printStackTrace(System.out); return false; } }
From source file:fll.web.admin.UploadSubjectiveData.java
@SuppressFBWarnings(value = { "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns are dynamic") private static void saveCategoryData(final int currentTournament, final Connection connection, final Element scoreCategoryElement, final String categoryName, final ScoreCategory categoryElement) throws SQLException, ParseException { final List<AbstractGoal> goalDescriptions = categoryElement.getGoals(); PreparedStatement insertPrep = null; PreparedStatement updatePrep = null; try {// w ww . j av a 2 s . com // prepare statements for update and insert final StringBuffer updateStmt = new StringBuffer(); final StringBuffer insertSQLColumns = new StringBuffer(); insertSQLColumns.append("INSERT INTO " + categoryName + " (TeamNumber, Tournament, Judge, NoShow"); final StringBuffer insertSQLValues = new StringBuffer(); insertSQLValues.append(") VALUES ( ?, ?, ?, ?"); updateStmt.append("UPDATE " + categoryName + " SET NoShow = ? "); final int numGoals = goalDescriptions.size(); for (final AbstractGoal goalDescription : goalDescriptions) { insertSQLColumns.append(", " + goalDescription.getName()); insertSQLValues.append(", ?"); updateStmt.append(", " + goalDescription.getName() + " = ?"); } updateStmt.append(" WHERE TeamNumber = ? AND Tournament = ? AND Judge = ?"); updatePrep = connection.prepareStatement(updateStmt.toString()); insertPrep = connection .prepareStatement(insertSQLColumns.toString() + insertSQLValues.toString() + ")"); // initialze the tournament insertPrep.setInt(2, currentTournament); updatePrep.setInt(numGoals + 3, currentTournament); for (final Element scoreElement : new NodelistElementCollectionAdapter( scoreCategoryElement.getElementsByTagName("score"))) { if (scoreElement.hasAttribute("modified") && "true".equalsIgnoreCase(scoreElement.getAttribute("modified"))) { final int teamNumber = Utilities.NUMBER_FORMAT_INSTANCE .parse(scoreElement.getAttribute("teamNumber")).intValue(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Saving score data for team: " + teamNumber); } final String judgeId = scoreElement.getAttribute("judge"); final boolean noShow = Boolean.parseBoolean(scoreElement.getAttribute("NoShow")); updatePrep.setBoolean(1, noShow); insertPrep.setBoolean(4, noShow); insertPrep.setInt(1, teamNumber); updatePrep.setInt(numGoals + 2, teamNumber); insertPrep.setString(3, judgeId); updatePrep.setString(numGoals + 4, judgeId); int goalIndex = 0; for (final AbstractGoal goalDescription : goalDescriptions) { final String goalName = goalDescription.getName(); final Element subscoreElement = SubjectiveUtils.getSubscoreElement(scoreElement, goalName); if (null == subscoreElement) { // no subscore element, no show or deleted insertPrep.setNull(goalIndex + 5, Types.DOUBLE); updatePrep.setNull(goalIndex + 2, Types.DOUBLE); } else { final String value = subscoreElement.getAttribute("value"); if (!value.trim().isEmpty()) { insertPrep.setString(goalIndex + 5, value.trim()); updatePrep.setString(goalIndex + 2, value.trim()); } else { insertPrep.setNull(goalIndex + 5, Types.DOUBLE); updatePrep.setNull(goalIndex + 2, Types.DOUBLE); } } ++goalIndex; } // end for // attempt the update first final int modifiedRows = updatePrep.executeUpdate(); if (modifiedRows < 1) { // do insert if nothing was updated insertPrep.executeUpdate(); } } } } finally { SQLFunctions.close(insertPrep); SQLFunctions.close(updatePrep); } }
From source file:eidassaml.starterkit.EidasRequest.java
public static EidasRequest Parse(InputStream is, List<X509Certificate> authors) throws XMLParserException, UnmarshallingException, ErrorCodeException, IOException { EidasRequest eidasReq = new EidasRequest(); BasicParserPool ppMgr = new BasicParserPool(); ppMgr.setNamespaceAware(true);/* w ww . j a v a 2s. c o m*/ Document inCommonMDDoc = ppMgr.parse(is); Element metadataRoot = inCommonMDDoc.getDocumentElement(); UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot); eidasReq.request = (AuthnRequest) unmarshaller.unmarshall(metadataRoot); if (authors != null) { CheckSignature(eidasReq.request.getSignature(), authors); } //isPassive SHOULD be false if (!eidasReq.request.isPassive()) { eidasReq.setPassive(eidasReq.request.isPassive()); } else { throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX, "Unsupported IsPassive value:" + eidasReq.request.isPassive()); } //forceAuthn MUST be true if (eidasReq.request.isForceAuthn()) { eidasReq.setIsForceAuthn(eidasReq.request.isForceAuthn()); } else { throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX, "Unsupported ForceAuthn value:" + eidasReq.request.isForceAuthn()); } eidasReq.id = eidasReq.request.getID(); //there should be one AuthnContextClassRef AuthnContextClassRef ref = eidasReq.request.getRequestedAuthnContext().getAuthnContextClassRefs().get(0); if (null != ref) { eidasReq.authClassRef = EidasLoA.GetValueOf(ref.getDOM().getTextContent()); } else { throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX, "No AuthnContextClassRef element."); } String namiIdformat = eidasReq.request.getNameIDPolicy().getFormat(); eidasReq.nameIdPolicy = EidasNameIdType.GetValueOf(namiIdformat); eidasReq.issueInstant = SimpleDf.format(eidasReq.request.getIssueInstant().toDate()); eidasReq.issuer = eidasReq.request.getIssuer().getDOM().getTextContent(); eidasReq.destination = eidasReq.request.getDestination(); if (null != eidasReq.request.getProviderName() && !eidasReq.request.getProviderName().isEmpty()) { eidasReq.providerName = eidasReq.request.getProviderName(); } else { throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX, "No providerName attribute."); } eidasReq.selectorType = null; for (XMLObject extension : eidasReq.request.getExtensions().getOrderedChildren()) { if ("RequestedAttributes".equals(extension.getElementQName().getLocalPart())) { for (XMLObject attribute : extension.getOrderedChildren()) { Element el = attribute.getDOM(); EidasPersonAttributes eidasPersonAttributes = getEidasPersonAttributes(el); if (null != eidasPersonAttributes) { eidasReq.requestedAttributes.put(eidasPersonAttributes, Boolean.parseBoolean(el.getAttribute("isRequired"))); } } } else if ("SPType".equals(extension.getElementQName().getLocalPart())) { eidasReq.selectorType = EidasRequestSectorType.GetValueOf(extension.getDOM().getTextContent()); } } if (!containsMinimumDataSet(eidasReq.requestedAttributes)) { throw new ErrorCodeException(ErrorCode.ILLEGAL_REQUEST_SYNTAX, "Request does not contain minimum dataset."); } return eidasReq; }
From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) throws ClassNotFoundException { RootBeanDefinition bd = new RootBeanDefinition(); bd.setBeanClass(beanClass);/*w ww . ja va2 s .c om*/ // ??lazy init bd.setLazyInit(false); // id?id,idcontext String id = element.getAttribute("id"); if ((id == null || id.length() == 0) && required) { String generatedBeanName = element.getAttribute("name"); if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = element.getAttribute("class"); } if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while (parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter++); } } if (id != null && id.length() > 0) { if (parserContext.getRegistry().containsBeanDefinition(id)) { throw new IllegalStateException("Duplicate spring bean id " + id); } parserContext.getRegistry().registerBeanDefinition(id, bd); } bd.getPropertyValues().addPropertyValue("id", id); if (ProtocolConfig.class.equals(beanClass)) { MotanNamespaceHandler.protocolDefineNames.add(id); } else if (RegistryConfig.class.equals(beanClass)) { MotanNamespaceHandler.registryDefineNames.add(id); } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) { MotanNamespaceHandler.basicServiceConfigDefineNames.add(id); } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) { MotanNamespaceHandler.basicRefererConfigDefineNames.add(id); } else if (ServiceConfigBean.class.equals(beanClass)) { String className = element.getAttribute("class"); if (className != null && className.length() > 0) { RootBeanDefinition classDefinition = new RootBeanDefinition(); classDefinition.setBeanClass( Class.forName(className, true, Thread.currentThread().getContextClassLoader())); classDefinition.setLazyInit(false); parseProperties(element.getChildNodes(), classDefinition); bd.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl")); } } Set<String> props = new HashSet<String>(); ManagedMap parameters = null; // ??setbd for (Method setter : beanClass.getMethods()) { String name = setter.getName(); // setXXX if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers()) || setter.getParameterTypes().length != 1) { continue; } String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-"); props.add(property); if ("id".equals(property)) { bd.getPropertyValues().addPropertyValue("id", id); continue; } String value = element.getAttribute(property); if ("methods".equals(property)) { parseMethods(id, element.getChildNodes(), bd, parserContext); } if (StringUtils.isBlank(value)) { continue; } value = value.trim(); if (value.length() == 0) { continue; } Object reference; if ("ref".equals(property)) { if (parserContext.getRegistry().containsBeanDefinition(value)) { BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value); if (!refBean.isSingleton()) { throw new IllegalStateException( "The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>"); } } reference = new RuntimeBeanReference(value); } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) { if (!value.contains(",")) { reference = new RuntimeBeanReference(value); } else { parseMultiRef("protocols", value, bd, parserContext); reference = null; } } else if ("registry".equals(property)) { parseMultiRef("registries", value, bd, parserContext); reference = null; } else if ("basicService".equals(property)) { reference = new RuntimeBeanReference(value); } else if ("basicReferer".equals(property)) { reference = new RuntimeBeanReference(value); } else if ("extConfig".equals(property)) { reference = new RuntimeBeanReference(value); } else { reference = new TypedStringValue(value); } if (reference != null) { bd.getPropertyValues().addPropertyValue(property, reference); } } if (ProtocolConfig.class.equals(beanClass)) { // protocolparameters? NamedNodeMap attributes = element.getAttributes(); int len = attributes.getLength(); for (int i = 0; i < len; i++) { Node node = attributes.item(i); String name = node.getLocalName(); if (!props.contains(name)) { if (parameters == null) { parameters = new ManagedMap(); } String value = node.getNodeValue(); parameters.put(name, new TypedStringValue(value, String.class)); } } bd.getPropertyValues().addPropertyValue("parameters", parameters); } return bd; }