List of usage examples for org.w3c.dom Document getElementsByTagNameNS
public NodeList getElementsByTagNameNS(String namespaceURI, String localName);
NodeList
of all the Elements
with a given local name and namespace URI in document order. From source file:de.mpg.escidoc.services.transformation.transformations.commonPublicationFormats.Bibtex.java
/** * @param bibtex/*w w w . j a v a 2s.c o m*/ * @return eSciDoc-publication item XML representation of this BibTeX entry * @throws RuntimeException */ public String getBibtex(String bibtex) throws RuntimeException { // Remove Math '$' from the whole BibTex-String Pattern mathPattern = Pattern.compile("(?sm)\\$(\\\\.*?)(?<!\\\\)\\$"); Matcher mathMatcher = mathPattern.matcher(bibtex); StringBuffer sb = new StringBuffer(); while (mathMatcher.find()) { mathMatcher.appendReplacement(sb, "$1"); } mathMatcher.appendTail(sb); bibtex = sb.toString(); BibtexParser parser = new BibtexParser(true); BibtexFile file = new BibtexFile(); try { parser.parse(file, new StringReader(bibtex)); } catch (Exception e) { this.logger.error("Error parsing BibTex record."); throw new RuntimeException(e); } PubItemVO itemVO = new PubItemVO(); MdsPublicationVO mds = new MdsPublicationVO(); itemVO.setMetadata(mds); List entries = file.getEntries(); boolean entryFound = false; if (entries == null || entries.size() == 0) { this.logger.warn("No entry found in BibTex record."); throw new RuntimeException(); } for (Object object : entries) { if (object instanceof BibtexEntry) { if (entryFound) { this.logger.error("Multiple entries in BibTex record."); throw new RuntimeException(); } entryFound = true; BibtexEntry entry = (BibtexEntry) object; // genre BibTexUtil.Genre bibGenre; try { bibGenre = BibTexUtil.Genre.valueOf(entry.getEntryType()); } catch (IllegalArgumentException iae) { bibGenre = BibTexUtil.Genre.misc; this.logger.warn("Unrecognized genre: " + entry.getEntryType()); } MdsPublicationVO.Genre itemGenre = BibTexUtil.getGenreMapping().get(bibGenre); mds.setGenre(itemGenre); SourceVO sourceVO = new SourceVO(new TextVO()); SourceVO secondSourceVO = new SourceVO(new TextVO()); Map fields = entry.getFields(); // Mapping of BibTeX Standard Entries // title if (fields.get("title") != null) { if (fields.get("chapter") != null) { mds.setTitle(new TextVO(BibTexUtil.stripBraces( BibTexUtil.bibtexDecode(fields.get("chapter").toString()), false) + " - " + BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("title").toString()), false))); } else { mds.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("title").toString()), false))); } } // booktitle if (fields.get("booktitle") != null) { if (bibGenre == BibTexUtil.Genre.book) { mds.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("booktitle").toString()), false))); } else if (bibGenre == BibTexUtil.Genre.conference || bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.incollection || bibGenre == BibTexUtil.Genre.inproceedings) { sourceVO.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("booktitle").toString()), false))); if (bibGenre == BibTexUtil.Genre.conference || bibGenre == BibTexUtil.Genre.inproceedings) { sourceVO.setGenre(Genre.PROCEEDINGS); } else if (bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.incollection) { sourceVO.setGenre(Genre.BOOK); } } } // fjournal, journal if (fields.get("fjournal") != null) { if (bibGenre == BibTexUtil.Genre.article || bibGenre == BibTexUtil.Genre.misc || bibGenre == BibTexUtil.Genre.unpublished) { sourceVO.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("fjournal").toString()), false))); sourceVO.setGenre(SourceVO.Genre.JOURNAL); if (fields.get("journal") != null) { sourceVO.getAlternativeTitles().add(new TextVO(BibTexUtil.stripBraces( BibTexUtil.bibtexDecode(fields.get("journal").toString()), false))); } } } else if (fields.get("journal") != null) { if (bibGenre == BibTexUtil.Genre.article || bibGenre == BibTexUtil.Genre.misc || bibGenre == BibTexUtil.Genre.unpublished || bibGenre == BibTexUtil.Genre.inproceedings) { sourceVO.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("journal").toString()), false))); sourceVO.setGenre(SourceVO.Genre.JOURNAL); } } // number if (fields.get("number") != null && bibGenre != BibTexUtil.Genre.techreport) { sourceVO.setIssue(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("number").toString()), false)); } else if (fields.get("number") != null && bibGenre == BibTexUtil.Genre.techreport) { { mds.getIdentifiers().add(new IdentifierVO(IdentifierVO.IdType.REPORT_NR, BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("number").toString()), false))); } } // pages if (fields.get("pages") != null) { if (bibGenre == BibTexUtil.Genre.book || bibGenre == BibTexUtil.Genre.proceedings) { mds.setTotalNumberOfPages(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("pages").toString()), false)); } else { BibTexUtil.fillSourcePages(BibTexUtil.stripBraces( BibTexUtil.bibtexDecode(fields.get("pages").toString()), false), sourceVO); if (bibGenre == BibTexUtil.Genre.inproceedings && (fields.get("booktitle") == null || fields.get("booktitle").toString() == "") && (fields.get("event_name") != null && fields.get("event_name").toString() != "")) { sourceVO.setTitle( new TextVO(BibTexUtil.stripBraces(fields.get("event_name").toString(), false))); sourceVO.setGenre(Genre.PROCEEDINGS); } } } // Publishing info PublishingInfoVO publishingInfoVO = new PublishingInfoVO(); mds.setPublishingInfo(publishingInfoVO); // address if (fields.get("address") != null) { if (!(bibGenre == BibTexUtil.Genre.article || bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.inproceedings || bibGenre == BibTexUtil.Genre.conference || bibGenre == BibTexUtil.Genre.incollection) && (sourceVO.getTitle() == null || sourceVO.getTitle().getValue() == null)) { publishingInfoVO.setPlace(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("address").toString()), false)); } else { if (sourceVO.getPublishingInfo() == null) { PublishingInfoVO sourcePublishingInfoVO = new PublishingInfoVO(); sourceVO.setPublishingInfo(sourcePublishingInfoVO); } sourceVO.getPublishingInfo().setPlace(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("address").toString()), false)); } } // edition if (fields.get("edition") != null) { publishingInfoVO.setEdition(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("edition").toString()), false)); } // publisher if (!(bibGenre == BibTexUtil.Genre.article || bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.inproceedings || bibGenre == BibTexUtil.Genre.conference || bibGenre == BibTexUtil.Genre.incollection) && (sourceVO.getTitle() == null || sourceVO.getTitle().getValue() == null)) { if (fields.get("publisher") != null) { publishingInfoVO.setPublisher(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("publisher").toString()), false)); } else if (fields.get("school") != null && (bibGenre == BibTexUtil.Genre.mastersthesis || bibGenre == BibTexUtil.Genre.phdthesis || bibGenre == BibTexUtil.Genre.techreport)) { publishingInfoVO.setPublisher(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("school").toString()), false)); } else if (fields.get("institution") != null) { publishingInfoVO.setPublisher(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("institution").toString()), false)); } else if (fields.get("publisher") == null && fields.get("school") == null && fields.get("institution") == null && fields.get("address") != null) { publishingInfoVO.setPublisher("ANY PUBLISHER"); } } else { if (sourceVO.getPublishingInfo() == null) { PublishingInfoVO sourcePublishingInfoVO = new PublishingInfoVO(); sourceVO.setPublishingInfo(sourcePublishingInfoVO); } if (fields.get("publisher") != null) { sourceVO.getPublishingInfo().setPublisher(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("publisher").toString()), false)); } else if (fields.get("school") != null && (bibGenre == BibTexUtil.Genre.mastersthesis || bibGenre == BibTexUtil.Genre.phdthesis || bibGenre == BibTexUtil.Genre.techreport)) { sourceVO.getPublishingInfo().setPublisher(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("school").toString()), false)); } else if (fields.get("institution") != null) { sourceVO.getPublishingInfo().setPublisher(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("institution").toString()), false)); } else if (fields.get("publisher") == null && fields.get("school") == null && fields.get("institution") == null && fields.get("address") != null) { sourceVO.getPublishingInfo().setPublisher("ANY PUBLISHER"); } } // series if (fields.get("series") != null) { if (bibGenre == BibTexUtil.Genre.book || bibGenre == BibTexUtil.Genre.misc || bibGenre == BibTexUtil.Genre.techreport) { sourceVO.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("series").toString()), false))); sourceVO.setGenre(SourceVO.Genre.SERIES); } else if (bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.incollection || bibGenre == BibTexUtil.Genre.inproceedings || bibGenre == BibTexUtil.Genre.conference) { secondSourceVO.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("series").toString()), false))); secondSourceVO.setGenre(SourceVO.Genre.SERIES); } } // type --> degree if (fields.get("type") != null && bibGenre == BibTexUtil.Genre.mastersthesis) { if (fields.get("type").toString().toLowerCase().contains("master") || fields.get("type").toString().toLowerCase().contains("m.a.") || fields.get("type").toString().toLowerCase().contains("m.s.") || fields.get("type").toString().toLowerCase().contains("m.sc.")) { mds.setDegree(MdsPublicationVO.DegreeType.MASTER); } else if (fields.get("type").toString().toLowerCase().contains("bachelor")) { mds.setDegree(MdsPublicationVO.DegreeType.BACHELOR); } else if (fields.get("type").toString().toLowerCase().contains("magister")) { mds.setDegree(MdsPublicationVO.DegreeType.MAGISTER); } else if (fields.get("type").toString().toLowerCase().contains("diplom")) // covers also the english // version (diploma) { mds.setDegree(MdsPublicationVO.DegreeType.DIPLOMA); } else if (fields.get("type").toString().toLowerCase().contains("statsexamen") || fields.get("type").toString().toLowerCase().contains("state examination")) { mds.setDegree(MdsPublicationVO.DegreeType.DIPLOMA); } } else if (fields.get("type") != null && bibGenre == BibTexUtil.Genre.phdthesis) { if (fields.get("type").toString().toLowerCase().contains("phd") || fields.get("type").toString().toLowerCase().contains("dissertation") || fields.get("type").toString().toLowerCase().contains("doktor") || fields.get("type").toString().toLowerCase().contains("doctor")) { mds.setDegree(MdsPublicationVO.DegreeType.PHD); } else if (fields.get("type").toString().toLowerCase().contains("habilitation")) { mds.setDegree(MdsPublicationVO.DegreeType.HABILITATION); } } // volume if (fields.get("volume") != null) { if (bibGenre == BibTexUtil.Genre.article || bibGenre == BibTexUtil.Genre.book) { sourceVO.setVolume(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("volume").toString()), false)); } else if (bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.inproceedings || bibGenre == BibTexUtil.Genre.incollection || bibGenre == BibTexUtil.Genre.conference) { if (sourceVO.getSources() != null && !sourceVO.getSources().isEmpty()) { sourceVO.getSources().get(0).setVolume(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("volume").toString()), false)); } else { sourceVO.setVolume(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("volume").toString()), false)); } } } // event infos if (bibGenre != null && (bibGenre.equals(BibTexUtil.Genre.inproceedings) || bibGenre.equals(BibTexUtil.Genre.proceedings) || bibGenre.equals(BibTexUtil.Genre.conference) || bibGenre.equals(BibTexUtil.Genre.poster) || bibGenre.equals(BibTexUtil.Genre.talk))) { EventVO event = new EventVO(); boolean eventNotEmpty = false; // event location if (fields.get("location") != null) { event.setPlace(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("location").toString()), false))); eventNotEmpty = true; } // event place else if (fields.get("event_place") != null) { event.setPlace(new TextVO(BibTexUtil.stripBraces( BibTexUtil.bibtexDecode(fields.get("event_place").toString()), false))); eventNotEmpty = true; } // event name/title if (fields.get("event_name") != null) { event.setTitle(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("event_name").toString()), false))); eventNotEmpty = true; } // event will be set only it's not empty if (eventNotEmpty == true) { if (event.getTitle() == null) { event.setTitle(new TextVO()); } mds.setEvent(event); } } // year, month String dateString = null; if (fields.get("year") != null) { dateString = BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("year").toString()), false); if (fields.get("month") != null) { String month = BibTexUtil.parseMonth(fields.get("month").toString()); dateString += "-" + month; } if (bibGenre == BibTexUtil.Genre.unpublished) { mds.setDateCreated(dateString); } else { mds.setDatePublishedInPrint(dateString); } } String affiliation = null; String affiliationAddress = null; // affiliation if (fields.get("affiliation") != null) { affiliation = BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("affiliation").toString()), false); } // affiliationaddress if (fields.get("affiliationaddress") != null) { affiliationAddress = BibTexUtil.stripBraces( BibTexUtil.bibtexDecode(fields.get("affiliationaddress").toString()), false); } // author boolean noConeAuthorFound = true; if (fields.get("author") != null) { if (fields.get("author") instanceof BibtexPersonList) { BibtexPersonList authors = (BibtexPersonList) fields.get("author"); for (Object author : authors.getList()) { if (author instanceof BibtexPerson) { addCreator(mds, (BibtexPerson) author, CreatorVO.CreatorRole.AUTHOR, affiliation, affiliationAddress); } else { this.logger.warn("Entry in BibtexPersonList not a BibtexPerson: [" + author + "] in [" + author + "]"); } } } else if (fields.get("author") instanceof BibtexPerson) { BibtexPerson author = (BibtexPerson) fields.get("author"); addCreator(mds, (BibtexPerson) author, CreatorVO.CreatorRole.AUTHOR, affiliation, affiliationAddress); } else if (fields.get("author") instanceof BibtexString) { AuthorDecoder decoder; try { String authorString = BibTexUtil.bibtexDecode(fields.get("author").toString(), false); List<CreatorVO> teams = new ArrayList<CreatorVO>(); if (authorString.contains("Team")) { // set pattern for finding Teams (leaded or followed by [and|,|;|{|}|^|$]) Pattern pattern = Pattern.compile( "(?<=(and|,|;|\\{|^))([\\w|\\s]*?Team[\\w|\\s]*?)(?=(and|,|;|\\}|$))", Pattern.DOTALL); Matcher matcher = pattern.matcher(authorString); String matchedGroup; while (matcher.find()) { matchedGroup = matcher.group(); // remove matchedGroup (and prefix/suffix) from authorString if (authorString.startsWith(matchedGroup)) { authorString = authorString.replaceAll(matchedGroup + "(and|,|;|\\})", ""); } else { authorString = authorString.replaceAll("(and|,|;|\\{)" + matchedGroup, ""); } // set matchedGroup as Organisation Author OrganizationVO team = new OrganizationVO(); team.setName(new TextVO(matchedGroup.trim())); CreatorVO creatorVO = new CreatorVO(team, CreatorVO.CreatorRole.AUTHOR); teams.add(creatorVO); } } decoder = new AuthorDecoder(authorString, false); if (decoder.getBestFormat() != null) { List<Author> authors = decoder.getAuthorListList().get(0); for (Author author : authors) { PersonVO personVO = new PersonVO(); personVO.setFamilyName(author.getSurname()); if (author.getGivenName() != null) { personVO.setGivenName(author.getGivenName()); } else { personVO.setGivenName(author.getInitial()); } /* * Case for MPI-KYB (Biological Cybernetics) with CoNE identifier in brackets and * affiliations to adopt from CoNE for each author (also in brackets) */ if (configuration != null && "true".equals(configuration.get("CoNE")) && ("identifier and affiliation in brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors"))) && (author.getTags().get("identifier") != null)) { String query = author.getTags().get("identifier"); int affiliationsCount = Integer .parseInt(author.getTags().get("affiliationsCount")); if (affiliationsCount > 0 || configuration.get("OrganizationalUnit") != null) { for (int ouCount = 0; ouCount < (affiliationsCount > 0 ? affiliationsCount : 1); ouCount++) // 1 // is // for // the // case // configuration.get("OrganizationalUnit") // != // null { String organizationalUnit = (author.getTags().get( "affiliation" + new Integer(ouCount).toString()) != null ? author.getTags() .get("affiliation" + new Integer(ouCount).toString()) : (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneEntries = null; if (query.equals(author.getTags().get("identifier"))) { coneEntries = Util.queryConeExactWithIdentifier("persons", query, organizationalUnit); // for MPIKYB due to OUs which do not occur in CoNE if (coneEntries.getFirstChild().getFirstChild() == null) { logger.error("No Person with Identifier (" + author.getTags().get("identifier") + ") and OU (" + organizationalUnit + ") found in CoNE for Publication \"" + fields.get("title") + "\""); } } else { coneEntries = Util.queryConeExact("persons", query, organizationalUnit); } Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeAuthorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier( new IdentifierVO(IdType.CONE, coneId)); for (int i = 0; i < coneEntry.getChildNodes() .getLength(); i++) { Node posNode = coneEntry.getChildNodes().item(i); if ("escidoc:position" .equals(posNode.getNodeName())) { String from = null; String until = null; String name = null; String id = null; Node node = posNode.getFirstChild() .getFirstChild(); while (node != null) { if ("eprints:affiliatedInstitution" .equals(node.getNodeName())) { name = node.getFirstChild() .getNodeValue(); } else if ("escidoc:start-date" .equals(node.getNodeName())) { from = node.getFirstChild() .getNodeValue(); } else if ("escidoc:end-date" .equals(node.getNodeName())) { until = node.getFirstChild() .getNodeValue(); } else if ("dc:identifier" .equals(node.getNodeName())) { id = node.getFirstChild() .getNodeValue(); } node = node.getNextSibling(); } if (smaller(from, dateString) && smaller(dateString, until)) { OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(name)); org.setIdentifier(id); personVO.getOrganizations().add(org); } } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } else { throw new RuntimeException("Missing CoNE entry for " + query); } } } } /* * Case for MPI-Microstructure Physics with affiliation identifier in brackets and * affiliations to adopt from CoNE for each author (also in brackets) */ else if (configuration != null && "true".equals(configuration.get("CoNE")) && ("affiliation id in brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors"))) && (author.getTags().get("identifier") != null)) { String identifier = author.getTags().get("identifier"); String query = personVO.getFamilyName() + ", " + personVO.getGivenName(); if (!("extern".equals(identifier))) { Node coneEntries = null; coneEntries = Util.queryConeExact("persons", query, (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeAuthorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier( new IdentifierVO(IdType.CONE, coneId)); if (identifier != null && !("".equals(identifier))) { try { String ouSubTitle = identifier.substring(0, identifier.indexOf(",")); Document document = Util.queryFramework( "/oum/organizational-units?query=" + URLEncoder.encode("\"/title\"=\"" + ouSubTitle + "\"", "UTF-8")); NodeList ouList = document.getElementsByTagNameNS( "http://www.escidoc.de/schemas/organizationalunit/0.8", "organizational-unit"); Element ou = (Element) ouList.item(0); String href = ou.getAttribute("xlink:href"); String ouId = href .substring(href.lastIndexOf("/") + 1); OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(identifier)); org.setIdentifier(ouId); personVO.getOrganizations().add(org); } catch (Exception e) { logger.error("Error getting OUs", e); throw new RuntimeException( "Error getting Organizational Unit for " + identifier); } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } else { throw new RuntimeException("Missing CoNE entry for " + query); } } } else if (configuration != null && "true".equals(configuration.get("CoNE")) && ("empty brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors")) && (author.getTags().get("brackets") != null))) { String query = personVO.getFamilyName() + ", " + personVO.getGivenName(); Node coneEntries = Util.queryConeExact("persons", query, (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeAuthorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier(new IdentifierVO(IdType.CONE, coneId)); for (int i = 0; i < coneEntry.getChildNodes() .getLength(); i++) { Node posNode = coneEntry.getChildNodes().item(i); if ("escidoc:position".equals(posNode.getNodeName())) { String from = null; String until = null; String name = null; String id = null; Node node = posNode.getFirstChild().getFirstChild(); while (node != null) { if ("eprints:affiliatedInstitution" .equals(node.getNodeName())) { name = node.getFirstChild().getNodeValue(); } else if ("escidoc:start-date" .equals(node.getNodeName())) { from = node.getFirstChild().getNodeValue(); } else if ("escidoc:end-date" .equals(node.getNodeName())) { until = node.getFirstChild().getNodeValue(); } else if ("dc:identifier" .equals(node.getNodeName())) { id = node.getFirstChild().getNodeValue(); } node = node.getNextSibling(); } if (smaller(from, dateString) && smaller(dateString, until)) { OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(name)); org.setIdentifier(id); personVO.getOrganizations().add(org); } } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } else { throw new RuntimeException("Missing CoNE entry for " + query); } } else if (configuration != null && "true".equals(configuration.get("CoNE")) && ("no".equals(configuration.get("CurlyBracketsForCoNEAuthors")))) { String query = personVO.getFamilyName() + ", " + personVO.getGivenName(); Node coneEntries = Util.queryConeExact("persons", query, (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeAuthorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier(new IdentifierVO(IdType.CONE, coneId)); for (int i = 0; i < coneEntry.getChildNodes() .getLength(); i++) { Node posNode = coneEntry.getChildNodes().item(i); if ("escidoc:position".equals(posNode.getNodeName())) { String from = null; String until = null; String name = null; String id = null; Node node = posNode.getFirstChild().getFirstChild(); while (node != null) { if ("eprints:affiliatedInstitution" .equals(node.getNodeName())) { name = node.getFirstChild().getNodeValue(); } else if ("escidoc:start-date" .equals(node.getNodeName())) { from = node.getFirstChild().getNodeValue(); } else if ("escidoc:end-date" .equals(node.getNodeName())) { until = node.getFirstChild().getNodeValue(); } else if ("dc:identifier" .equals(node.getNodeName())) { id = node.getFirstChild().getNodeValue(); } node = node.getNextSibling(); } if (smaller(from, dateString) && smaller(dateString, until)) { OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(name)); org.setIdentifier(id); personVO.getOrganizations().add(org); } } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } } /* * Case for MPI-RA (Radio Astronomy) with identifier and affiliation in brackets * This Case is using NO CoNE! */ if (configuration != null && "false".equals(configuration.get("CoNE")) && ("identifier and affiliation in brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors"))) && (author.getTags().get("identifier") != null)) { String identifier = author.getTags().get("identifier"); String authoAffiliation = author.getTags().get("affiliation0"); OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(authoAffiliation)); org.setIdentifier(identifier); personVO.getOrganizations().add(org); } if (affiliation != null) { OrganizationVO organization = new OrganizationVO(); organization.setIdentifier(PropertyReader .getProperty("escidoc.pubman.external.organisation.id")); organization.setName(new TextVO(affiliation)); organization.setAddress(affiliationAddress); personVO.getOrganizations().add(organization); } CreatorVO creatorVO = new CreatorVO(personVO, CreatorVO.CreatorRole.AUTHOR); mds.getCreators().add(creatorVO); } } if (!teams.isEmpty()) { mds.getCreators().addAll(teams); } } catch (Exception e) { this.logger.error("An error occured while getting field 'author'.", e); throw new RuntimeException(e); } } } // editor boolean noConeEditorFound = false; if (fields.get("editor") != null) { this.logger.debug("fields.get(\"editor\"): " + fields.get("editor").getClass()); if (fields.get("editor") instanceof BibtexPersonList) { BibtexPersonList editors = (BibtexPersonList) fields.get("editor"); for (Object editor : editors.getList()) { if (editor instanceof BibtexPerson) { addCreator(mds, (BibtexPerson) editor, CreatorVO.CreatorRole.EDITOR, affiliation, affiliationAddress); } else { this.logger.warn("Entry in BibtexPersonList not a BibtexPerson: [" + editor + "] in [" + editors + "]"); } } } else if (fields.get("editor") instanceof BibtexPerson) { BibtexPerson editor = (BibtexPerson) fields.get("editor"); addCreator(mds, (BibtexPerson) editor, CreatorVO.CreatorRole.EDITOR, affiliation, affiliationAddress); } else if (fields.get("editor") instanceof BibtexString) { AuthorDecoder decoder; try { String editorString = BibTexUtil.bibtexDecode(fields.get("editor").toString(), false); List<CreatorVO> teams = new ArrayList<CreatorVO>(); if (editorString.contains("Team")) { // set pattern for finding Teams (leaded or followed by [and|,|;|{|}|^|$]) Pattern pattern = Pattern.compile( "(?<=(and|,|;|\\{|^))([\\w|\\s]*?Team[\\w|\\s]*?)(?=(and|,|;|\\}|$))", Pattern.DOTALL); Matcher matcher = pattern.matcher(editorString); String matchedGroup; while (matcher.find()) { matchedGroup = matcher.group(); // remove matchedGroup (and prefix/suffix) from authorString if (editorString.startsWith(matchedGroup)) { editorString = editorString.replaceAll(matchedGroup + "(and|,|;|\\})", ""); } else { editorString = editorString.replaceAll("(and|,|;|\\{)" + matchedGroup, ""); } // set matchedGroup as Organisation Author OrganizationVO team = new OrganizationVO(); team.setName(new TextVO(matchedGroup.trim())); CreatorVO creatorVO = new CreatorVO(team, CreatorVO.CreatorRole.EDITOR); teams.add(creatorVO); } } decoder = new AuthorDecoder(editorString, false); if (decoder.getBestFormat() != null) { List<Author> editors = decoder.getAuthorListList().get(0); for (Author editor : editors) { PersonVO personVO = new PersonVO(); personVO.setFamilyName(editor.getSurname()); if (editor.getGivenName() != null) { personVO.setGivenName(editor.getGivenName()); } else { personVO.setGivenName(editor.getInitial()); } /* * Case for MPI-KYB (Biological Cybernetics) with CoNE identifier in brackets and * affiliations to adopt from CoNE for each author (also in brackets) */ if (configuration != null && "true".equals(configuration.get("CoNE")) && ("identifier and affiliation in brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors"))) && (editor.getTags().get("identifier") != null)) { String query = editor.getTags().get("identifier"); int affiliationsCount = Integer .parseInt(editor.getTags().get("affiliationsCount")); if (affiliationsCount > 0 || configuration.get("OrganizationalUnit") != null) { for (int ouCount = 0; ouCount < (affiliationsCount > 0 ? affiliationsCount : 1); ouCount++) // 1 // is // for // the // case // configuration.get("OrganizationalUnit") // != // null { String organizationalUnit = (editor.getTags().get( "affiliation" + new Integer(ouCount).toString()) != null ? editor.getTags() .get("affiliation" + new Integer(ouCount).toString()) : (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneEntries = null; if (query.equals(editor.getTags().get("identifier"))) { coneEntries = Util.queryConeExactWithIdentifier("persons", query, organizationalUnit); // for MPIKYB due to OUs which do not occur in CoNE if (coneEntries.getFirstChild().getFirstChild() == null) { logger.error("No Person with Identifier (" + editor.getTags().get("identifier") + ") and OU (" + organizationalUnit + ") found in CoNE for Publication \"" + fields.get("title") + "\""); } } else { coneEntries = Util.queryConeExact("persons", query, organizationalUnit); } Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeEditorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier( new IdentifierVO(IdType.CONE, coneId)); for (int i = 0; i < coneEntry.getChildNodes() .getLength(); i++) { Node posNode = coneEntry.getChildNodes().item(i); if ("escidoc:position" .equals(posNode.getNodeName())) { String from = null; String until = null; String name = null; String id = null; Node node = posNode.getFirstChild() .getFirstChild(); while (node != null) { if ("eprints:affiliatedInstitution" .equals(node.getNodeName())) { name = node.getFirstChild() .getNodeValue(); } else if ("escidoc:start-date" .equals(node.getNodeName())) { from = node.getFirstChild() .getNodeValue(); } else if ("escidoc:end-date" .equals(node.getNodeName())) { until = node.getFirstChild() .getNodeValue(); } else if ("dc:identifier" .equals(node.getNodeName())) { id = node.getFirstChild() .getNodeValue(); } node = node.getNextSibling(); } if (smaller(from, dateString) && smaller(dateString, until)) { OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(name)); org.setIdentifier(id); personVO.getOrganizations().add(org); } } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } else { throw new RuntimeException("Missing CoNE entry for " + query); } } } } /* * Case for MPI-Microstructure Physics with affiliation identifier in brackets and * affiliations to adopt from CoNE for each author (also in brackets) */ else if (configuration != null && "true".equals(configuration.get("CoNE")) && ("affiliation id in brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors"))) && (editor.getTags().get("identifier") != null)) { String identifier = editor.getTags().get("identifier"); String query = personVO.getFamilyName() + ", " + personVO.getGivenName(); if (!("extern".equals(identifier))) { Node coneEntries = null; coneEntries = Util.queryConeExact("persons", query, (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeAuthorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier( new IdentifierVO(IdType.CONE, coneId)); if (identifier != null && !("".equals(identifier))) { try { String ouSubTitle = identifier.substring(0, identifier.indexOf(",")); Document document = Util.queryFramework( "/oum/organizational-units?query=" + URLEncoder.encode("\"/title\"=\"" + ouSubTitle + "\"", "UTF-8")); NodeList ouList = document.getElementsByTagNameNS( "http://www.escidoc.de/schemas/organizationalunit/0.8", "organizational-unit"); Element ou = (Element) ouList.item(0); String href = ou.getAttribute("xlink:href"); String ouId = href .substring(href.lastIndexOf("/") + 1); OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(identifier)); org.setIdentifier(ouId); personVO.getOrganizations().add(org); } catch (Exception e) { logger.error("Error getting OUs", e); throw new RuntimeException( "Error getting Organizational Unit for " + identifier); } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } else { throw new RuntimeException("Missing CoNE entry for " + query); } } } else if (configuration != null && "true".equals(configuration.get("CoNE")) && ("empty brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors")) && (editor.getTags().get("brackets") != null))) { String query = personVO.getFamilyName() + ", " + personVO.getGivenName(); Node coneEntries = Util.queryConeExact("persons", query, (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeEditorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier(new IdentifierVO(IdType.CONE, coneId)); for (int i = 0; i < coneEntry.getChildNodes() .getLength(); i++) { Node posNode = coneEntry.getChildNodes().item(i); if ("escidoc:position".equals(posNode.getNodeName())) { String from = null; String until = null; String name = null; String id = null; Node node = posNode.getFirstChild().getFirstChild(); while (node != null) { if ("eprints:affiliatedInstitution" .equals(node.getNodeName())) { name = node.getFirstChild().getNodeValue(); } else if ("escidoc:start-date" .equals(node.getNodeName())) { from = node.getFirstChild().getNodeValue(); } else if ("escidoc:end-date" .equals(node.getNodeName())) { until = node.getFirstChild().getNodeValue(); } else if ("dc:identifier" .equals(node.getNodeName())) { id = node.getFirstChild().getNodeValue(); } node = node.getNextSibling(); } if (smaller(from, dateString) && smaller(dateString, until)) { OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(name)); org.setIdentifier(id); personVO.getOrganizations().add(org); } } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } else { throw new RuntimeException("Missing CoNE entry for " + query); } } else if (configuration != null && "true".equals(configuration.get("CoNE")) && ("no".equals(configuration.get("CurlyBracketsForCoNEAuthors")))) { String query = personVO.getFamilyName() + ", " + personVO.getGivenName(); Node coneEntries = Util.queryConeExact("persons", query, (configuration.get("OrganizationalUnit") != null ? configuration.get("OrganizationalUnit") : "")); Node coneNode = coneEntries.getFirstChild().getFirstChild(); if (coneNode != null) { Node currentNode = coneNode.getFirstChild(); boolean first = true; while (currentNode != null) { if (currentNode.getNodeType() == Node.ELEMENT_NODE && first) { first = false; noConeEditorFound = false; Node coneEntry = currentNode; String coneId = coneEntry.getAttributes() .getNamedItem("rdf:about").getNodeValue(); personVO.setIdentifier(new IdentifierVO(IdType.CONE, coneId)); for (int i = 0; i < coneEntry.getChildNodes() .getLength(); i++) { Node posNode = coneEntry.getChildNodes().item(i); if ("escidoc:position".equals(posNode.getNodeName())) { String from = null; String until = null; String name = null; String id = null; Node node = posNode.getFirstChild().getFirstChild(); while (node != null) { if ("eprints:affiliatedInstitution" .equals(node.getNodeName())) { name = node.getFirstChild().getNodeValue(); } else if ("escidoc:start-date" .equals(node.getNodeName())) { from = node.getFirstChild().getNodeValue(); } else if ("escidoc:end-date" .equals(node.getNodeName())) { until = node.getFirstChild().getNodeValue(); } else if ("dc:identifier" .equals(node.getNodeName())) { id = node.getFirstChild().getNodeValue(); } node = node.getNextSibling(); } if (smaller(from, dateString) && smaller(dateString, until)) { OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(name)); org.setIdentifier(id); personVO.getOrganizations().add(org); } } } } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) { throw new RuntimeException( "Ambigous CoNE entries for " + query); } currentNode = currentNode.getNextSibling(); } } } /* * Case for MPI-RA (Radio Astronomy) with identifier and affiliation in brackets * This Case is using NO CoNE! */ if (configuration != null && "false".equals(configuration.get("CoNE")) && ("identifier and affiliation in brackets" .equals(configuration.get("CurlyBracketsForCoNEAuthors"))) && (editor.getTags().get("identifier") != null)) { String identifier = editor.getTags().get("identifier"); String authoAffiliation = editor.getTags().get("affiliation0"); OrganizationVO org = new OrganizationVO(); org.setName(new TextVO(authoAffiliation)); org.setIdentifier(identifier); personVO.getOrganizations().add(org); } if (affiliation != null) { OrganizationVO organization = new OrganizationVO(); organization.setIdentifier(PropertyReader .getProperty("escidoc.pubman.external.organisation.id")); organization.setName(new TextVO(affiliation)); organization.setAddress(affiliationAddress); personVO.getOrganizations().add(organization); } CreatorVO creatorVO = new CreatorVO(personVO, CreatorVO.CreatorRole.EDITOR); if ((bibGenre == BibTexUtil.Genre.article || bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.inproceedings || bibGenre == BibTexUtil.Genre.conference || bibGenre == BibTexUtil.Genre.incollection) && (sourceVO.getTitle() != null || sourceVO.getTitle().getValue() == null)) { sourceVO.getCreators().add(creatorVO); } else { mds.getCreators().add(creatorVO); } } } if (!teams.isEmpty()) { mds.getCreators().addAll(teams); } } catch (Exception e) { this.logger.error("An error occured while getting field 'editor'.", e); throw new RuntimeException(e); } } } // No CoNE Author or Editor Found if (noConeAuthorFound == true && noConeEditorFound == true && configuration != null && "true".equals(configuration.get("CoNE"))) { throw new RuntimeException("No CoNE-Author and no CoNE-Editor was found"); } // If no affiliation is given, set the first author to "external" boolean affiliationFound = false; for (CreatorVO creator : mds.getCreators()) { if (creator.getPerson() != null && creator.getPerson().getOrganizations() != null) { for (OrganizationVO organization : creator.getPerson().getOrganizations()) { if (organization.getIdentifier() != null) { affiliationFound = true; break; } } } } if (!affiliationFound && mds.getCreators().size() > 0) { OrganizationVO externalOrganization = new OrganizationVO(); externalOrganization.setName(new TextVO("External Organizations")); try { externalOrganization.setIdentifier( PropertyReader.getProperty("escidoc.pubman.external.organisation.id")); } catch (Exception e) { throw new RuntimeException("Property escidoc.pubman.external.organisation.id not found", e); } if (mds.getCreators().get(0).getPerson() != null) { mds.getCreators().get(0).getPerson().getOrganizations().add(externalOrganization); } } // Mapping of "common" (maybe relevant), non standard BibTeX Entries // abstract if (fields.get("abstract") != null) { mds.getAbstracts().add(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("abstract").toString()), false))); } // contents if (fields.get("contents") != null) { mds.setTableOfContents(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("contents").toString()), false))); } // isbn if (fields.get("isbn") != null) { if (bibGenre == BibTexUtil.Genre.inproceedings || bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.incollection || bibGenre == BibTexUtil.Genre.conference) { if (sourceVO != null) { sourceVO.getIdentifiers().add(new IdentifierVO(IdentifierVO.IdType.ISBN, BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("isbn").toString()), false))); } } else { mds.getIdentifiers().add(new IdentifierVO(IdentifierVO.IdType.ISBN, BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("isbn").toString()), false))); } } // issn if (fields.get("issn") != null) { if (bibGenre == BibTexUtil.Genre.inproceedings || bibGenre == BibTexUtil.Genre.inbook || bibGenre == BibTexUtil.Genre.incollection || bibGenre == BibTexUtil.Genre.conference) { if (sourceVO.getSources() != null && !sourceVO.getSources().isEmpty()) { sourceVO.getSources().get(0).getIdentifiers() .add(new IdentifierVO(IdentifierVO.IdType.ISSN, BibTexUtil.stripBraces( BibTexUtil.bibtexDecode(fields.get("issn").toString()), false))); } } else if (bibGenre == BibTexUtil.Genre.article) { if (sourceVO != null) { sourceVO.getIdentifiers().add(new IdentifierVO(IdentifierVO.IdType.ISSN, BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("issn").toString()), false))); } } else { mds.getIdentifiers().add(new IdentifierVO(IdentifierVO.IdType.ISSN, BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("issn").toString()), false))); } } // keywords if (fields.get("keywords") != null) { mds.setFreeKeywords(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("keywords").toString()), false))); } // language /* * if (fields.get("language") != null) { * mds.getLanguages().add(BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("language").toString * ()), false)); } */ // subtitle if (fields.get("subtitle") != null) { mds.getAlternativeTitles().add(new TextVO(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("subtitle").toString()), false))); } // url is now mapped to locator if (fields.get("url") != null) { // mds.getIdentifiers().add( // new IdentifierVO( // IdentifierVO.IdType.URI, // BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("url").toString()), false))); FileVO locator = new FileVO(); locator.setContent( BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("url").toString()), false)); locator.setName("Link"); locator.setStorage(FileVO.Storage.EXTERNAL_URL); locator.setVisibility(FileVO.Visibility.PUBLIC); locator.setContentCategory( "http://purl.org/escidoc/metadata/ves/content-categories/any-fulltext"); MdsFileVO metadata = new MdsFileVO(); metadata.setContentCategory( "http://purl.org/escidoc/metadata/ves/content-categories/any-fulltext"); metadata.setTitle(new TextVO("Link")); locator.getMetadataSets().add(metadata); itemVO.getFiles().add(locator); } // web_url as URI-Identifier else if (fields.get("web_url") != null) { mds.getIdentifiers().add(new IdentifierVO(IdentifierVO.IdType.URI, BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("web_url").toString()), false))); } // Prevent the creation of an empty source if (sourceVO.getTitle() != null && sourceVO.getTitle().getValue() != null && sourceVO.getTitle().getValue() != "" && sourceVO.getGenre() != null) { mds.getSources().add(sourceVO); // Prevent the creation of an empty second if (sourceVO.getSources() != null && !sourceVO.getSources().isEmpty() && sourceVO.getSources().get(0) != null && sourceVO.getSources().get(0).getTitle() != null && sourceVO.getSources().get(0).getTitle().getValue() != null && sourceVO.getSources().get(0).getTitle().getValue() != "") { mds.getSources().add(sourceVO.getSources().get(0)); } } // Prevent the creation of an empty second source if (secondSourceVO.getTitle() != null && secondSourceVO.getTitle().getValue() != null && secondSourceVO.getTitle().getValue() != "" && secondSourceVO.getGenre() != null) { mds.getSources().add(secondSourceVO); // Prevent the creation of an empty second if (secondSourceVO.getSources() != null && !secondSourceVO.getSources().isEmpty() && secondSourceVO.getSources().get(0) != null && secondSourceVO.getSources().get(0).getTitle() != null && secondSourceVO.getSources().get(0).getTitle().getValue() != null && secondSourceVO.getSources().get(0).getTitle().getValue() != "") { mds.getSources().add(secondSourceVO.getSources().get(0)); } } // New mapping for MPIS // DOI if (fields.get("doi") != null) { mds.getIdentifiers().add(new IdentifierVO(IdentifierVO.IdType.DOI, BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("doi").toString()), false))); } // eid if (fields.get("eid") != null) { if (mds.getSources().size() == 1) { mds.getSources().get(0).setSequenceNumber(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("eid").toString()), false)); } } // rev if (fields.get("rev") != null) { if ("Peer".equals( BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("rev").toString()), false))) { mds.setReviewMethod(ReviewMethod.PEER); } else if ("No review".equals( BibTexUtil.stripBraces(BibTexUtil.bibtexDecode(fields.get("rev").toString()), false))) { mds.setReviewMethod(ReviewMethod.NO_REVIEW); } } // MPG-Affil if (fields.get("MPG-Affil") != null) { if ("Peer".equals(BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("MPG-Affil").toString()), false))) { // TODO } } // MPIS Groups if (fields.get("group") != null) { String[] groups = BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("group").toString()), false).split(","); for (String group : groups) { group = group.trim(); if (!"".equals(group)) { if (groupSet == null) { try { groupSet = loadGroupSet(); } catch (Exception e) { throw new RuntimeException(e); } } if (!groupSet.contains(group)) { throw new RuntimeException("Group '" + group + "' not found."); } mds.getSubjects() .add(new TextVO(group, null, SubjectClassification.MPIS_GROUPS.toString())); } } } // MPIS Projects if (fields.get("project") != null) { String[] projects = BibTexUtil .stripBraces(BibTexUtil.bibtexDecode(fields.get("project").toString()), false) .split(","); for (String project : projects) { project = project.trim(); if (!"".equals(project)) { if (projectSet == null) { try { projectSet = loadProjectSet(); } catch (Exception e) { throw new RuntimeException(e); } } if (!projectSet.contains(project)) { throw new RuntimeException("Project '" + project + "' not found."); } mds.getSubjects() .add(new TextVO(project, null, SubjectClassification.MPIS_PROJECTS.toString())); } } } // Cite Key mds.getIdentifiers().add(new IdentifierVO(IdType.BIBTEX_CITEKEY, entry.getEntryKey())); } else if (object instanceof BibtexToplevelComment) { this.logger.debug("Comment found: " + ((BibtexToplevelComment) object).getContent()); } } XmlTransforming xmlTransforming = new XmlTransformingBean(); try { if (entryFound) { return xmlTransforming.transformToItem(itemVO); } else { this.logger.warn("No entry found in BibTex record."); throw new RuntimeException(); } } catch (TechnicalException e) { this.logger.error("An error ocurred while transforming the item."); throw new RuntimeException(e); } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * Extracts all question information from a questionnaire form given as XML document. * Information is returned as a JSONObject of the following form: * //from w ww . j a v a 2 s . c om * {<QuestionID1>:<QuestionInfo1>,...}, where * <QuestionInfoN> is again a JSONObject with the following fields: * * name: name of the question (all) * * required: is an answer required or optional? (all) * * type: question type (one of qu:OrdinalScaleQuestionPageType, qu:DichotomousQuestionPageType, qu:FreeTextQuestionPageType) * * defval: default value (only for ordinal scale and dichotomous) * * min/maxvalue: minimum/maximum value (only for ordinal scale) * * min/maxlabel: label for minimum/maximum value (only for dichotomous and ordinal scale) * * @param questionnaireDocument * @return */ private JSONObject extractQuestionInformation(Document questionnaireDocument) { JSONObject questions = new JSONObject(); NodeList nodeList = questionnaireDocument.getElementsByTagNameNS(MOBSOS_QUESTIONNAIRE_NS, "Page"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; if (e.getAttribute("xsi:type").endsWith("QuestionPageType")) { JSONObject question = new JSONObject(); String qtype = e.getAttribute("xsi:type"); String required = e.getAttribute("required"); if (required == null || required.equals("false")) { question.put("required", 0); } else if (required != null && required.equals("true")) { question.put("required", 1); } question.put("name", e.getAttribute("name")); question.put("type", e.getAttribute("xsi:type")); if ("qu:OrdinalScaleQuestionPageType".equals(qtype) || "qu:DichotomousQuestionPageType".equals(qtype)) { //question.put("defval",Integer.parseInt(e.getAttribute("defval"))); question.put("minlabel", e.getAttribute("minlabel")); question.put("maxlabel", e.getAttribute("maxlabel")); if ("qu:OrdinalScaleQuestionPageType".equals(qtype)) { question.put("minval", Integer.parseInt(e.getAttribute("minval"))); question.put("maxval", Integer.parseInt(e.getAttribute("maxval"))); } } questions.put(e.getAttribute("qid"), question); } } } return questions; }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * TODO: write documentation//from ww w . ja v a2 s . c o m * @param id * @return */ @GET @Produces(MediaType.TEXT_HTML) @Path("surveys/{id}/questionnaire") @Summary("Download questionnaire form for given survey. Enables response submission.") @Notes("Can be used with or without authentication, including response submission.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Survey questionnaire HTML representation."), @ApiResponse(code = 400, message = "Survey questionnaire form invalid. Cause: ..."), @ApiResponse(code = 404, message = "Questionnaire does not exist. <b>-or-</b> Survey questionnaire not set. <b>-or-</b> Survey questionnaire does not define form.") }) public HttpResponse getSurveyQuestionnaireFormHTML( @HeaderParam(name = "accept-language", defaultValue = "") String lang, @PathParam("id") int id) { String onAction = "downloading questionnaire form for survey " + id; try { // if survey does not exist, return 404. if (checkExistenceOwnership(id, 0) == -1) { HttpResponse result = new HttpResponse("Survey does not exist!"); result.setStatus(404); return result; } } catch (Exception e1) { return internalError(onAction); } Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; String formXml; // ----------------- try { // retrieve survey data; if survey does not exist, return 404. HttpResponse r = getSurvey(id); if (200 != r.getStatus()) { System.err.println(r.getResult()); return r; } JSONObject survey = (JSONObject) JSONValue.parse(r.getResult()); // check if survey has the questionnaire id field qid set. If not, return not found. if (null == survey.get("qid")) { HttpResponse result = new HttpResponse("Questionnaire not set for survey " + id + "."); result.setStatus(404); return result; } // if questionnaire was found, download questionnaire form long qid = (Long) survey.get("qid"); try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("select form from " + jdbcSchema + ".questionnaire where id = ?"); stmt.setLong(1, qid); ResultSet rs = stmt.executeQuery(); // if no form was uploaded for questionnaire, respond to user with not found if (!rs.isBeforeFirst()) { HttpResponse result = new HttpResponse("Form for questionnaire " + qid + " does not exist!"); result.setStatus(404); return result; } rs.next(); formXml = rs.getString(1); } catch (SQLException | UnsupportedOperationException e) { return internalError(onAction); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } } // adapt form template to concrete survey and user String adaptedFormXml = adaptForm(formXml, survey, (UserAgent) this.getActiveAgent(), null); //String adaptedFormXml = formXml; Document form; // before returning form, make sure it's still valid (may be obsolete step...) try { form = validateQuestionnaireData(adaptedFormXml); } catch (IOException e) { e.printStackTrace(); return internalError(onAction); } catch (SAXException e) { e.printStackTrace(); HttpResponse result = new HttpResponse("Questionnaire form is invalid! Cause: " + e.getMessage()); result.setStatus(400); return result; } // now start to transform XML into ready-to-use HTML // start off with template String html = new Scanner(new File("./etc/html/survey-form-template.html")).useDelimiter("\\A").next(); // fill in placeholders html = fillPlaceHolder(html, "EP_URL", epUrl); html = fillPlaceHolder(html, "SC_URL", staticContentUrl); html = fillPlaceHolder(html, "OIDC_PROV_NAME", oidcProviderName); html = fillPlaceHolder(html, "OIDC_PROV_LOGO", oidcProviderLogo); html = fillPlaceHolder(html, "OIDC_PROV_URL", oidcProviderUrl); html = fillPlaceHolder(html, "OIDC_CLNT_ID", oidcClientId); // do all adaptation to user and survey String adaptHtml = adaptForm(html, survey, (UserAgent) this.getActiveAgent(), null); adaptHtml = i18n(adaptHtml, lang); //String adaptText = text; // add HTML elements for all questionnaire items accordingly Vector<String> qpages = new Vector<String>(); Vector<String> navpills = new Vector<String>(); NodeList nodeList = form.getElementsByTagNameNS(MOBSOS_QUESTIONNAIRE_NS, "Page"); // then iterate over all question pages for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; // set first page and navpill item to active String active = ""; if (i == 0) { active = " class='active'"; } // differentiate between possible item types and add HTML accordingly if (e.getAttribute("xsi:type").endsWith("InformationPageType")) { // first add navpill item String navpill = "\t\t\t\t\t<li" + active + "><a href=\"#step-" + i + "\"><span class=\"list-group-item-heading\">" + i + "</span></a></li>\n"; navpills.add(navpill); // then add information page String qpage = "\t\t<div class=\"row setup-content\" id=\"step-" + i + "\"><div class=\"col-xs-12\"><div class=\"col-md-12 well text-center\">\n"; String name = e.getAttribute("name"); qpage += "\t\t\t<h4><b>" + name + "</b></h4>\n"; String instr = escapeHtml4(e.getElementsByTagNameNS(MOBSOS_QUESTIONNAIRE_NS, "Instructions") .item(0).getTextContent().trim()); qpage += "\t\t\t<p>\n\t\t\t\t" + instr + "\n" + "\t\t\t</p>\n"; qpage += "\t\t</div></div></div>\n"; qpages.add(qpage); } else if (e.getAttribute("xsi:type").endsWith("QuestionPageType")) { // first add nav pill item String navpill = "\t\t\t\t\t<li" + active + "><a href=\"#step-" + i + "\"><span class=\"list-group-item-heading\">" + i + "</span></a></li>\n"; navpills.add(navpill); // then add question page String qpage = "\t\t<div class=\"row setup-content\" id=\"step-" + i + "\"><div class=\"col-xs-12\"><div class=\"col-md-12 text-center\">\n"; String name = e.getAttribute("name"); String quid = e.getAttribute("qid"); qpage += "\t\t\t<h4><b>" + name + " (" + quid + ")</b></h4>\n"; String instr = escapeHtml4(e.getElementsByTagNameNS(MOBSOS_QUESTIONNAIRE_NS, "Instructions") .item(0).getTextContent().trim()); String cssClass = "question"; if (e.getAttribute("required") != null && e.getAttribute("required").equals("true")) { cssClass += " required"; instr += " (<i>" + i18n("${required}", lang) + "</i>)"; } qpage += "\t\t\t<div class=\"" + cssClass + "\" style='text-align: justify;'>" + instr + "</div><p/>\n"; String qtype = e.getAttribute("xsi:type"); if ("qu:OrdinalScaleQuestionPageType".equals(qtype)) { // TODO: do something with default value, if set. //int defval = Integer.parseInt(e.getAttribute("defval")); String minlabel = escapeHtml4(e.getAttribute("minlabel")); String maxlabel = escapeHtml4(e.getAttribute("maxlabel")); int minval = Integer.parseInt(e.getAttribute("minval")); int maxval = Integer.parseInt(e.getAttribute("maxval")); // do UI in a button style (not really nice in terms of responsive design) /* qpage += "\t\t\t<div class=\"btn-group\" data-toggle=\"buttons\">\n"; qpage += "\t\t\t\t<span class=\"btn\">" + minlabel + "</span>\n"; for(int k=minval;k<=maxval;k++){ qpage += "\t\t\t\t<label class=\"btn btn-primary\">\n"; qpage += "\t\t\t\t\t<input name=\""+ quid + "\" type=\"radio\" value=\""+k + "\">" + k + "\n"; qpage += "\t\t\t\t</label>\n"; } qpage += "\t\t\t\t<span class=\"btn\">" + maxlabel + "</span>\n"; qpage += "\t\t\t</div>\n"; */ // --- end UI button style // do UI in range slider style (better responsive design) /* <div class="row well"> <input class="col-md-12 col-xs-12 scale" name="SQ.N.1" type="range" min="1" max="7" step="1" list="SQ.N.1-scale"/><br> <datalist id="SQ.N.1-scale"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> </datalist> <span class="col-md-4 col-xs-4">Totally disagree</span><span name="SQ.N.1" class="col-md-4 col-xs-4 text-center h4 response scale-response alert" data-toggle="tooltip" data-placement="left" title="Click to reset to n/a.">n/a</span> <span class="col-md-4 col-xs-4 pull-right text-right">Totally agree</span> </div>*/ qpage += "\t\t\t<div class='row well'>\n"; qpage += "\t\t\t\t<input class='col-md-12 col-xs-12 scale' name='" + quid + "' type='range' min='" + minval + "' max='" + maxval + "' step='1' list='" + quid.replace(".", "-") + "-scale'/><br>\n"; qpage += "\t\t\t\t<datalist id='" + quid.replace(".", "-") + "-scale'>\n"; for (int k = minval; k <= maxval; k++) { qpage += "\t\t\t\t\t<option>" + k + "</option>\n"; } qpage += "\t\t\t\t</datalist>"; qpage += "<span class='col-md-4 col-xs-5 text-left'>" + minlabel + "</span><span name='" + quid + "' class='col-md-4 col-xs-2 text-center h2 response scale-response' data-toggle='tooltip' data-placement='left' title='Click to reset to n/a.'>n/a</span> <span class='col-md-4 col-xs-5 pull-right text-right'>" + maxlabel + "</span>"; qpage += "\t\t\t</div>\n"; // --- end UI range slider style } else if ("qu:FreeTextQuestionPageType".equals(qtype)) { qpage += "\t\t\t<textarea name=\"" + quid + "\" class=\"form-control response freetext-response\" rows=\"3\"></textarea>\n"; } qpage += "\t\t</div></div></div>\n"; qpages.add(qpage); } } } // now that all questions are extracted and transformed to HTML, append nav pill items and question pages to final HTML. // first serialize nav pill items String navpillItems = ""; for (int j = 0; j < navpills.size(); j++) { navpillItems += navpills.get(j); } // then serialize question page divs String questionDivs = ""; for (int j = 0; j < qpages.size(); j++) { questionDivs += qpages.get(j); } // then generate answer link URL answerUrl = new URL(epUrl + "surveys/" + id + "/answers"); String answerLink = "<a href=\"" + answerUrl + "\" id=\"return-url\" class=\"hidden\" ></a>"; // finally insert all generated parts into the resulting adapted HTML adaptHtml = adaptHtml.replaceAll("<!-- NAVPILLS -->", navpillItems); adaptHtml = adaptHtml.replaceAll("<!-- QUESTIONPAGES -->", questionDivs); adaptHtml = adaptHtml.replaceAll("<!-- ANSWERLINK -->", answerLink); // return adapted HTML HttpResponse result = new HttpResponse(adaptHtml); result.setStatus(200); return result; } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } }
From source file:nl.b3p.viewer.stripes.SldActionBean.java
private void addFilterToExistingSld() throws Exception { Filter f = CQL.toFilter(filter); f = (Filter) f.accept(new ChangeMatchCase(false), null); if (featureTypeName == null) { featureTypeName = layer;/*from w w w. jav a 2 s. c om*/ } FeatureTypeConstraint ftc = sldFactory.createFeatureTypeConstraint(featureTypeName, f, new Extent[] {}); if (newSld == null) { SLDTransformer sldTransformer = new SLDTransformer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); sldTransformer.transform(ftc, bos); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document sldXmlDoc = db.parse(new ByteArrayInputStream(sldXml)); Document ftcDoc = db.parse(new ByteArrayInputStream(bos.toByteArray())); String sldVersion = sldXmlDoc.getDocumentElement().getAttribute("version"); if ("1.1.0".equals(sldVersion)) { // replace sld:FeatureTypeName element generated by GeoTools // by se:FeatureTypeName NodeList sldFTNs = ftcDoc.getElementsByTagNameNS(NS_SLD, "FeatureTypeName"); if (sldFTNs.getLength() == 1) { Node sldFTN = sldFTNs.item(0); Node seFTN = ftcDoc.createElementNS(NS_SE, "FeatureTypeName"); seFTN.setTextContent(sldFTN.getTextContent()); sldFTN.getParentNode().replaceChild(seFTN, sldFTN); } } // Ignore namespaces to tackle both SLD 1.0.0 and SLD 1.1.0 // Add constraint to all NamedLayers, not only to the layer specified // in layers parameter NodeList namedLayers = sldXmlDoc.getElementsByTagNameNS(NS_SLD, "NamedLayer"); for (int i = 0; i < namedLayers.getLength(); i++) { Node namedLayer = namedLayers.item(i); // Search where to insert the FeatureTypeConstraint from our ftcDoc // Insert LayerFeatureConstraints after sld:Name, se:Name or se:Description // and before sld:NamedStyle or sld:UserStyle so search backwards. // If we find an existing LayerFeatureConstraints, use that NodeList childs = namedLayer.getChildNodes(); Node insertBefore = null; Node layerFeatureConstraints = null; int j = childs.getLength() - 1; do { Node child = childs.item(j); if ("LayerFeatureConstraints".equals(child.getLocalName())) { layerFeatureConstraints = child; break; } if ("Description".equals(child.getLocalName()) || "Name".equals(child.getLocalName())) { break; } insertBefore = child; j--; } while (j >= 0); Node featureTypeConstraint = sldXmlDoc.adoptNode(ftcDoc.getDocumentElement().cloneNode(true)); if (layerFeatureConstraints == null) { layerFeatureConstraints = sldXmlDoc.createElementNS(NS_SLD, "LayerFeatureConstraints"); layerFeatureConstraints.appendChild(featureTypeConstraint); namedLayer.insertBefore(layerFeatureConstraints, insertBefore); } else { layerFeatureConstraints.appendChild(featureTypeConstraint); } } TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(sldXmlDoc); bos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(bos); t.transform(source, result); sldXml = bos.toByteArray(); } }
From source file:nl.clockwork.mule.ebms.cxf.EbMSSecSignatureInInterceptor.java
@Override public void handleMessage(SoapMessage message) throws Fault { try {//from w w w . j a v a 2s. co m KeyStore keyStore = SecurityUtils.loadKeyStore(keyStorePath, keyStorePassword); XMLStreamReader reader = message.getContent(XMLStreamReader.class); Document document = StaxUtils.read(reader); XMLStreamReader copy = StaxUtils.createXMLStreamReader(document); message.setContent(XMLStreamReader.class, copy); List<EbMSDataSource> dataSources = new ArrayList<EbMSDataSource>(); if (message.getAttachments() != null) for (Attachment attachment : message.getAttachments()) dataSources.add(new EbMSDataSource(attachment.getDataHandler().getDataSource(), attachment.getId(), attachment.getDataHandler().getName())); NodeList signatureNodeList = document.getElementsByTagNameNS( org.apache.xml.security.utils.Constants.SignatureSpecNS, org.apache.xml.security.utils.Constants._TAG_SIGNATURE); if (signatureNodeList.getLength() > 0) { boolean isValid = false; X509Certificate certificate = getCertificate(document); if (certificate != null) { isValid = validateCertificate(keyStore, certificate, new Date()/*TODO get date from message???*/); if (!isValid) logger.info("Certificate invalid."); else { isValid = verify(certificate, signatureNodeList, dataSources); logger.info("Signature" + (isValid ? " " : " in") + "valid."); } } SignatureManager.set(new Signature(certificate, XMLMessageBuilder.getInstance(SignatureType.class).handle(signatureNodeList.item(0)), isValid)); } else SignatureManager.set(null); } catch (Exception e) { throw new Fault(e); } }
From source file:nl.clockwork.mule.ebms.cxf.XMLDSignatureInInterceptor.java
private boolean verify(Document document, List<EbMSDataSource> dataSources) throws MarshalException, XMLSignatureException { NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nodeList.getLength() > 0) { XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(); DOMValidateContext validateContext = new DOMValidateContext(new XMLDSigKeySelector(), nodeList.item(0)); URIDereferencer dereferencer = new EbMSDataSourceURIDereferencer(dataSources); validateContext.setURIDereferencer(dereferencer); XMLSignature signature = signFactory.unmarshalXMLSignature(validateContext); return signature.validate(validateContext); }/*from ww w . ja v a 2s .c om*/ return true; }
From source file:nl.clockwork.mule.ebms.cxf.XMLSecSignatureInInterceptor.java
private boolean verify(KeyStore keyStore, Document document, List<EbMSDataSource> dataSources) throws XMLSignatureException, XMLSecurityException, CertificateExpiredException, CertificateNotYetValidException, KeyStoreException { NodeList nodeList = document.getElementsByTagNameNS(org.apache.xml.security.utils.Constants.SignatureSpecNS, org.apache.xml.security.utils.Constants._TAG_SIGNATURE); if (nodeList.getLength() > 0) { XMLSignature signature = new XMLSignature((Element) nodeList.item(0), org.apache.xml.security.utils.Constants.SignatureSpecNS); EbMSDataSourceResolver resolver = new EbMSDataSourceResolver(dataSources); signature.addResourceResolver(resolver); X509Certificate certificate = signature.getKeyInfo().getX509Certificate(); if (certificate != null) { certificate.checkValidity(); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { try { Certificate c = keyStore.getCertificate(aliases.nextElement()); certificate.verify(c.getPublicKey()); return signature.checkSignatureValue(certificate); } catch (KeyStoreException e) { throw e; } catch (Exception e) { }/*from w w w. j a v a 2s . co m*/ } } else { PublicKey publicKey = signature.getKeyInfo().getPublicKey(); if (publicKey != null) return signature.checkSignatureValue(publicKey); } return false; } return true; }
From source file:org.alfresco.web.forms.xforms.Schema2XForms.java
private static String extractPropertyFromAnnotation(final String namespace, final String elementName, final XSAnnotation annotation, final ResourceBundle resourceBundle) { if (annotation == null) { return null; }//from www . j a va 2 s . co m // write annotation to empty doc final Document doc = XMLUtil.newDocument(); annotation.writeAnnotation(doc, XSAnnotation.W3C_DOM_DOCUMENT); final NodeList d = doc.getElementsByTagNameNS(namespace, elementName); if (d.getLength() == 0) { return null; } if (d.getLength() > 1) { LOGGER.warn("[extractPropertyFromAnnotation] expected exactly one value for " + namespace + ":" + elementName + ". found " + d.getLength()); } String result = DOMUtil.getTextNodeAsString(d.item(0)); if (LOGGER.isDebugEnabled()) LOGGER.debug(namespace + ":" + elementName + " = " + result); if (result.startsWith("${") && result.endsWith("}") && resourceBundle != null) { result = result.substring("${".length(), result.length() - "}".length()); if (LOGGER.isDebugEnabled()) LOGGER.debug("[extractPropertyFromAnnotation] looking up key " + result + " in bundle " + resourceBundle); try { result = resourceBundle.getString(result); } catch (MissingResourceException mse) { if (LOGGER.isDebugEnabled()) LOGGER.debug("[extractPropertyFromAnnotation] unable to find key " + result, mse); result = "$$" + result + "$$"; } } return result; }
From source file:org.alfresco.web.forms.xforms.Schema2XForms.java
private void createTriggersForRepeats(final Document xformsDocument, final Element rootGroup) { if (LOGGER.isDebugEnabled()) LOGGER.debug("[createTriggersForRepeats] start"); final HashMap<String, Element> bindIdToBind = new HashMap<String, Element>(); final NodeList binds = xformsDocument.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "bind"); for (int i = 0; i < binds.getLength(); i++) { final Element b = (Element) binds.item(i); bindIdToBind.put(b.getAttributeNS(null, "id"), b); }//from w ww.j ava 2s .c o m final NodeList repeats = xformsDocument.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "repeat"); final HashMap<Element, Element> bindToRepeat = new HashMap<Element, Element>(); for (int i = 0; i < repeats.getLength(); i++) { Element r = (Element) repeats.item(i); if (LOGGER.isDebugEnabled()) LOGGER.debug("[createTriggersForRepeats] processing repeat " + r.getAttributeNS(null, "id")); Element bind = bindIdToBind.get(r.getAttributeNS(NamespaceConstants.XFORMS_NS, "bind")); bindToRepeat.put(bind, r); String xpath = ""; do { if (xpath.length() != 0) { xpath = '/' + xpath; } if (LOGGER.isDebugEnabled()) LOGGER.debug("[createTriggersForRepeats] walking bind " + bind.getAttributeNS(null, "id")); String s = bind.getAttributeNS(NamespaceConstants.XFORMS_NS, "nodeset"); s = s.replaceAll("^([^\\[]+).*$", "$1"); if (bindToRepeat.containsKey(bind) && !r.equals(bindToRepeat.get(bind))) { s += "[index(\'" + bindToRepeat.get(bind).getAttributeNS(null, "id") + "\')]"; } xpath = s + xpath; bind = ((NamespaceConstants.XFORMS_PREFIX + ":bind").equals(bind.getParentNode().getNodeName()) ? (Element) bind.getParentNode() : null); } while (bind != null); this.createTriggersForRepeat(xformsDocument, rootGroup, r.getAttributeNS(null, "id"), xpath, r.getAttributeNS(NamespaceConstants.XFORMS_NS, "bind")); } }
From source file:org.alfresco.web.forms.xforms.XFormsBean.java
private static void rewriteInlineURIs(final Document schemaDocument, final String cwdAvmPath) { final NodeList nl = XMLUtil.combine( schemaDocument.getElementsByTagNameNS(NamespaceConstants.XMLSCHEMA_NS, "include"), schemaDocument.getElementsByTagNameNS(NamespaceConstants.XMLSCHEMA_NS, "import")); if (LOGGER.isDebugEnabled()) LOGGER.debug("rewriting " + nl.getLength() + " includes"); for (int i = 0; i < nl.getLength(); i++) { final Element includeEl = (Element) nl.item(i); if (includeEl.hasAttribute("schemaLocation")) { String uri = includeEl.getAttribute("schemaLocation"); String finalURI = null; if (uri == null || uri.startsWith("http://") || uri.startsWith("https://")) { if (LOGGER.isDebugEnabled()) LOGGER.debug("not rewriting " + uri); continue; }/*www .j a va 2 s . co m*/ if (uri.startsWith("webscript://")) { // It's a web script include / import final FacesContext facesContext = FacesContext.getCurrentInstance(); final ExternalContext externalContext = facesContext.getExternalContext(); final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); final String baseURI = (request.getScheme() + "://" + request.getServerName() + ':' + request.getServerPort() + request.getContextPath() + "/wcservice"); String rewrittenURI = uri; if (uri.contains("${storeid}")) { final String storeId = AVMUtil.getStoreName(cwdAvmPath); rewrittenURI = uri.replace("${storeid}", storeId); } else if (uri.contains("{storeid}")) { final String storeId = AVMUtil.getStoreName(cwdAvmPath); rewrittenURI = uri.replace("{storeid}", storeId); } else { if (LOGGER.isDebugEnabled()) LOGGER.debug("no store id specified in webscript URI " + uri); } if (uri.contains("${ticket}")) { AuthenticationService authenticationService = Repository.getServiceRegistry(facesContext) .getAuthenticationService(); final String ticket = authenticationService.getCurrentTicket(); rewrittenURI = rewrittenURI.replace("${ticket}", ticket); } else if (uri.contains("{ticket}")) { AuthenticationService authenticationService = Repository.getServiceRegistry(facesContext) .getAuthenticationService(); final String ticket = authenticationService.getCurrentTicket(); rewrittenURI = rewrittenURI.replace("{ticket}", ticket); } else { if (LOGGER.isDebugEnabled()) LOGGER.debug("no ticket specified in webscript URI " + uri); } rewrittenURI = rewrittenURI.replaceAll("%26", "&"); finalURI = baseURI + rewrittenURI.replace("webscript://", "/"); if (LOGGER.isDebugEnabled()) LOGGER.debug("Final URI " + finalURI); } else { // It's a web project asset include / import final String baseURI = (uri.charAt(0) == '/' ? AVMUtil.getPreviewURI(AVMUtil.getStoreName(cwdAvmPath)) : AVMUtil.getPreviewURI(cwdAvmPath)); finalURI = baseURI + uri; } if (LOGGER.isDebugEnabled()) LOGGER.debug("rewriting " + uri + " as " + finalURI); includeEl.setAttribute("schemaLocation", finalURI); } } }