List of usage examples for org.w3c.dom Element hasAttribute
public boolean hasAttribute(String name);
true
when an attribute with a given name is specified on this element or has a default value, false
otherwise. From source file:org.alfresco.web.config.WebConfigRuntime.java
/** * @param configElem/* www . j av a 2s . c om*/ * @param attrName * @param properties * @return */ private boolean manageAttribute(Element configElem, String attrName, HashMap<String, String> properties) { boolean status = false; String newValue = properties.get(attrName); if (newValue != null && !newValue.equals("")) { if (!configElem.hasAttribute(attrName) || !configElem.getAttribute(attrName).equals(newValue)) { status = true; } configElem.setAttribute(attrName, newValue); } else { if (configElem.hasAttribute(attrName)) { configElem.removeAttribute(attrName); status = true; } } return status; }
From source file:pl.chilldev.web.spring.config.HandlePageModelBeanDefinitionParser.java
/** * {@inheritDoc}// www . java 2s . com * @since 0.0.1 */ @Override public BeanDefinition parse(Element element, ParserContext parserContext) { // page model bean prototype GenericBeanDefinition pageMetaModelBean = new GenericBeanDefinition(); pageMetaModelBean.setBeanClass(PageMetaModel.class); pageMetaModelBean.setScope(WebApplicationContext.SCOPE_REQUEST); pageMetaModelBean.setFactoryBeanName(PageMetaModelFactoryBean.class.getName()); pageMetaModelBean.setFactoryMethodName(HandlePageModelBeanDefinitionParser.METHOD_CREATEPAGEMETAMODEL); parserContext.getRegistry().registerBeanDefinition(PageMetaModel.class.getName(), pageMetaModelBean); parserContext.getRegistry().registerBeanDefinition(PageMetaModelFactoryBean.class.getName(), this.pageMetaModelFactoryBean); // XHTML switch needs to be handled with generator bean if (element.hasAttribute(HandlePageModelBeanDefinitionParser.ATTRIBUTE_XHTML)) { boolean xhtml = element.getAttribute(HandlePageModelBeanDefinitionParser.ATTRIBUTE_XHTML) .equals("true"); GenericBeanDefinition generatorBean = new GenericBeanDefinition(); generatorBean.setBeanClass(Generator.class); this.logger.info("Setting markup generator XHTML mode to {}.", xhtml); ConstructorArgumentValues arguments = generatorBean.getConstructorArgumentValues(); arguments.addGenericArgumentValue(xhtml); parserContext.getRegistry().registerBeanDefinition(Generator.class.getName(), generatorBean); arguments = pageMetaModelBean.getConstructorArgumentValues(); arguments.addGenericArgumentValue(new RuntimeBeanReference(Generator.class.getName())); } // register new resolving strategy PageMetaModelContextUtils.setPageMetaModelResolver(new SpringBeansJspPageMetaModelResolver()); pl.chilldev.web.faces.context.PageMetaModelContextUtils .setPageMetaModelResolver(new SpringBeansFacesPageMetaModelResolver()); return null; }
From source file:de.huberlin.wbi.hiway.am.galaxy.GalaxyApplicationMaster.java
/** * A (recursive) helper function for parsing the parameters of a tool from their XML specification * //from w w w. j ava2 s . co m * @param el * the XML element from which to commence the parsing * @return the set of parameters under this element * @throws XPathExpressionException */ private Set<GalaxyParam> getParams(Element el, GalaxyTool tool) throws XPathExpressionException { Set<GalaxyParam> params = new HashSet<>(); XPath xpath = XPathFactory.newInstance().newXPath(); // there are three different types of parameters in Galaxy's tool descriptions: atomic parameters, conditionals and repeats NodeList paramNds = (NodeList) xpath.evaluate("param", el, XPathConstants.NODESET); NodeList conditionalNds = (NodeList) xpath.evaluate("conditional", el, XPathConstants.NODESET); NodeList repeatNds = (NodeList) xpath.evaluate("repeat", el, XPathConstants.NODESET); // (1) parse atomic parameters for (int i = 0; i < paramNds.getLength(); i++) { Element paramEl = (Element) paramNds.item(i); String name = paramEl.getAttribute("name"); GalaxyParamValue param = new GalaxyParamValue(name); params.add(param); // (a) determine default values and mappings of values String type = paramEl.getAttribute("type"); switch (type) { case "data": param.addMapping("", "{\"path\": \"\"}"); tool.setPath(name); break; case "boolean": String trueValue = paramEl.getAttribute("truevalue"); param.addMapping("True", trueValue); String falseValue = paramEl.getAttribute("falsevalue"); param.addMapping("False", falseValue); break; case "select": param.addMapping("", "None"); break; default: } // (b) resolve references to Galaxy data tables NodeList optionNds = (NodeList) xpath.evaluate("option", paramEl, XPathConstants.NODESET); NodeList optionsNds = (NodeList) xpath.evaluate("options", paramEl, XPathConstants.NODESET); for (int j = 0; j < optionNds.getLength() + optionsNds.getLength(); j++) { Element optionEl = j < optionNds.getLength() ? (Element) optionNds.item(j) : (Element) optionsNds.item(j - optionNds.getLength()); if (optionEl.hasAttribute("from_data_table")) { String tableName = optionEl.getAttribute("from_data_table"); GalaxyDataTable galaxyDataTable = galaxyDataTables.get(tableName); for (String value : galaxyDataTable.getValues()) { param.addMapping(value, galaxyDataTable.getContent(value)); } } } } // (2) parse conditionals, which consist of a single condition parameter and several "when condition equals" parameters for (int i = 0; i < conditionalNds.getLength(); i++) { Element conditionalEl = (Element) conditionalNds.item(i); String name = conditionalEl.getAttribute("name"); GalaxyConditional conditional = new GalaxyConditional(name); NodeList conditionNds = (NodeList) xpath.evaluate("param", conditionalEl, XPathConstants.NODESET); NodeList whenNds = (NodeList) xpath.evaluate("when", conditionalEl, XPathConstants.NODESET); if (conditionNds.getLength() == 0 || whenNds.getLength() == 0) continue; Element conditionEl = (Element) conditionNds.item(0); name = conditionEl.getAttribute("name"); GalaxyParamValue condition = new GalaxyParamValue(name); conditional.setCondition(condition); for (int j = 0; j < whenNds.getLength(); j++) { Element whenEl = (Element) whenNds.item(j); String conditionValue = whenEl.getAttribute("value"); conditional.setConditionalParams(conditionValue, getParams(whenEl, tool)); } params.add(conditional); } // (3) parse repeats, which consist of a list of parameters for (int i = 0; i < repeatNds.getLength(); i++) { Element repeatEl = (Element) repeatNds.item(i); String name = repeatEl.getAttribute("name"); GalaxyRepeat repeat = new GalaxyRepeat(name); params.add(repeat); repeat.setParams(getParams(repeatEl, tool)); } return params; }
From source file:fll.subjective.SubjectiveFrame.java
/** * Load data. Meant for testing. Most users should use #promptForFile(). * //from ww w . j a v a 2s . c om * @param file where to read the data in from and where to save data to * @throws IOException */ public void load(final File file) throws IOException { _file = file; ZipFile zipfile = null; try { zipfile = new ZipFile(file); final ZipEntry challengeEntry = zipfile.getEntry(DownloadSubjectiveData.CHALLENGE_ENTRY_NAME); if (null == challengeEntry) { throw new FLLRuntimeException( "Unable to find challenge descriptor in file, you probably choose the wrong file or it is corrupted"); } final InputStream challengeStream = zipfile.getInputStream(challengeEntry); _challengeDocument = ChallengeParser .parse(new InputStreamReader(challengeStream, Utilities.DEFAULT_CHARSET)); challengeStream.close(); _challengeDescription = new ChallengeDescription(_challengeDocument.getDocumentElement()); final ZipEntry scoreEntry = zipfile.getEntry(DownloadSubjectiveData.SCORE_ENTRY_NAME); if (null == scoreEntry) { throw new FLLRuntimeException( "Unable to find score data in file, you probably choose the wrong file or it is corrupted"); } final InputStream scoreStream = zipfile.getInputStream(scoreEntry); _scoreDocument = XMLUtils.parseXMLDocument(scoreStream); scoreStream.close(); final ZipEntry scheduleEntry = zipfile.getEntry(DownloadSubjectiveData.SCHEDULE_ENTRY_NAME); if (null != scheduleEntry) { ObjectInputStream scheduleStream = null; try { scheduleStream = new ObjectInputStream(zipfile.getInputStream(scheduleEntry)); _schedule = (TournamentSchedule) scheduleStream.readObject(); } finally { IOUtils.closeQuietly(scheduleStream); } } else { _schedule = null; } final ZipEntry mappingEntry = zipfile.getEntry(DownloadSubjectiveData.MAPPING_ENTRY_NAME); if (null != mappingEntry) { ObjectInputStream mappingStream = null; try { mappingStream = new ObjectInputStream(zipfile.getInputStream(mappingEntry)); // ObjectStream isn't type safe @SuppressWarnings("unchecked") final Collection<CategoryColumnMapping> mappings = (Collection<CategoryColumnMapping>) mappingStream .readObject(); _scheduleColumnMappings = mappings; } finally { IOUtils.closeQuietly(mappingStream); } } else { _scheduleColumnMappings = null; } } catch (final ClassNotFoundException e) { throw new FLLInternalException("Internal error loading schedule from data file", e); } catch (final SAXParseException spe) { final String errorMessage = String.format( "Error parsing file line: %d column: %d%n Message: %s%n This may be caused by using the wrong version of the software attempting to parse a file that is not subjective data.", spe.getLineNumber(), spe.getColumnNumber(), spe.getMessage()); throw new FLLRuntimeException(errorMessage, spe); } catch (final SAXException se) { final String errorMessage = "The subjective scores file was found to be invalid, check that you are parsing a subjective scores file and not something else"; throw new FLLRuntimeException(errorMessage, se); } finally { if (null != zipfile) { try { zipfile.close(); } catch (final IOException e) { LOGGER.debug("Error closing zipfile", e); } } } for (final ScoreCategory subjectiveCategory : getChallengeDescription().getSubjectiveCategories()) { createSubjectiveTable(tabbedPane, subjectiveCategory); } // get the name and location of the tournament final Element top = _scoreDocument.getDocumentElement(); final String tournamentName = top.getAttribute("tournamentName"); if (top.hasAttribute("tournamentLocation")) { final String tournamentLocation = top.getAttribute("tournamentName"); setTitle(String.format("Subjective Score Entry - %s @ %s", tournamentName, tournamentLocation)); } else { setTitle(String.format("Subjective Score Entry - %s", tournamentName)); } pack(); }
From source file:marytts.modules.phonemiser.AllophoneSet.java
private AllophoneSet(InputStream inputStream) throws MaryConfigurationException { allophones = new TreeMap<String, Allophone>(); // parse the xml file: Document document;// w w w. jav a 2s . c om try { document = DomUtils.parseDocument(inputStream); } catch (Exception e) { throw new MaryConfigurationException("Cannot parse allophone file", e); } finally { try { inputStream.close(); } catch (IOException ioe) { // ignore } } Element root = document.getDocumentElement(); name = root.getAttribute("name"); String xmlLang = root.getAttribute("xml:lang"); locale = MaryUtils.string2locale(xmlLang); String[] featureNames = root.getAttribute("features").split(" "); if (root.hasAttribute("ignore_chars")) { ignore_chars = root.getAttribute("ignore_chars"); } NodeIterator ni = DomUtils.createNodeIterator(document, root, "vowel", "consonant", "silence", "tone"); Element a; while ((a = (Element) ni.nextNode()) != null) { Allophone ap = new Allophone(a, featureNames); if (allophones.containsKey(ap.name())) throw new MaryConfigurationException( "File contains duplicate definition of allophone '" + ap.name() + "'!"); allophones.put(ap.name(), ap); if (ap.isPause()) { if (silence != null) throw new MaryConfigurationException("File contains more than one silence symbol: '" + silence.name() + "' and '" + ap.name() + "'!"); silence = ap; } int len = ap.name().length(); if (len > maxAllophoneSymbolLength) { maxAllophoneSymbolLength = len; } } if (silence == null) throw new MaryConfigurationException("File does not contain a silence symbol"); // Fill the list of possible values for all features // such that "0" comes first and all other values are sorted alphabetically featureValueMap = new TreeMap<String, String[]>(); for (String feature : featureNames) { Set<String> featureValueSet = new TreeSet<String>(); for (Allophone ap : allophones.values()) { featureValueSet.add(ap.getFeature(feature)); } if (featureValueSet.contains("0")) featureValueSet.remove("0"); String[] featureValues = new String[featureValueSet.size() + 1]; featureValues[0] = "0"; int i = 1; for (String f : featureValueSet) { featureValues[i++] = f; } featureValueMap.put(feature, featureValues); } // Special "vc" feature: featureValueMap.put("vc", new String[] { "0", "+", "-" }); }
From source file:com.inspiresoftware.lib.dto.geda.config.AnnotationDrivenGeDABeanDefinitionParser.java
protected RuntimeBeanReference setupPointcutAdvisor(final Element element, final ParserContext parserContext, final Object elementSource, final RuntimeBeanReference pointcutBeanReference, final RuntimeBeanReference interceptorBeanReference) { final RootBeanDefinition pointcutAdvisor = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class); pointcutAdvisor.setSource(elementSource); pointcutAdvisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); final MutablePropertyValues propertyValues = pointcutAdvisor.getPropertyValues(); propertyValues.addPropertyValue("adviceBeanName", interceptorBeanReference.getBeanName()); propertyValues.addPropertyValue("pointcut", pointcutBeanReference); if (element.hasAttribute("order")) { propertyValues.addPropertyValue("order", element.getAttribute("order")); }//from w w w. j av a 2s. c om final BeanDefinitionRegistry registry = parserContext.getRegistry(); registry.registerBeanDefinition(ADVISOR_BEAN_NAME, pointcutAdvisor); return new RuntimeBeanReference(ADVISOR_BEAN_NAME); }
From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java
protected void prepareJson(Element element, BeanDefinitionBuilder builder) { Element jsonElement = selectSingleChildElement(element, "json", false); // Object mapper if (jsonElement.hasAttribute("object-mapper-ref")) { String objectMapperRef = jsonElement.getAttribute("object-mapper-ref"); builder.addConstructorArgReference(objectMapperRef); } else {//from ww w . j av a2 s . co m builder.addConstructorArgValue(prepareObjectMapper()); } // RootNode class String rootNodeClass = jsonElement.getAttribute("root-node-class"); builder.addConstructorArgValue(rootNodeClass); // ConversionManager builder.addConstructorArgValue(prepareJsonConversionManager()); }
From source file:de.huberlin.wbi.hiway.am.galaxy.GalaxyApplicationMaster.java
/** * A helper function for processing the Galaxy config file that specifies metadata for data tables along with the location of their loc files * /*from ww w. ja va 2 s .co m*/ * @param file * the Galaxy data table config file */ private void processDataTables(File file) { try { System.out.println("Processing Galaxy data table config file " + file.getCanonicalPath()); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(file); NodeList tables = doc.getElementsByTagName("table"); for (int i = 0; i < tables.getLength(); i++) { Element tableEl = (Element) tables.item(i); Element columnsEl = (Element) tableEl.getElementsByTagName("columns").item(0); Element fileEl = (Element) tableEl.getElementsByTagName("file").item(0); String name = tableEl.getAttribute("name"); String comment_char = tableEl.getAttribute("comment_char"); String[] columns = columnsEl.getFirstChild().getNodeValue().split(", "); if (!fileEl.hasAttribute("path")) continue; String path = fileEl.getAttribute("path"); if (!path.startsWith("/")) path = galaxyPath + "/" + path; GalaxyDataTable galaxyDataTable = new GalaxyDataTable(name, comment_char, columns, path); processLocFile(new File(path), galaxyDataTable); galaxyDataTables.put(name, galaxyDataTable); } } catch (SAXException | IOException | ParserConfigurationException e) { e.printStackTrace(); System.exit(-1); } }
From source file:de.qucosa.webapi.v1.DocumentResource.java
@RequestMapping(value = "/document/{qucosaID}", method = RequestMethod.PUT, consumes = { "text/xml", "application/xml", MIMETYPE_QUCOSA_V1_XML }) public ResponseEntity<String> updateDocument(@PathVariable String qucosaID, @RequestParam(value = "nis1", required = false) String libraryNetworkAbbreviation, @RequestParam(value = "nis2", required = false) String libraryIdentifier, @RequestParam(value = "niss", required = false) String prefix, @RequestBody String body) throws Exception { String pid = "qucosa:" + qucosaID; if (!fedoraRepository.hasObject(pid)) { return errorResponse("Qucosa document " + qucosaID + " not found.", HttpStatus.NOT_FOUND); }/*from w w w . java 2 s.c om*/ Document updateDocument = documentBuilder.parse(IOUtils.toInputStream(body)); assertXPathNodeExists("/Opus[@version='2.0']", "No Opus node with version '2.0'.", updateDocument); assertXPathNodeExists("/Opus/Opus_Document", "No Opus_Document node found.", updateDocument); if (log.isDebugEnabled()) { log.debug("Incoming update XML:"); log.debug(DOMSerializer.toString(updateDocument)); } Document qucosaDocument = documentBuilder .parse(fedoraRepository.getDatastreamContent(pid, DSID_QUCOSA_XML)); List<FileUpdateOperation> fileUpdateOperations = new LinkedList<>(); Tuple<Collection<String>> updateOps = updateWith(qucosaDocument, updateDocument, fileUpdateOperations); Set<String> updateFields = (Set<String>) updateOps.get(0); assertBasicDocumentProperties(qucosaDocument); List<String> newDcUrns = new LinkedList<>(); if (updateFields.contains("IdentifierUrn")) { Set<String> updateSet = getIdentifierUrnValueSet(updateDocument); newDcUrns.addAll(updateSet); } if (!hasURN(qucosaDocument)) { String urnnbn = generateUrnString(libraryNetworkAbbreviation, libraryIdentifier, prefix, qucosaID); addIdentifierUrn(qucosaDocument, urnnbn); newDcUrns.add(urnnbn); } String newTitle = null; if (updateFields.contains("TitleMain")) { newTitle = xPath.evaluate("/Opus/Opus_Document/TitleMain[1]/Value", qucosaDocument); } modifyDcDatastream(pid, newDcUrns, newTitle); NodeList newFileElements = (NodeList) xPath.evaluate("/Opus/Opus_Document/File", qucosaDocument, XPathConstants.NODESET); for (int i = 0; i < newFileElements.getLength(); i++) { Element fileElement = (Element) newFileElements.item(i); if (!fileElement.hasAttribute("id")) { handleFileElement(pid, i + 1, fileElement); } } InputStream inputStream = IOUtils.toInputStream(DOMSerializer.toString(qucosaDocument)); fedoraRepository.modifyDatastreamContent(pid, DSID_QUCOSA_XML, MIMETYPE_QUCOSA_V1_XML, inputStream); String state = null; if (updateFields.contains("ServerState")) { state = determineState(qucosaDocument); } String label = null; if (updateFields.contains("TitleMain") || updateFields.contains("PersonAuthor")) { label = buildAts(qucosaDocument); } String ownerId = "qucosa"; fedoraRepository.modifyObjectMetadata(pid, state, label, ownerId); List<String> purgeDatastreamList = (List<String>) updateOps.get(1); purgeFilesAndCorrespondingDatastreams(pid, purgeDatastreamList); executeFileUpdateOperations(pid, fileUpdateOperations); writeHtAccessFile(qucosaID, qucosaDocument); String okResponse = getDocumentUpdatedResponse(); return new ResponseEntity<>(okResponse, HttpStatus.OK); }
From source file:com.googlecode.ehcache.annotations.config.AnnotationDrivenEhCacheBeanDefinitionParser.java
/** * Create {@link PointcutAdvisor} that puts the {@link Pointcut} and {@link MethodInterceptor} together. * /* ww w . j av a 2s.co m*/ * @return Reference to the {@link PointcutAdvisor}. Should never be null. */ protected RuntimeBeanReference setupPointcutAdvisor(Element element, ParserContext parserContext, Object elementSource, RuntimeBeanReference cacheablePointcutBeanReference, RuntimeBeanReference cachingInterceptorBeanReference) { final RootBeanDefinition pointcutAdvisor = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class); pointcutAdvisor.setSource(elementSource); pointcutAdvisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); final MutablePropertyValues propertyValues = pointcutAdvisor.getPropertyValues(); propertyValues.addPropertyValue("adviceBeanName", cachingInterceptorBeanReference.getBeanName()); propertyValues.addPropertyValue("pointcut", cacheablePointcutBeanReference); if (element.hasAttribute("order")) { propertyValues.addPropertyValue("order", element.getAttribute("order")); } final BeanDefinitionRegistry registry = parserContext.getRegistry(); registry.registerBeanDefinition(EHCACHE_CACHING_ADVISOR_BEAN_NAME, pointcutAdvisor); return new RuntimeBeanReference(EHCACHE_CACHING_ADVISOR_BEAN_NAME); }