file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
MCRFieldTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRFieldTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import java.util.Collections; import java.util.List; import java.util.Locale; import org.jaxen.JaxenException; import org.jdom2.Element; import org.mycore.common.MCRException; import org.mycore.common.xml.MCRNodeBuilder; import bibtex.dom.BibtexAbstractValue; import bibtex.dom.BibtexEntry; /** * Transforms a single BibTeX field to a MODS element. * * @author Frank Lützenkirchen */ class MCRFieldTransformer { static final String AS_NEW_ELEMENT = "[999]"; protected String field; MCRFieldTransformer(String field) { this.field = field; } String getField() { return field; } /** Converts german umlauts and other special LaTeX characters */ protected String normalizeValue(String value) { return value.replaceAll("\\s+", " ").trim().replace("{\\\"a}", "\u00e4").replace("{\\\"o}", "\u00f6") .replace("{\\\"u}", "\u00fc").replace("{\\\"A}", "\u00c4").replace("{\\\"O}", "\u00d6") .replace("{\\\"U}", "\u00dc").replace("{\\ss}", "\u00df").replace("\\\"a", "\u00e4") .replace("\\\"o", "\u00f6").replace("\\\"u", "\u00fc").replace("\\\"A", "\u00c4") .replace("\\\"O", "\u00d6").replace("\\\"U", "\u00dc").replace("{\\'a}", "\u00e1") .replace("{\\'e}", "\u00e9").replace("{\\'i}", "\u00ed").replace("{\\'o}", "\u00f3") .replace("{\\'u}", "\u00fa").replace("{\\`a}", "\u00e0").replace("{\\`e}", "\u00e8") .replace("{\\`i}", "\u00ec").replace("{\\`o}", "\u00f2").replace("{\\`u}", "\u00f9") .replace("{\\'\\i}", "\u00ed").replace("{\\`\\i}", "\u00ec").replace("{", "").replace("}", "") .replace("---", "-").replace("--", "-"); } void transformField(BibtexEntry entry, Element parent) { for (BibtexAbstractValue value : getFieldValues(entry, field)) { buildField(value, parent); } } private List<BibtexAbstractValue> getFieldValues(BibtexEntry entry, String field) { List<BibtexAbstractValue> fieldValues = entry.getFieldValuesAsList(field); if (fieldValues == null) { fieldValues = entry.getFieldValuesAsList(field.toUpperCase(Locale.ROOT)); } return fieldValues == null ? Collections.emptyList() : fieldValues; } void buildField(BibtexAbstractValue value, Element parent) { String type = value.getClass().getSimpleName(); MCRMessageLogger.logMessage("Field " + field + " returns unsupported abstract value of type " + type, parent); } static Element buildElement(String xPath, String content, Element parent) { try { return new MCRNodeBuilder().buildElement(xPath, content, parent); } catch (JaxenException ex) { throw new MCRException("Unable to build field " + xPath, ex); } } }
3,589
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPagesTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRPagesTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import org.jdom2.Element; import org.mycore.mods.MCRMODSPagesHelper; import bibtex.dom.BibtexAbstractValue; import bibtex.dom.BibtexString; /** * Transforms a BibTeX pages field to a JDOM mods:extent element containing pages info. * * @author Frank Lützenkirchen */ class MCRPagesTransformer extends MCRField2XPathTransformer { MCRPagesTransformer() { super("pages", "mods:relatedItem[@type='host']/mods:part"); } void buildField(BibtexAbstractValue value, Element parent) { String pages = ((BibtexString) value).getContent(); pages = normalizeValue(pages); Element part = buildElement(xPath, null, parent); part.addContent(MCRMODSPagesHelper.buildExtentPages(pages)); } }
1,498
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRYearTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRYearTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jdom2.Element; import bibtex.dom.BibtexAbstractValue; import bibtex.dom.BibtexString; /** * Transforms a BibTeX year field to a JDOM mods:dateIssued element. * * @author Frank Lützenkirchen */ class MCRYearTransformer extends MCRField2XPathTransformer { private static final Pattern YEAR_PATTERN = Pattern.compile(".*(\\d{4}).*"); MCRYearTransformer() { super("year", "mods:originInfo/mods:dateIssued[@encoding='w3cdtf']"); } void buildField(BibtexAbstractValue value, Element parent) { String content = ((BibtexString) value).getContent(); content = normalizeValue(content); String year = getFourDigitYear(content); if (year != null) { buildElement(xPath, year, parent); } else { MCRMessageLogger.logMessage("Field year: No 4-digit year found: " + content, parent); } } private String getFourDigitYear(String text) { Matcher m = YEAR_PATTERN.matcher(text); return m.matches() ? m.group(1) : null; } }
1,873
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRGenreTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRGenreTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import java.util.Locale; import java.util.Objects; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import bibtex.dom.BibtexEntry; /** * Transforms the BibTeX entry type to mods:genre element(s). * * @author Frank Lützenkirchen */ class MCRGenreTransformer { static void setGenre(BibtexEntry entry, Element mods) { String type = entry.getEntryType().toLowerCase(Locale.ROOT); MCRFieldTransformer.buildElement("mods:genre", type, mods); } static void fixHostGenre(BibtexEntry entry, Element mods) { String type = entry.getEntryType().toLowerCase(Locale.ROOT); if (Objects.equals(type, "incollection") || Objects.equals(type, "inproceedings") || Objects.equals(type, "inbook")) { type = type.substring(2); Element genre = getHostGenre(mods); if (genre != null) { genre.setText(type); } else { MCRFieldTransformer.buildElement("mods:relatedItem[@type='host']/mods:genre", type, mods); } } } private static Element getHostGenre(Element mods) { XPathExpression<Element> expr = XPathFactory.instance().compile("mods:relatedItem[@type='host']/mods:genre", Filters.element(), null, MCRConstants.getStandardNamespaces()); return expr.evaluateFirst(mods); } }
2,244
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAndOthersTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRAndOthersTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import org.jdom2.Element; import bibtex.dom.BibtexPerson; /** * Transforms the BibTeX "and others" suffix in author/editor fields to a JDOM mods:etAl element. * * @author Frank Lützenkirchen */ class MCRAndOthersTransformer extends MCRPersonTransformer { MCRAndOthersTransformer(String field, String role) { super(field, role); } void buildField(BibtexPerson person, Element parent) { Element modsName = buildElement(xPath, null, parent); buildElement("mods:etAl", null, modsName); } }
1,295
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersonListTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRPersonListTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import bibtex.dom.BibtexAbstractValue; import bibtex.dom.BibtexPerson; import bibtex.dom.BibtexPersonList; /** * Transforms a BibTeX field containing author/editor names to multiple JDOM mods:name elements. * * @author Frank Lützenkirchen */ class MCRPersonListTransformer extends MCRFieldTransformer { private static final Logger LOGGER = LogManager.getLogger(MCRPersonListTransformer.class); private MCRPersonTransformer personTransformer; private MCRAndOthersTransformer andOthers; MCRPersonListTransformer(String field, String role) { super(field); this.personTransformer = new MCRPersonTransformer(field, role); this.andOthers = new MCRAndOthersTransformer(field, role); } @SuppressWarnings("unchecked") void buildField(BibtexAbstractValue value, Element parent) { if (!(value instanceof BibtexPersonList personList)) { LOGGER.error("Cannot not cast {} ({}) to {}", BibtexAbstractValue.class.getName(), value, BibtexPersonList.class.getName()); return; } for (BibtexPerson person : (List<BibtexPerson>) (personList.getList())) { (person.isOthers() ? andOthers : personTransformer).buildField(person, parent); } } }
2,166
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUnsupportedFieldTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRUnsupportedFieldTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.jdom2.Element; import bibtex.dom.BibtexAbstractValue; import bibtex.dom.BibtexEntry; import bibtex.dom.BibtexString; /** * Transforms any BibTeX field that can not be mapped to MODS to a mods:extension/field element. * * @author Frank Lützenkirchen */ class MCRUnsupportedFieldTransformer extends MCRFieldTransformer { Set<String> supportedFields = new HashSet<>(); MCRUnsupportedFieldTransformer(Collection<MCRFieldTransformer> supportedTransformers) { super("*"); determineSupportedFields(supportedTransformers); } private void determineSupportedFields(Collection<MCRFieldTransformer> supportedTransformers) { for (MCRFieldTransformer transformer : supportedTransformers) { supportedFields.add(transformer.getField()); } } private boolean isUnsupported(String field) { return !supportedFields.contains(field); } void transformField(BibtexEntry entry, Element parent) { for (String field : (entry.getFields().keySet())) { if (isUnsupported(field)) { this.field = field; super.transformField(entry, parent); } } } void buildField(BibtexAbstractValue value, Element parent) { MCRMessageLogger.logMessage("Field " + field + " is unsupported: " + value.toString().replaceAll("\\s+", " ")); String xPath = "mods:extension/field[@name='" + field + "']" + MCRFieldTransformer.AS_NEW_ELEMENT; String content = ((BibtexString) value).getContent(); content = normalizeValue(content); buildElement(xPath, content, parent); } }
2,487
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBibTeXEntryTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRBibTeXEntryTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import java.util.ArrayList; import java.util.List; import org.jdom2.Element; import org.mycore.common.MCRConstants; import bibtex.dom.BibtexEntry; /** * Transforms a single BibTeX entry to a JDOM mods:mods element. * * @author Frank Lützenkirchen */ class MCRBibTeXEntryTransformer { private static final String XPATH_HOST = "mods:relatedItem[@type='host']"; private List<MCRFieldTransformer> fieldTransformers = new ArrayList<>(); MCRBibTeXEntryTransformer() { fieldTransformers .add(new MCRField2XPathTransformer("document_type", "mods:genre" + MCRFieldTransformer.AS_NEW_ELEMENT)); fieldTransformers.add(new MCRField2XPathTransformer("title", "mods:titleInfo" + MCRFieldTransformer.AS_NEW_ELEMENT + "/mods:title")); fieldTransformers .add(new MCRMoveToRelatedItemIfExists("mods:titleInfo", new MCRField2XPathTransformer("subtitle", "mods:subTitle"))); fieldTransformers.add(new MCRPersonListTransformer("author", "aut")); fieldTransformers.add(new MCRField2XPathTransformer("journal", XPATH_HOST + "[mods:genre='journal']/mods:titleInfo/mods:title")); fieldTransformers.add(new MCRField2XPathTransformer("booktitle", XPATH_HOST + "[mods:genre='collection']/mods:titleInfo/mods:title")); fieldTransformers .add(new MCRMoveToRelatedItemIfExists(XPATH_HOST, new MCRPersonListTransformer("editor", "edt"))); fieldTransformers.add(new MCRMoveToRelatedItemIfExists(XPATH_HOST, new MCRField2XPathTransformer("edition", "mods:originInfo/mods:edition"))); fieldTransformers.add(new MCRMoveToRelatedItemIfExists(XPATH_HOST, new MCRField2XPathTransformer("howpublished", "mods:originInfo/mods:edition"))); fieldTransformers.add(new MCRMoveToRelatedItemIfExists(XPATH_HOST, new MCRField2XPathTransformer("publisher", "mods:originInfo/mods:publisher"))); fieldTransformers.add(new MCRMoveToRelatedItemIfExists(XPATH_HOST, new MCRField2XPathTransformer("address", "mods:originInfo/mods:place/mods:placeTerm[@type='text']"))); fieldTransformers.add( new MCRMoveToRelatedItemIfExists(XPATH_HOST + "[mods:genre='collection']", new MCRYearTransformer())); fieldTransformers.add(new MCRMoveToRelatedItemIfExists( XPATH_HOST + "[mods:genre='journal']|descendant::mods:relatedItem[@type='series']", new MCRField2XPathTransformer("volume", "mods:part/mods:detail[@type='volume']/mods:number"))); fieldTransformers.add(new MCRField2XPathTransformer("number", XPATH_HOST + "/mods:part/mods:detail[@type='issue']/mods:number")); fieldTransformers.add(new MCRField2XPathTransformer("issue", XPATH_HOST + "/mods:part/mods:detail[@type='issue']/mods:number")); fieldTransformers.add(new MCRPagesTransformer()); fieldTransformers.add(new MCRMoveToRelatedItemIfExists(XPATH_HOST, new MCRField2XPathTransformer("isbn", "mods:identifier[@type='isbn']" + MCRFieldTransformer.AS_NEW_ELEMENT))); fieldTransformers.add(new MCRMoveToRelatedItemIfExists(XPATH_HOST, new MCRField2XPathTransformer("series", "mods:relatedItem[@type='series']/mods:titleInfo/mods:title"))); fieldTransformers.add(new MCRMoveToRelatedItemIfExists( XPATH_HOST + "[mods:genre='journal']|descendant::mods:relatedItem[@type='series']", new MCRField2XPathTransformer("issn", "mods:identifier[@type='issn']" + MCRFieldTransformer.AS_NEW_ELEMENT))); fieldTransformers.add(new MCRField2XPathTransformer("doi", "mods:identifier[@type='doi']" + MCRFieldTransformer.AS_NEW_ELEMENT)); fieldTransformers.add(new MCRField2XPathTransformer("urn", "mods:identifier[@type='urn']" + MCRFieldTransformer.AS_NEW_ELEMENT)); fieldTransformers.add( new MCRField2XPathTransformer("url", "mods:location/mods:url" + MCRFieldTransformer.AS_NEW_ELEMENT)); fieldTransformers.add(new MCRField2XPathTransformer("keywords", "mods:subject" + MCRFieldTransformer.AS_NEW_ELEMENT + "/mods:topic")); fieldTransformers.add(new MCRField2XPathTransformer("author_keywords", "mods:subject" + MCRFieldTransformer.AS_NEW_ELEMENT + "/mods:topic")); fieldTransformers .add(new MCRField2XPathTransformer("abstract", "mods:abstract" + MCRFieldTransformer.AS_NEW_ELEMENT)); fieldTransformers.add(new MCRField2XPathTransformer("note", "mods:note" + MCRFieldTransformer.AS_NEW_ELEMENT)); fieldTransformers.add(new MCRField2XPathTransformer("type", "mods:note" + MCRFieldTransformer.AS_NEW_ELEMENT)); fieldTransformers.add(new MCRField2XPathTransformer("source", "mods:recordInfo/mods:recordOrigin")); fieldTransformers.add(new MCRField2XPathTransformer("annote", "mods:note")); fieldTransformers.add(new MCRField2XPathTransformer("pagetotal", "mods:physicalDescription/mods:extent")); fieldTransformers.add(new MCRUnsupportedFieldTransformer(fieldTransformers)); } Element transform(BibtexEntry entry) { Element mods = new Element("mods", MCRConstants.MODS_NAMESPACE); MCRGenreTransformer.setGenre(entry, mods); transformFields(entry, mods); MCRGenreTransformer.fixHostGenre(entry, mods); Element extension = getExtension(mods); extension.addContent(buildSourceExtension(entry)); return mods; } private Element getExtension(Element mods) { Element extension = mods.getChild("extension", MCRConstants.MODS_NAMESPACE); if (extension == null) { extension = new Element("extension", MCRConstants.MODS_NAMESPACE); mods.addContent(extension); } return extension; } private Element buildSourceExtension(BibtexEntry entry) { Element source = new Element("source"); source.setAttribute("format", "bibtex"); source.setText(entry.toString()); return source; } private void transformFields(BibtexEntry entry, Element mods) { for (MCRFieldTransformer transformer : fieldTransformers) { transformer.transformField(entry, mods); } } }
7,089
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersonTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRPersonTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import org.jdom2.Element; import bibtex.dom.BibtexPerson; /** * Transforms a BibTeX person name to a JDOM mods:name element. * * @author Frank Lützenkirchen */ class MCRPersonTransformer extends MCRFieldTransformer { protected String xPath; MCRPersonTransformer(String field, String role) { super(field); this.xPath = "mods:name[@type='personal'][mods:role/mods:roleTerm[@type='code'][@authority='marcrelator']='" + role + "']" + MCRFieldTransformer.AS_NEW_ELEMENT; } void buildField(BibtexPerson person, Element parent) { Element modsName = buildElement(xPath, null, parent); String lastName = normalizeValue(person.getLast()); buildElement("mods:namePart[@type='family']", lastName, modsName); String firstName = getFirstName(person); if (!firstName.isEmpty()) { buildElement("mods:namePart[@type='given']", firstName, modsName); } String lineage = person.getLineage(); if (lineage != null) { buildElement("mods:namePart[@type='termsOfAddress']", lineage, modsName); } } private String getFirstName(BibtexPerson person) { StringBuilder first = new StringBuilder(); if (person.getFirst() != null) { first.append(person.getFirst()); } if (person.getPreLast() != null) { first.append(' ').append(person.getPreLast()); } return normalizeValue(first.toString().trim()); } }
2,269
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBibTeXFileTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/bibtex/MCRBibTeXFileTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.bibtex; import org.jdom2.Element; import org.mycore.common.MCRConstants; import bibtex.dom.BibtexEntry; import bibtex.dom.BibtexFile; import bibtex.expansions.CrossReferenceExpander; import bibtex.expansions.Expander; import bibtex.expansions.ExpansionException; import bibtex.expansions.MacroReferenceExpander; import bibtex.expansions.PersonListExpander; /** * Transforms a BibTeX file to a JDOM mods:modsCollection. * * @author Frank Lützenkirchen */ class MCRBibTeXFileTransformer { private Element collection = new Element("modsCollection", MCRConstants.MODS_NAMESPACE); Element transform(BibtexFile file) { expandReferences(file); MCRBibTeXEntryTransformer transformer = new MCRBibTeXEntryTransformer(); for (Object obj : file.getEntries()) { if (obj instanceof BibtexEntry entry) { if (entry.getFields().isEmpty()) { MCRMessageLogger.logMessage("Skipping entry of type " + entry.getEntryType() + ", has no fields", collection); } else { collection.addContent(transformer.transform(entry)); } } } return collection; } private void expandReferences(BibtexFile file) { expand(new MacroReferenceExpander(true, true, false, false), file); expand(new CrossReferenceExpander(false), file); expand(new PersonListExpander(true, true, false), file); } private void expand(Expander expander, BibtexFile file) { try { expander.expand(file); } catch (ExpansionException ex) { MCRMessageLogger.logMessage(ex.toString(), collection); } for (Exception ex : expander.getExceptions()) { MCRMessageLogger.logMessage(ex.toString(), collection); } } }
2,608
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSGenreCondition.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/access/facts/condition/MCRMODSGenreCondition.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.access.facts.condition; import java.util.List; import java.util.Optional; import org.jdom2.Element; import org.mycore.access.facts.MCRFactsHolder; import org.mycore.access.facts.condition.fact.MCRStringCondition; import org.mycore.access.facts.fact.MCRObjectIDFact; import org.mycore.access.facts.fact.MCRStringFact; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.mods.MCRMODSWrapper; /** * condition for fact-based access system, * that checks if a certain mods:genre is set. * * TODO Could probably be replaced with a more generic XPathCondition. * * @author Robert Stephan * */ public class MCRMODSGenreCondition extends MCRStringCondition { private static final String XPATH_COLLECTION = "mods:genre[contains(@valueURI,'/mir_genres#')]"; private String idFact = "objid"; @Override public void parse(Element xml) { super.parse(xml); this.idFact = Optional.ofNullable(xml.getAttributeValue("idfact")).orElse("objid"); } @Override public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) { Optional<MCRObjectIDFact> idc = facts.require(idFact); if (idc.isPresent()) { Optional<MCRObject> optMCRObject = idc.get().getObject(); if (optMCRObject.isPresent()) { MCRMODSWrapper wrapper = new MCRMODSWrapper(optMCRObject.get()); List<Element> e = wrapper.getElements(XPATH_COLLECTION); if ((e != null) && !(e.isEmpty())) { String value = e.get(0).getAttributeValue("valueURI").split("#")[1]; if (value.equals(getTerm())) { MCRStringFact fact = new MCRStringFact(getFactName(), getTerm()); fact.setValue(value); facts.add(fact); return Optional.of(fact); } } } } return Optional.empty(); } }
2,718
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSEmbargoCondition.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/access/facts/condition/MCRMODSEmbargoCondition.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.access.facts.condition; import java.util.Optional; import org.jdom2.Element; import org.mycore.access.facts.MCRFactsHolder; import org.mycore.access.facts.condition.fact.MCRStringCondition; import org.mycore.access.facts.fact.MCRObjectIDFact; import org.mycore.access.facts.fact.MCRStringFact; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.mods.MCRMODSEmbargoUtils; /** * condition for fact-based access system, that checks * if an embargo exists for a given MyCoRe object * * @author Robert Stephan * */ public class MCRMODSEmbargoCondition extends MCRStringCondition { private String idFact = "objid"; @Override public void parse(Element xml) { super.parse(xml); this.idFact = Optional.ofNullable(xml.getAttributeValue("idfact")).orElse("objid"); } @Override public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) { Optional<MCRObjectIDFact> idc = facts.require(idFact); if (idc.isPresent()) { Optional<MCRObject> optMCRObject = idc.get().getObject(); if (optMCRObject.isPresent()) { String embargo = MCRMODSEmbargoUtils.getEmbargo(optMCRObject.get()); //only positive facts are added to the facts holder if (embargo != null) { MCRStringFact fact = new MCRStringFact(getFactName(), getTerm()); fact.setValue(embargo); facts.add(fact); return Optional.of(fact); } } } return Optional.empty(); } }
2,351
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSCollectionCondition.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/access/facts/condition/MCRMODSCollectionCondition.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.access.facts.condition; import java.util.List; import java.util.Optional; import org.jdom2.Element; import org.mycore.access.facts.MCRFactsHolder; import org.mycore.access.facts.condition.fact.MCRStringCondition; import org.mycore.access.facts.fact.MCRObjectIDFact; import org.mycore.access.facts.fact.MCRStringFact; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.mods.MCRMODSWrapper; /** * condition for fact-based access system, that * checks if a certain value of the collection condition is set for the given object * * TODO Could probably be replaced with a more generic XPathCondition. * * @author Robert Stephan * */ public class MCRMODSCollectionCondition extends MCRStringCondition { private static final String XPATH_COLLECTION = "mods:classification[contains(@valueURI,'/collection#')]"; private String idFact = "objid"; @Override public void parse(Element xml) { super.parse(xml); this.idFact = Optional.ofNullable(xml.getAttributeValue("idfact")).orElse("objid"); } @Override public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) { Optional<MCRObjectIDFact> idc = facts.require(idFact); if (idc.isPresent()) { Optional<MCRObject> optMCRObject = idc.get().getObject(); if (optMCRObject.isPresent()) { MCRMODSWrapper wrapper = new MCRMODSWrapper(optMCRObject.get()); List<Element> e = wrapper.getElements(XPATH_COLLECTION); if ((e != null) && !(e.isEmpty())) { String value = e.get(0).getAttributeValue("valueURI").split("#")[1]; if (value.equals(getTerm())) { MCRStringFact fact = new MCRStringFact(getFactName(), getTerm()); fact.setValue(value); facts.add(fact); return Optional.of(fact); } } } } return Optional.empty(); } }
2,775
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRSSFeedImporter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/rss/MCRRSSFeedImporter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.rss; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.SolrDocumentList; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.filter.ElementFilter; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.MCRMailer; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.xml.MCRURIResolver; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mods.MCRMODSWrapper; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrUtils; import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.FeedException; import com.rometools.rome.io.SyndFeedInput; import com.rometools.rome.io.XmlReader; /** * Reads an RSS feed referencing new publications and imports those publications that are not stored yet. * * Usage: * MCRRSSFeedImporter.importFromFeed( [sourceSystemID], [targetProjectID] ); * where targetProjectID is the target project ID to import mods objects to, e.g. "mir". * * Reads the RSS feed configured via * MCR.MODS.RSSFeedImporter.[sourceSystemID].FeedURL=[http(s) URL of remote RSS feed to read] * * For each entry, * * 1. Gets the link given in that entry (assuming it points to the publications) and * extracts the publication ID from the link, using a regular expression configured via * MCR.MODS.RSSFeedImporter.[sourceSystemID].Pattern2FindID= * * 2. Queries the SOLR index to check if this publication isn't already stored. The field to query is * MCR.MODS.RSSFeedImporter.[sourceSystemID].Field2QueryID=[SOLR field name] * * 3. Retrieves the publication metadata from the remote system and converts it to &lt;mycoreobject /&gt; XML. * MCR.MODS.RSSFeedImporter.[sourceSystemID].PublicationURI=xslStyle:...:http://...{0}... * where the remote publication ID will be replaced in Java message format syntax as {0}. * * 4. Saves the publication in persistent store, with the given projectID and object type "mods". * * When the total number of publications imported is &gt; 0 AND the property * MCR.MODS.RSSFeedImporter.[sourceSystemID].XSL2BuildNotificationMail=foo.xsl * is set, builds and sends a notification mail via MCRMailer. * * @author Frank Lützenkirchen */ public class MCRRSSFeedImporter { private String sourceSystemID; private String feedURL; private Pattern pattern2findID; private String field2queryID; private String importURI; private String xsl2BuildNotificationMail; private static final String STATUS_FLAG = "imported"; private static final String PROPERTY_MAIL_ADDRESS = "MCR.Mail.Address"; private static final Logger LOGGER = LogManager.getLogger(MCRRSSFeedImporter.class); public static void importFromFeed(String sourceSystemID, String projectID) throws Exception { MCRRSSFeedImporter importer = new MCRRSSFeedImporter(sourceSystemID); importer.importPublications(projectID); } public MCRRSSFeedImporter(String sourceSystemID) { this.sourceSystemID = sourceSystemID; String prefix = "MCR.MODS.RSSFeedImporter." + sourceSystemID + "."; feedURL = MCRConfiguration2.getStringOrThrow(prefix + "FeedURL"); importURI = MCRConfiguration2.getStringOrThrow(prefix + "PublicationURI"); field2queryID = MCRConfiguration2.getStringOrThrow(prefix + "Field2QueryID"); xsl2BuildNotificationMail = MCRConfiguration2.getString(prefix + "XSL2BuildNotificationMail").orElse(null); getPattern2FindID(prefix); } private void getPattern2FindID(String prefix) { String patternProperty = prefix + "Pattern2FindID"; try { String pattern = MCRConfiguration2.getStringOrThrow(patternProperty); pattern2findID = Pattern.compile(pattern); } catch (PatternSyntaxException ex) { String msg = "Regular expression syntax error: " + patternProperty; throw new MCRConfigurationException(msg, ex); } } public void importPublications(String projectID) throws Exception { LOGGER.info("Getting new publications from {} RSS feed...", sourceSystemID); SyndFeed feed = retrieveFeed(); List<MCRObject> importedObjects = new ArrayList<>(); for (SyndEntry entry : feed.getEntries()) { MCRObject importedObject = handleFeedEntry(entry, projectID); if (importedObject != null) { importedObjects.add(importedObject); } } int numPublicationsImported = importedObjects.size(); LOGGER.info("imported {} publications.", numPublicationsImported); if ((numPublicationsImported > 0) && (xsl2BuildNotificationMail != null)) { sendNotificationMail(importedObjects); } } private SyndFeed retrieveFeed() throws IOException, FeedException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder().uri(URI.create(feedURL)).build(); HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); try (InputStream resIS = response.body(); XmlReader feedReader = new XmlReader(resIS)) { SyndFeedInput input = new SyndFeedInput(); return input.build(feedReader); } } private MCRObject handleFeedEntry(SyndEntry entry, String projectID) throws MCRPersistenceException, MCRAccessException { String publicationID = getPublicationID(entry); if (publicationID == null) { return null; } if (isAlreadyStored(publicationID)) { LOGGER.info("publication with ID {} already existing, will not import.", publicationID); return null; } LOGGER.info("publication with ID {} does not exist yet, retrieving data...", publicationID); Element publicationXML = retrieveAndConvertPublication(publicationID); if (shouldIgnore(publicationXML)) { LOGGER.info("publication will be ignored, do not store."); return null; } MCRObject obj = buildMCRObject(publicationXML, projectID); MCRMetadataManager.create(obj); return obj; } private String getPublicationID(SyndEntry entry) { String link = entry.getLink(); if (link == null) { LOGGER.warn("no link found in feed entry"); return null; } link = link.trim(); Matcher m = pattern2findID.matcher(link); if (m.matches()) { return m.group(1); } else { LOGGER.warn("no publication ID found in link {}", link); return null; } } private boolean isAlreadyStored(String publicationID) { SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); SolrQuery query = new SolrQuery(); query.setQuery(field2queryID + ":" + MCRSolrUtils.escapeSearchValue(publicationID)); query.setRows(0); SolrDocumentList results; try { results = solrClient.query(query).getResults(); return (results.getNumFound() > 0); } catch (Exception ex) { throw new MCRException(ex); } } private Element retrieveAndConvertPublication(String externalID) { String uri = new MessageFormat(importURI, Locale.ROOT).format(new String[] { externalID }); return MCRURIResolver.instance().resolve(uri); } /** If mods:genre was not mapped by conversion/import function, ignore this publication and do not import */ private static boolean shouldIgnore(Element publication) { return !publication.getDescendants(new ElementFilter("genre", MCRConstants.MODS_NAMESPACE)).hasNext(); } private MCRObject buildMCRObject(Element publicationXML, String projectID) { MCRObject obj = new MCRObject(new Document(publicationXML)); MCRMODSWrapper wrapper = new MCRMODSWrapper(obj); wrapper.setServiceFlag("status", STATUS_FLAG); MCRObjectID oid = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(projectID, "mods"); obj.setId(oid); return obj; } private void sendNotificationMail(List<MCRObject> importedObjects) throws Exception { Element xml = new Element(STATUS_FLAG).setAttribute("source", this.sourceSystemID); for (MCRObject obj : importedObjects) { xml.addContent(obj.createXML().detachRootElement()); } HashMap<String, String> parameters = new HashMap<>(); parameters.put(PROPERTY_MAIL_ADDRESS, MCRConfiguration2.getStringOrThrow(PROPERTY_MAIL_ADDRESS)); MCRMailer.sendMail(new Document(xml), xsl2BuildNotificationMail, parameters); } }
10,441
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) Classes for mapping of MODS elements and MyCoRe classification. */ package org.mycore.mods.classification;
874
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAuthorityAndCode.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRAuthorityAndCode.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.w3c.dom.Element; /** * Authority information that is represented by authority ID and code value. Such authority info comes from a * standardized vocabulary registered at the Library of Congress. * * @author Frank Lützenkirchen */ class MCRAuthorityAndCode extends MCRAuthorityInfo { private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); private static final Logger LOGGER = LogManager.getLogger(MCRAuthorityAndCode.class); /** * xml:lang value of category or classification <label> for MODS @authority. */ public static final String LABEL_LANG_AUTHORITY = "x-auth"; /** The authority code */ private String authority; /** The value code */ private String code; /** * Inspects the attributes in the given MODS XML element and returns the AuthorityInfo given there. */ public static MCRAuthorityAndCode getAuthorityInfo(org.jdom2.Element modsElement) { String authority = modsElement.getAttributeValue("authority"); String type = modsElement.getAttributeValue("type"); String code = modsElement.getTextTrim(); return getAuthorityInfo(authority, type, code); } /** * Inspects the attributes in the given MODS XML element and returns the AuthorityInfo given there. */ public static MCRAuthorityAndCode getAuthorityInfo(Element modsElement) { String authority = modsElement.getAttribute("authority"); String type = modsElement.getAttribute("type"); String code = MCRMODSClassificationSupport.getText(modsElement).trim(); return getAuthorityInfo(authority, type, code); } /** * Builds the authority info from the given values, does some checks on the values. * * @return the authority info, or null if the values are illegal or unsupported. */ private static MCRAuthorityAndCode getAuthorityInfo(String authority, String type, String code) { if (authority == null) { return null; } if (Objects.equals(type, "text")) { LOGGER.warn("Type 'text' is currently unsupported when resolving a classification category"); return null; } return new MCRAuthorityAndCode(authority, code); } /** * Returns the authority code for the given classification */ protected static String getAuthority(MCRCategory classification) { return getLabel(classification, LABEL_LANG_AUTHORITY, null); } MCRAuthorityAndCode(String authority, String code) { this.authority = authority; this.code = code; } @Override public String toString() { return authority + "#" + code; } @Override protected MCRCategoryID lookupCategoryID() { return DAO .getCategoriesByLabel(LABEL_LANG_AUTHORITY, authority) .stream() .findFirst() .map(c -> new MCRCategoryID(c.getId().getRootID(), code)) .orElse(null); } @Override public void setInElement(org.jdom2.Element element) { element.setAttribute("authority", authority); element.setText(code); } @Override public void setInElement(Element element) { element.setAttribute("authority", authority); element.setTextContent(code); } }
4,478
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMODSClassificationSupport.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRMODSClassificationSupport.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import java.net.URISyntaxException; import java.text.MessageFormat; import java.util.Locale; import javax.xml.parsers.DocumentBuilder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.xml.MCRDOMUtils; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author Thomas Scheffler (yagee) * @author Frank Lützenkirchen */ public final class MCRMODSClassificationSupport { private static final Logger LOGGER = LogManager.getLogger(MCRMODSClassificationSupport.class); private MCRMODSClassificationSupport() { } /** * For a category ID, looks up the authority information for that category and returns the attributes in the given * MODS element so that it represents that category. This is used as a Xalan extension. */ public static NodeList getClassNodes(final NodeList sources) { if (sources.getLength() == 0) { LOGGER.warn("Cannot get first element of node list 'sources'."); return null; } DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked(); try { Document document = documentBuilder.newDocument(); final Element source = (Element) sources.item(0); final String categId = source.getAttributeNS(MCRConstants.MCR_NAMESPACE.getURI(), "categId"); final MCRCategoryID categoryID = MCRCategoryID.fromString(categId); final Element returns = document.createElementNS(source.getNamespaceURI(), source.getLocalName()); MCRClassMapper.assignCategory(returns, categoryID); return returns.getChildNodes(); } catch (Throwable e) { LOGGER.warn("Error in Xalan Extension", e); return null; } finally { MCRDOMUtils.releaseDocumentBuilder(documentBuilder); } } public static NodeList getMCRClassNodes(final NodeList sources) { if (sources.getLength() == 0) { LOGGER.warn("Cannot get first element of node list 'sources'."); return null; } DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked(); try { final Document document = documentBuilder.newDocument(); final Element source = (Element) sources.item(0); MCRCategoryID category = MCRClassMapper.getCategoryID(source); if (category == null) { return null; } final Element returns = document.createElement("returns"); returns.setAttributeNS(MCRConstants.MCR_NAMESPACE.getURI(), "mcr:categId", category.toString()); return returns.getChildNodes(); } catch (Throwable e) { LOGGER.warn("Error in Xalan Extension", e); return null; } finally { MCRDOMUtils.releaseDocumentBuilder(documentBuilder); } } public static String getClassCategLink(final NodeList sources) { if (sources.getLength() == 0) { LOGGER.warn("Cannot get first element of node list 'sources'."); return ""; } final Element source = (Element) sources.item(0); MCRCategoryID category = MCRClassMapper.getCategoryID(source); if (category == null) { return ""; } String id; try { id = MCRXMLFunctions.encodeURIPath(category.getId()); } catch (URISyntaxException e) { /* This should be impossible! */ throw new MCRException(e); } return new MessageFormat("classification:metadata:0:children:{0}:{1}", Locale.ROOT).format( new Object[] { category.getRootID(), id }); } public static String getClassCategParentLink(final NodeList sources) { if (sources.getLength() == 0) { LOGGER.warn("Cannot get first element of node list 'sources'."); return ""; } final Element source = (Element) sources.item(0); MCRCategoryID category = MCRClassMapper.getCategoryID(source); if (category == null) { return ""; } String id; try { id = MCRXMLFunctions.encodeURIPath(category.getId()); } catch (URISyntaxException e) { /* This should be impossible! */ throw new MCRException(e); } return String.format(Locale.ROOT, "classification:metadata:0:parents:%s:%s", category.getRootID(), id); } static String getText(final Element element) { final StringBuilder sb = new StringBuilder(); final NodeList nodeList = element.getChildNodes(); final int length = nodeList.getLength(); for (int i = 0; i < length; i++) { final Node node = nodeList.item(i); if (node.getNodeType() == Node.TEXT_NODE) { sb.append(node.getNodeValue()); } } return sb.toString(); } }
5,997
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessCondition.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRAccessCondition.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import java.util.Collection; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; /** * Translates <code>&lt;mods:accessCondition /&gt;</code> into mycore classifications * * @author Thomas Scheffler (yagee) */ public class MCRAccessCondition extends MCRAuthorityInfo { public String href; private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); private static final Logger LOGGER = LogManager.getLogger(MCRAccessCondition.class); public MCRAccessCondition(String href) { this.href = href; } /* (non-Javadoc) * @see org.mycore.mods.classification.MCRAuthorityInfo#lookupCategoryID() */ @Override protected MCRCategoryID lookupCategoryID() { Collection<MCRCategory> categoryByURI = MCRAuthorityWithURI.getCategoryByURI(href); if (categoryByURI.size() > 1) { throw new MCRException( href + " is ambigous: " + categoryByURI.stream().map(MCRCategory::getId).collect(Collectors.toList())); } if (!categoryByURI.isEmpty()) { return categoryByURI.iterator().next().getId(); } //maybe href is in form {authorityURI}#{categId} String categId; String authorityURI = null; try { authorityURI = href.substring(0, href.lastIndexOf("#")); categId = href.substring(authorityURI.length() + 1); } catch (RuntimeException e) { LOGGER.warn("authorityURI:{}, valueURI:{}", authorityURI, href); return null; } int internalStylePos = authorityURI.indexOf(MCRAuthorityWithURI.CLASS_URI_PART); if (internalStylePos > 0) { String rootId = authorityURI.substring(internalStylePos + MCRAuthorityWithURI.CLASS_URI_PART.length()); MCRCategoryID catId = new MCRCategoryID(rootId, categId); if (DAO.exist(catId)) { return catId; } } Collection<MCRCategory> classes = MCRAuthorityWithURI.getCategoryByURI(authorityURI); return classes.stream() .map(cat -> new MCRCategoryID(cat.getId().getRootID(), categId)) .filter(DAO::exist) .findFirst() .orElse(null); } /* (non-Javadoc) * @see org.mycore.mods.classification.MCRAuthorityInfo#setInElement(org.jdom2.Element) */ @Override public void setInElement(Element modsElement) { modsElement.setAttribute("href", href, MCRConstants.XLINK_NAMESPACE); } /* (non-Javadoc) * @see org.mycore.mods.classification.MCRAuthorityInfo#setInElement(org.w3c.dom.Element) */ @Override public void setInElement(org.w3c.dom.Element modsElement) { modsElement.setAttributeNS(MCRConstants.XLINK_NAMESPACE.getURI(), "href", href); } @Override public String toString() { return href; } }
4,074
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRModsClassificationURIResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRModsClassificationURIResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import java.net.URI; import java.util.Locale; import java.util.Optional; import java.util.stream.Stream; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.common.xml.MCRURIResolver; import org.mycore.datamodel.classifications2.MCRCategoryID; /** * Resolves a classification in parent style. * Uses the URI <code>classification:metadata:0:parents:{{@link MCRCategoryID#toString()}}</code> to resolve the result. * If no matching classification is found an &lt;empty /&gt; element is returned. * This URIResolver can used by this URI syntax:<br> * <ul> * <li> * mycoremods:/{sourcePath}/{subPath} * <ul> * <li>sourcePath is either: * <ul> * <li>uri * <ul> * <li>subPath is {{@literal @}authorityURI}/{{@literal @}valueURI} in URI encoded form</li> * </ul> * </li> * <li>authority * <ul> * <li>subPath is {{@literal @}authority}/{text()} in URI encoded form</li> * </ul> * </li> * <li>accessCondition * <ul> * <li>subPath is {{@literal @}xlink:href} in URI encoded form</li> * </ul> * </li> * <li>typeOfResource * <ul> * <li>subPath is {text()} in URI encoded form</li> * </ul> * </li> * </ul> * </li> * </ul> * </li> * <li> * examples: * <ul> * <li> *modsclass:/uri/http%3A%2F%2Fwww.example.org%2Fclassifications/http%3A%2F%2Fwww.example.org%2Fpub-type%23Sound * </li> * <li>modsclass:/authority/marcrelator/aut</li> * <li> *modsclass:/accessCondition/http%3A%2F%2Fwww.mycore.org%2Fclassifications%2Fmir_licenses%23cc_by-sa_4.0 * </li> * <li>modsclass:/typeOfResource/sound%20recording</li> * </ul> * </li> * </ul> * */ public class MCRModsClassificationURIResolver implements URIResolver { private static final Logger LOGGER = LogManager.getLogger(); private static Optional<MCRAuthorityInfo> getAuthorityInfo(String href) { final URI uri = URI.create(href); //keep any encoded '/' inside a path segment final String[] decodedPathSegments = Stream.of(uri.getRawPath().substring(1).split("/")) .map(s -> "/" + s) //mask as a path for parsing .map(URI::create) //parse .map(URI::getPath) //decode .map(p -> p.substring(1)) //strip '/' again .toArray(String[]::new); MCRAuthorityInfo authInfo = null; switch (decodedPathSegments[0]) { case "uri" -> { if (decodedPathSegments.length == 3) { authInfo = new MCRAuthorityWithURI(decodedPathSegments[1], decodedPathSegments[2]); } } case "authority" -> { if (decodedPathSegments.length == 3) { authInfo = new MCRAuthorityAndCode(decodedPathSegments[1], decodedPathSegments[2]); } } case "accessCondition" -> { if (decodedPathSegments.length == 2) { authInfo = new MCRAccessCondition(decodedPathSegments[1]); } } case "typeOfResource" -> { if (decodedPathSegments.length == 2) { authInfo = new MCRTypeOfResource(decodedPathSegments[1]); } } } LOGGER.debug("authinfo {}", authInfo); return Optional.ofNullable(authInfo); } @Override public Source resolve(String href, String base) throws TransformerException { final Optional<String> categoryURI = getAuthorityInfo(href) .map(MCRAuthorityInfo::getCategoryID) .map(category -> String.format(Locale.ROOT, "classification:metadata:0:parents:%s:%s", category.getRootID(), category.getId())); if (categoryURI.isPresent()) { LOGGER.debug("{} -> {}", href, categoryURI.get()); return MCRURIResolver.instance().resolve(categoryURI.get(), base); } LOGGER.debug("no category found for {}", href); return new JDOMSource(new Element("empty")); } }
5,574
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationMappingEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRClassificationMappingEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import java.util.AbstractMap; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.mods.MCRMODSWrapper; /** * Maps classifications in Mods-Documents. * <p>You can define a label <b><code>x-mapping</code></b> in a classification with space seperated categoryIds * to which the classification will be mapped.</p> * <code> * &lt;category ID=&quot;article&quot; counter=&quot;1&quot;&gt;<br> * &nbsp;&lt;label xml:lang=&quot;en&quot; text=&quot;Article / Chapter&quot; /&gt;<br> * &nbsp;&lt;label xml:lang=&quot;de&quot; text=&quot;Artikel / Aufsatz&quot; /&gt;<br> * &nbsp;&lt;label xml:lang=&quot;x-mapping&quot; text=&quot;diniPublType:article&quot; /&gt;<br> * &lt;/category&gt; * </code> * * @author Sebastian Hofmann (mcrshofm) */ public class MCRClassificationMappingEventHandler extends MCREventHandlerBase { public static final String GENERATOR_SUFFIX = "-mycore"; private static final Logger LOGGER = LogManager.getLogger(MCRClassificationMappingEventHandler.class); private static List<Map.Entry<MCRCategoryID, MCRCategoryID>> getMappings(MCRCategory category) { Optional<MCRLabel> labelOptional = category.getLabel("x-mapping"); if (labelOptional.isPresent()) { final MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance(); String label = labelOptional.get().getText(); return Stream.of(label.split("\\s")) .map(categIdString -> categIdString.split(":")) .map(categIdArr -> new MCRCategoryID(categIdArr[0], categIdArr[1])) .filter(dao::exist) .map(mappingTarget -> new AbstractMap.SimpleEntry<>(category.getId(), mappingTarget)) .collect(Collectors.toList()); } return Collections.emptyList(); } @Override protected void handleObjectCreated(MCREvent evt, MCRObject obj) { createMapping(obj); } @Override protected void handleObjectUpdated(MCREvent evt, MCRObject obj) { createMapping(obj); } @Override protected void handleObjectRepaired(MCREvent evt, MCRObject obj) { createMapping(obj); } private static String getGenerator(MCRCategoryID src, MCRCategoryID target) { return String.format(Locale.ROOT, "%s2%s%s", src.getRootID(), target.getRootID(), GENERATOR_SUFFIX); } private void createMapping(MCRObject obj) { MCRMODSWrapper mcrmodsWrapper = new MCRMODSWrapper(obj); if (mcrmodsWrapper.getMODS() == null) { return; } // vorher alle mit generator *-mycore löschen mcrmodsWrapper.getElements("mods:classification[contains(@generator, '" + GENERATOR_SUFFIX + "')]") .stream().forEach(Element::detach); LOGGER.info("check mappings {}", obj.getId()); final MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance(); mcrmodsWrapper.getMcrCategoryIDs().stream() .map(categoryId -> { return dao.getCategory(categoryId, 0); }) .filter(Objects::nonNull) .map(MCRClassificationMappingEventHandler::getMappings) .flatMap(Collection::stream) .distinct() .forEach(mapping -> { String taskMessage = String.format(Locale.ROOT, "add mapping from '%s' to '%s'", mapping.getKey().toString(), mapping.getValue().toString()); LOGGER.info(taskMessage); Element mappedClassification = mcrmodsWrapper.addElement("classification"); String generator = getGenerator(mapping.getKey(), mapping.getValue()); mappedClassification.setAttribute("generator", generator); MCRClassMapper.assignCategory(mappedClassification, mapping.getValue()); }); LOGGER.debug("mapping complete."); } }
5,405
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTypeOfResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRTypeOfResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.w3c.dom.Element; /** * Authority information that is a static mapping for mods:typeOfResource. This element is always mapped to a * classification with the ID typeOfResource. * * @author Frank Lützenkirchen */ class MCRTypeOfResource extends MCRAuthorityInfo { /** * The name of the MODS element typeOfResource, which is same as the classification ID used to map the codes to * categories. */ public static final String TYPE_OF_RESOURCE = "typeOfResource"; /** * The mods:typeOfResource code, which is same as the category ID */ private String code; MCRTypeOfResource(String code) { this.code = code; } /** * If the given element is mods:typeOfResource, returns the MCRTypeOfResource mapping. */ public static MCRTypeOfResource getAuthorityInfo(org.jdom2.Element modsElement) { if (modsElement == null) { return null; } String name = modsElement.getName(); String code = modsElement.getTextTrim(); return getTypeOfResource(name, code); } /** * If the given element is mods:typeOfResource, returns the MCRTypeOfResource mapping. */ public static MCRTypeOfResource getAuthorityInfo(Element modsElement) { if (modsElement == null) { return null; } String name = modsElement.getLocalName(); String code = MCRMODSClassificationSupport.getText(modsElement).trim(); return getTypeOfResource(name, code); } /** * If the given element name is typeOfResource, returns the MCRTypeOfResource mapping. */ private static MCRTypeOfResource getTypeOfResource(String name, String code) { return (name.equals(TYPE_OF_RESOURCE) && isClassificationPresent()) ? new MCRTypeOfResource(code) : null; } @Override public String toString() { return TYPE_OF_RESOURCE + "#" + code; } @Override protected MCRCategoryID lookupCategoryID() { return new MCRCategoryID(TYPE_OF_RESOURCE, code.replace(" ", "_")); // Category IDs can not contain spaces } @Override public void setInElement(org.jdom2.Element element) { element.setText(code); } @Override public void setInElement(Element element) { element.setTextContent(code); } public static boolean isClassificationPresent() { return MCRCategoryDAOFactory.getInstance().exist(MCRCategoryID.rootID(TYPE_OF_RESOURCE)); } }
3,397
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAuthorityInfo.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRAuthorityInfo.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRCache; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.w3c.dom.Element; /** * MCRAuthorityInfo holds a combination of either authority ID and value code, or authorityURI and valueURI. In MODS, * this combination typically represents a value from a normed vocabulary like a classification. The AuthorityInfo can * be mapped to a MCRCategory in MyCoRe. * * @see <a href="http://www.loc.gov/standards/mods/userguide/classification.html">MODS classification guidelines</a> * @author Frank Lützenkirchen */ abstract class MCRAuthorityInfo { private static Logger LOGGER = LogManager.getLogger(MCRAuthorityInfo.class); private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); /** * A cache that maps authority information to the category ID that is represented by that info. */ private static final MCRCache<String, Object> CATEGORY_ID_BY_AUTHORITY_INFO = new MCRCache<>(1000, "Category ID by authority info"); /** * Used in the cache to indicate the case when no category ID maps to the given authority info */ private static final String NULL = "null"; /** * Returns the label value of the given type ("language"), or the given default if that label does not exist in the * category. */ protected static String getLabel(MCRCategory category, String labelType, String defaultLabel) { return category.getLabel(labelType).map(MCRLabel::getText).orElse(defaultLabel); } /** * Returns the category ID that is represented by this authority information. * * @return the category ID that maps this authority information, or null if no matching category exists. */ public MCRCategoryID getCategoryID() { String key = toString(); LOGGER.debug("get categoryID for {}", key); Object categoryID = CATEGORY_ID_BY_AUTHORITY_INFO.getIfUpToDate(key, DAO.getLastModified()); if (categoryID == null) { LOGGER.debug("lookup categoryID for {}", key); categoryID = lookupCategoryID(); if (categoryID == null) { categoryID = NULL; // Indicate that no matching category found, null can not be cached directly } CATEGORY_ID_BY_AUTHORITY_INFO.put(key, categoryID); } return categoryID instanceof MCRCategoryID ? (MCRCategoryID) categoryID : null; } /** * Looks up the category ID for this authority information in the classification database. */ protected abstract MCRCategoryID lookupCategoryID(); /** * Sets this authority information in the given MODS XML element by setting authority/authorityURI/valueURI * attributes and/or value code as text. */ public abstract void setInElement(org.jdom2.Element modsElement); /** * Sets this authority information in the given MODS XML element by setting authority/authorityURI/valueURI * attributes and/or value code as text. */ public abstract void setInElement(Element modsElement); }
4,197
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAuthorityWithURI.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRAuthorityWithURI.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import java.util.Collection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.frontend.MCRFrontendUtil; import org.w3c.dom.Element; /** * Authority information that is represented by authorityURI and valueURI. Such authority info comes from a vocabulary * that is not registered at the Library of Congress, but maintained by an external authority like the MyCoRe * application. * * @author Frank Lützenkirchen */ class MCRAuthorityWithURI extends MCRAuthorityInfo { /** The attribute holding the authority URI in XML */ private static final String ATTRIBUTE_AUTHORITY_URI = "authorityURI"; /** The attribute holding the value URI in XML */ private static final String ATTRIBUTE_VALUE_URI = "valueURI"; static final String CLASS_URI_PART = "classifications/"; private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); /** * xml:lang value of category or classification <label> for MODS @authorityURI or @valueURI. */ private static final String LABEL_LANG_URI = "x-uri"; private static final Logger LOGGER = LogManager.getLogger(MCRMODSClassificationSupport.class); /** * The authority URI */ private String authorityURI; /** * The value URI */ private String valueURI; /** * Inspects the attributes in the given MODS XML element and returns the AuthorityInfo given there. */ public static MCRAuthorityWithURI getAuthorityInfo(Element element) { String authorityURI = element.getAttribute(ATTRIBUTE_AUTHORITY_URI); String valueURI = element.getAttribute(ATTRIBUTE_VALUE_URI); return getAuthorityInfo(authorityURI, valueURI); } /** * Inspects the attributes in the given MODS XML element and returns the AuthorityInfo given there. */ public static MCRAuthorityWithURI getAuthorityInfo(org.jdom2.Element element) { String authorityURI = element.getAttributeValue(ATTRIBUTE_AUTHORITY_URI); String valueURI = element.getAttributeValue(ATTRIBUTE_VALUE_URI); return getAuthorityInfo(authorityURI, valueURI); } /** * Builds the authority info from the given values, does some checks on the values. * * @return the authority info, or null if the values are illegal or unsupported. */ private static MCRAuthorityWithURI getAuthorityInfo(String authorityURI, String valueURI) { if (authorityURI == null || authorityURI.isEmpty()) { return null; } if (valueURI == null || valueURI.length() == 0) { LOGGER.warn("Did find attribute authorityURI='{}', but no valueURI", authorityURI); return null; } return new MCRAuthorityWithURI(authorityURI, valueURI); } /** * Returns the authority URI for the given classification. */ protected static String getAuthorityURI(MCRCategory classification) { String defaultURI = MCRFrontendUtil.getBaseURL() + CLASS_URI_PART + classification.getId().getRootID(); return getLabel(classification, LABEL_LANG_URI, defaultURI); } /** * Returns the categories which have the given URI as label. */ static Collection<MCRCategory> getCategoryByURI(final String uri) { return DAO.getCategoriesByLabel(LABEL_LANG_URI, uri); } /** * Returns the value URI for the given category and authority URI */ protected static String getValueURI(MCRCategory category, String authorityURI) { String defaultURI = authorityURI + "#" + category.getId().getId(); return getLabel(category, LABEL_LANG_URI, defaultURI); } MCRAuthorityWithURI(String authorityURI, String valueURI) { this.authorityURI = authorityURI; this.valueURI = valueURI; } @Override protected MCRCategoryID lookupCategoryID() { for (MCRCategory category : getCategoryByURI(valueURI)) { if (authorityURI.equals(category.getRoot().getLabel(LABEL_LANG_URI).get().getText())) { return category.getId(); } } //maybe valueUri is in form {authorityURI}#{categId} if (valueURI.startsWith(authorityURI) && authorityURI.length() < valueURI.length()) { String categId; try { categId = valueURI.substring(authorityURI.length() + 1); } catch (RuntimeException e) { LOGGER.warn("authorityURI:{}, valueURI:{}", authorityURI, valueURI); throw e; } int internalStylePos = authorityURI.indexOf(CLASS_URI_PART); if (internalStylePos > 0) { String rootId = authorityURI.substring(internalStylePos + CLASS_URI_PART.length()); MCRCategoryID catId = new MCRCategoryID(rootId, categId); if (DAO.exist(catId)) { return catId; } } return getCategoryByURI(authorityURI).stream() .map(cat -> new MCRCategoryID(cat.getId().getRootID(), categId)) .filter(DAO::exist) .findFirst() .orElse(null); } return null; } @Override public void setInElement(Element element) { element.setAttribute(ATTRIBUTE_AUTHORITY_URI, authorityURI); element.setAttribute(ATTRIBUTE_VALUE_URI, valueURI); } @Override public void setInElement(org.jdom2.Element element) { element.setAttribute(ATTRIBUTE_AUTHORITY_URI, authorityURI); element.setAttribute(ATTRIBUTE_VALUE_URI, valueURI); } @Override public String toString() { return authorityURI + "#" + valueURI; } }
6,771
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassMapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mods/src/main/java/org/mycore/mods/classification/MCRClassMapper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mods.classification; import java.util.Set; import org.mycore.common.MCRCache; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.w3c.dom.Element; /** * @author Thomas Scheffler (yagee) */ public class MCRClassMapper { private static final String TYPE_OF_RESOURCE = "typeOfResource"; private static final String ACCESS_CONDITION = "accessCondition"; //as of MODS 3.7 with addition of accessCondition private static final Set<String> SUPPORTED = Set.of("accessCondition", "area", "cartographics", "city", "citySection", "classification", "continent", "country", "county", "descriptionStandard", "extraTerrestrialArea", "form", "frequency", "genre", "geographic", "geographicCode", "hierarchicalGeographic", "island", "languageTerm", "name", "occupation", "physicalLocation", "placeTerm", "publisher", "recordContentSource", "region", "roleTerm", "scriptTerm", "state", "subject", "targetAudience", "temporal", "territory", "titleInfo", "topic", "typeOfResource"); private static final String NS_MODS_URI = MCRConstants.MODS_NAMESPACE.getURI(); private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); private static final MCRCache<String, String> AUTH_CACHE = new MCRCache<>(100, "MCRCategory authority"); private static final MCRCache<String, String> AUTH_URI_CACHE = new MCRCache<>(100, "MCRCategory authorityURI"); private static final MCRCache<MCRAuthKey, MCRAuthorityInfo> AUTHORITY_INFO_CACHE = new MCRCache<>(1000, "MCRAuthorityInfo cache"); private MCRClassMapper() { } public static boolean supportsClassification(org.jdom2.Element modsElement) { return modsElement.getNamespaceURI().equals(NS_MODS_URI) && SUPPORTED.contains(modsElement.getName()); } public static boolean supportsClassification(Element modsElement) { return modsElement.getNamespaceURI().equals(NS_MODS_URI) && SUPPORTED.contains(modsElement.getLocalName()); } public static MCRCategoryID getCategoryID(org.jdom2.Element modsElement) { if (supportsClassification(modsElement)) { MCRAuthorityInfo authInfo; if (modsElement.getAttributeValue("authorityURI") != null) { //authorityURI String authorityURI = modsElement.getAttributeValue("authorityURI"); String valueURI = modsElement.getAttributeValue("valueURI"); authInfo = new MCRAuthorityWithURI(authorityURI, valueURI); } else if (modsElement.getAttributeValue("authority") != null) { //authority authInfo = MCRAuthorityAndCode.getAuthorityInfo(modsElement); } else if (modsElement.getName().equals(ACCESS_CONDITION)) { //accessDefinition String href = modsElement.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE, ""); authInfo = new MCRAccessCondition(href); } else if (modsElement.getName().equals(TYPE_OF_RESOURCE)) { //typeOfResource String code = modsElement.getTextTrim(); authInfo = new MCRTypeOfResource(code); } else { return null; } if (authInfo == null) { return null; } return authInfo.getCategoryID(); } return null; } public static MCRCategoryID getCategoryID(Element modsElement) { if (supportsClassification(modsElement)) { MCRAuthorityInfo authInfo; if (!modsElement.getAttribute("authorityURI").isEmpty()) { //authorityURI String authorityURI = modsElement.getAttribute("authorityURI"); String valueURI = modsElement.getAttribute("valueURI"); authInfo = new MCRAuthorityWithURI(authorityURI, valueURI); } else if (!modsElement.getAttribute("authority").isEmpty()) { //authority authInfo = MCRAuthorityAndCode.getAuthorityInfo(modsElement); } else if (modsElement.getLocalName().equals(ACCESS_CONDITION)) { //accessDefinition String href = modsElement.getAttributeNS(MCRConstants.XLINK_NAMESPACE.getURI(), "href"); authInfo = new MCRAccessCondition(href); } else if (modsElement.getLocalName().equals(TYPE_OF_RESOURCE)) { //typeOfResource String code = modsElement.getTextContent().trim(); authInfo = new MCRTypeOfResource(code); } else { return null; } if (authInfo == null) { return null; } return authInfo.getCategoryID(); } return null; } public static void assignCategory(org.jdom2.Element modsElement, MCRCategoryID categID) { MCRAuthorityInfo authInfo = modsElement.getNamespace().equals(MCRConstants.MODS_NAMESPACE) ? getAuthInfo(categID, modsElement.getName()) : null; if (authInfo == null) { throw new MCRException(modsElement.getQualifiedName() + " could not be assigned to category " + categID); } authInfo.setInElement(modsElement); } public static void assignCategory(Element modsElement, MCRCategoryID categID) { MCRAuthorityInfo authInfo = modsElement.getNamespaceURI().equals(MCRConstants.MODS_NAMESPACE.getURI()) ? getAuthInfo(categID, modsElement.getLocalName()) : null; if (authInfo == null) { throw new MCRException(modsElement.getTagName() + " could not be assigned to category " + categID); } authInfo.setInElement(modsElement); } private static MCRAuthorityInfo getAuthInfo(MCRCategoryID categID, String elementLocalName) { MCRAuthKey authKey = new MCRAuthKey(elementLocalName, categID); long classLastModified = Math.max(0, DAO.getLastModified(categID.getRootID())); MCRAuthorityInfo authInfo = AUTHORITY_INFO_CACHE.getIfUpToDate(authKey, classLastModified); if (authInfo == null) { if (elementLocalName.equals(TYPE_OF_RESOURCE) && categID.getRootID().equals(MCRTypeOfResource.TYPE_OF_RESOURCE)) { authInfo = new MCRTypeOfResource(categID.getId().replace('_', ' ')); } else if (elementLocalName.equals(ACCESS_CONDITION)) { String authURI = getAuthorityURI(categID.getRootID()); String valueURI = MCRAuthorityWithURI.getValueURI(DAO.getCategory(categID, 0), authURI); authInfo = new MCRAccessCondition(valueURI); } else if (SUPPORTED.contains(elementLocalName)) { String authority = getAuthority(categID.getRootID()); if (authority != null) { authInfo = new MCRAuthorityAndCode(authority, categID.getId()); } else { String authURI = getAuthorityURI(categID.getRootID()); String valueURI = MCRAuthorityWithURI.getValueURI(DAO.getCategory(categID, 0), authURI); authInfo = new MCRAuthorityWithURI(authURI, valueURI); } } if (authInfo == null) { authInfo = new MCRNullAuthInfo(); } AUTHORITY_INFO_CACHE.put(authKey, authInfo, classLastModified); } return authInfo instanceof MCRNullAuthInfo ? null : authInfo; } private static String getAuthority(String rootID) { long classLastModified = Math.max(0, DAO.getLastModified(rootID)); String auth = AUTH_CACHE.getIfUpToDate(rootID, classLastModified); if (auth == null) { MCRCategory rootCategory = DAO.getRootCategory(MCRCategoryID.rootID(rootID), 0); auth = rootCategory.getLabel("x-auth").map(MCRLabel::getText).orElse(""); AUTH_CACHE.put(rootID, auth, classLastModified); } return auth.isEmpty() ? null : auth; } private static String getAuthorityURI(String rootID) { long classLastModified = Math.max(0, DAO.getLastModified(rootID)); String authURI = AUTH_URI_CACHE.getIfUpToDate(rootID, classLastModified); if (authURI == null) { MCRCategory rootCategory = DAO.getRootCategory(MCRCategoryID.rootID(rootID), 0); authURI = MCRAuthorityWithURI.getAuthorityURI(rootCategory); AUTH_URI_CACHE.put(rootID, authURI, classLastModified); } return authURI; } private static class MCRAuthKey { String localName; MCRCategoryID categID; MCRAuthKey(String localName, MCRCategoryID categID) { this.localName = localName; this.categID = categID; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((localName == null) ? 0 : localName.hashCode()); result = prime * result + ((categID == null) ? 0 : categID.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRAuthKey other = (MCRAuthKey) obj; if (localName == null) { if (other.localName != null) { return false; } } else if (!localName.equals(other.localName)) { return false; } if (categID == null) { return other.categID == null; } else { return categID.equals(other.categID); } } } private static class MCRNullAuthInfo extends MCRAuthorityInfo { @Override protected MCRCategoryID lookupCategoryID() { throw new UnsupportedOperationException(); } @Override public void setInElement(org.jdom2.Element modsElement) { throw new UnsupportedOperationException(); } @Override public void setInElement(Element modsElement) { throw new UnsupportedOperationException(); } } }
11,535
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCSLJSONTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-csl/src/main/java/org/mycore/csl/MCRCSLJSONTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.csl; import java.io.IOException; import java.util.stream.Collectors; import org.jdom2.JDOMException; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRStringContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.xml.sax.SAXException; import de.undercouch.citeproc.helper.json.JsonBuilder; import de.undercouch.citeproc.helper.json.StringJsonBuilderFactory; public class MCRCSLJSONTransformer extends MCRContentTransformer { private String configuredItemProviderProperty; @Override public void init(String id) { super.init(id); configuredItemProviderProperty = "MCR.ContentTransformer." + id + "." + MCRCSLTransformer.ITEM_PROVIDER; } private MCRItemDataProvider createItemDataProvider() { return MCRConfiguration2.<MCRItemDataProvider>getInstanceOf(configuredItemProviderProperty) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(configuredItemProviderProperty)); } @Override public String getMimeType() { return "application/json"; } @Override public String getEncoding() { return MCRConstants.DEFAULT_ENCODING; } @Override public String getFileExtension() { return "json"; } @Override public MCRContent transform(MCRContent source) throws IOException { final JsonBuilder jsonBuilder = new StringJsonBuilderFactory().createJsonBuilder(); MCRItemDataProvider dataProvider = createItemDataProvider(); try { dataProvider.addContent(source); } catch (JDOMException | SAXException e) { throw new IOException(e); } final String jsonArray = dataProvider.getIds().stream() .map(dataProvider::retrieveItem) .map(jsonBuilder::toJson) .map(Object::toString) .collect(Collectors.joining(",", "[", "]")); return new MCRStringContent(jsonArray); } }
2,824
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRItemDataProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-csl/src/main/java/org/mycore/csl/MCRItemDataProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.csl; import java.io.IOException; import org.jdom2.JDOMException; import org.mycore.common.content.MCRContent; import org.xml.sax.SAXException; import de.undercouch.citeproc.ItemDataProvider; public abstract class MCRItemDataProvider implements ItemDataProvider { public abstract void addContent(MCRContent content) throws IOException, JDOMException, SAXException; public abstract void reset(); }
1,155
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBibtextItemDataProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-csl/src/main/java/org/mycore/csl/MCRBibtextItemDataProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.csl; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import org.jbibtex.BibTeXDatabase; import org.jbibtex.ParseException; import org.mycore.common.content.MCRContent; import de.undercouch.citeproc.bibtex.BibTeXConverter; import de.undercouch.citeproc.bibtex.BibTeXItemDataProvider; import de.undercouch.citeproc.csl.CSLItemData; /** * Wrapper around BibTeXItemDataProvider to make it reusable */ public class MCRBibtextItemDataProvider extends MCRItemDataProvider { private BibTeXItemDataProvider wrappedProvider = new BibTeXItemDataProvider(); @Override public CSLItemData retrieveItem(String id) { return wrappedProvider.retrieveItem(id); } @Override public Collection<String> getIds() { return wrappedProvider.getIds(); } @Override public void addContent(MCRContent bibTeX) throws IOException { InputStream in = bibTeX.getInputStream(); BibTeXDatabase db; try { db = new BibTeXConverter().loadDatabase(in); } catch (ParseException ex) { throw new IOException(ex); } in.close(); wrappedProvider.addDatabase(db); } @Override public void reset() { wrappedProvider = new BibTeXItemDataProvider(); } }
2,052
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCSLTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-csl/src/main/java/org/mycore/csl/MCRCSLTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.csl; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.concurrent.atomic.AtomicReference; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRStringContent; import org.mycore.common.content.transformer.MCRParameterizedTransformer; import org.mycore.common.xsl.MCRParameterCollector; import de.undercouch.citeproc.CSL; import de.undercouch.citeproc.output.Bibliography; public class MCRCSLTransformer extends MCRParameterizedTransformer { public static final String DEFAULT_FORMAT = "text"; public static final String DEFAULT_STYLE = "nature"; public static final String ITEM_PROVIDER = "ItemProviderClass"; private static final String CONFIG_PREFIX = "MCR.ContentTransformer."; private final Map<String, Stack<MCRCSLTransformerInstance>> transformerInstances; private String configuredFormat; private String configuredStyle; private String configuredItemProviderProperty; private boolean unsorted; { transformerInstances = new HashMap<>(); } @Override public void init(String id) { super.init(id); configuredFormat = MCRConfiguration2.getString(CONFIG_PREFIX + id + ".format").orElse(DEFAULT_FORMAT); configuredStyle = MCRConfiguration2.getString(CONFIG_PREFIX + id + ".style").orElse(DEFAULT_STYLE); configuredItemProviderProperty = CONFIG_PREFIX + id + "." + ITEM_PROVIDER; // when set to true, then the sorting of the CSL Style is used instead // of the one provided by the ItemDataProvider unsorted = !MCRConfiguration2.getBoolean(CONFIG_PREFIX + id + ".CSLSorting").orElse(false); createItemDataProvider(); } private MCRItemDataProvider createItemDataProvider() { return (MCRItemDataProvider) MCRConfiguration2.getInstanceOf(configuredItemProviderProperty) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(configuredItemProviderProperty)); } @Override public MCRContent transform(MCRContent source) { return null; } private MCRCSLTransformerInstance getTransformerInstance(String style, String format) { synchronized (transformerInstances) { if (getStyleFormatTransformerStack(style, format).size() > 0) { return transformerInstances.get(mapKey(style, format)).pop(); } } AtomicReference<MCRCSLTransformerInstance> instance = new AtomicReference<>(); final MCRCSLTransformerInstance newInstance = new MCRCSLTransformerInstance(style, format, () -> returnTransformerInstance(instance.get(), style, format), createItemDataProvider()); instance.set(newInstance); return newInstance; } private Stack<MCRCSLTransformerInstance> getStyleFormatTransformerStack(String style, String format) { return transformerInstances.computeIfAbsent(mapKey(style, format), (a) -> new Stack<>()); } private String mapKey(String style, String format) { return style + "_" + format; } private void returnTransformerInstance(MCRCSLTransformerInstance instance, String style, String format) { try { instance.getCitationProcessor().reset(); instance.getDataProvider().reset(); } catch (RuntimeException e) { // if a error happens the instances may be not reset, so we trow away the instance return; } synchronized (transformerInstances) { final Stack<MCRCSLTransformerInstance> styleFormatTransformerStack = getStyleFormatTransformerStack(style, format); if (!styleFormatTransformerStack.contains(instance)) { styleFormatTransformerStack.push(instance); } } } @Override public MCRContent transform(MCRContent bibtext, MCRParameterCollector parameter) { final String format = parameter != null ? parameter.getParameter("format", configuredFormat) : configuredFormat; final String style = parameter != null ? parameter.getParameter("style", configuredStyle) : configuredStyle; try (MCRCSLTransformerInstance transformerInstance = getTransformerInstance(style, format)) { final CSL citationProcessor = transformerInstance.getCitationProcessor(); final MCRItemDataProvider dataProvider = transformerInstance.getDataProvider(); dataProvider.addContent(bibtext); citationProcessor.registerCitationItems(dataProvider.getIds(), unsorted); Bibliography biblio = citationProcessor.makeBibliography(); String result = biblio.makeString(); return new MCRStringContent(result); } catch (Exception e) { throw new MCRException("Error while returning CSL instance to pool!", e); } } }
5,721
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCSLTransformerInstance.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-csl/src/main/java/org/mycore/csl/MCRCSLTransformerInstance.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.csl; import java.io.IOException; import org.mycore.common.config.MCRConfigurationException; import de.undercouch.citeproc.CSL; public class MCRCSLTransformerInstance implements AutoCloseable { private final AutoCloseable closeable; private final CSL citationProcessor; private final MCRItemDataProvider dataProvider; public MCRCSLTransformerInstance(String style, String format, AutoCloseable closeable, MCRItemDataProvider dataProvider) { this.closeable = closeable; this.dataProvider = dataProvider; try { this.citationProcessor = new CSL(this.dataProvider, style); } catch (IOException e) { throw new MCRConfigurationException("Error while creating CSL with Style " + style, e); } this.citationProcessor.setOutputFormat(format); } public CSL getCitationProcessor() { return citationProcessor; } public MCRItemDataProvider getDataProvider() { return dataProvider; } @Override public void close() throws Exception { this.closeable.close(); } }
1,855
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkTransformerHelperTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/test/java/org/mycore/orcid2/v3/transformer/MCRORCIDWorkTransformerHelperTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.transformer; import static org.junit.Assert.assertEquals; import java.net.URL; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.jdom2.output.XMLOutputter; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.content.MCRJDOMContent; import org.orcid.jaxb.model.v3.release.record.Work; import jakarta.xml.bind.JAXBContext; public class MCRORCIDWorkTransformerHelperTest extends MCRTestCase { private static final Logger LOGGER = LogManager.getLogger(); @Test public void testTransformContent() throws Exception { final JAXBContext jaxbContext = JAXBContext.newInstance(Work.class); final URL inputUrl = MCRORCIDWorkTransformerHelperTest.class.getResource("/work_example.xml"); final Work work = (Work) jaxbContext.createUnmarshaller().unmarshal(inputUrl); LOGGER.info(work); final Element mods = MCRORCIDWorkTransformerHelper.transformWork(work).asXML().detachRootElement(); LOGGER.info(new XMLOutputter().outputString(mods)); final Work result = MCRORCIDWorkTransformerHelper.transformContent(new MCRJDOMContent(mods)); LOGGER.info(result); assertEquals(work.getWorkType(), result.getWorkType()); LOGGER.warn("Skipping contributors..."); // assertEquals(work.getWorkContributors(), result.getWorkContributors()); LOGGER.warn("Skipping journal title..."); // assertEquals(work.getJournalTitle(), result.getJournalTitle()); assertEquals(work.getPublicationDate(), result.getPublicationDate()); assertEquals(work.getShortDescription(), result.getShortDescription()); assertEquals(work.getUrl(), result.getUrl()); assertEquals(work.getLanguageCode(), result.getLanguageCode()); assertEquals(work.getWorkExternalIdentifiers(), result.getWorkExternalIdentifiers()); } }
2,692
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDMetadataUtilsTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/test/java/org/mycore/orcid2/metadata/MCRORCIDMetadataUtilsTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.metadata; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.List; import java.util.Map; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.orcid2.exception.MCRORCIDTransformationException; public class MCRORCIDMetadataUtilsTest extends MCRTestCase { @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.ORCID2.Metadata.SaveOtherPutCodes", Boolean.TRUE.toString()); return testProperties; } @Test public void testGetORCIDFlagContentNull() { assertNull(MCRORCIDMetadataUtils.getORCIDFlagContent(new MCRObject())); } @Test(expected = MCRORCIDTransformationException.class) public void testTransformFlagContentStringException() { MCRORCIDMetadataUtils.transformFlagContentString("invalid json"); } @Test public void testTransformFlagContent() { final MCRORCIDFlagContent flagContent = new MCRORCIDFlagContent(); String result = MCRORCIDMetadataUtils.transformFlagContent(flagContent); String expectedResult = "{\"userInfos\":[]}"; assertEquals(result, expectedResult); final MCRORCIDUserInfo userInfo = new MCRORCIDUserInfo("ORCID"); flagContent.getUserInfos().add(userInfo); result = MCRORCIDMetadataUtils.transformFlagContent(flagContent); expectedResult = "{\"userInfos\":[{\"orcid\":\"ORCID\"}]}"; assertEquals(result, expectedResult); final MCRORCIDPutCodeInfo putCodeInfo = new MCRORCIDPutCodeInfo(); userInfo.setWorkInfo(putCodeInfo); result = MCRORCIDMetadataUtils.transformFlagContent(flagContent); expectedResult = "{\"userInfos\":[{\"orcid\":\"ORCID\",\"works\":{}}]}"; assertEquals(result, expectedResult); putCodeInfo.setOwnPutCode(1); result = MCRORCIDMetadataUtils.transformFlagContent(flagContent); expectedResult = "{\"userInfos\":[{\"orcid\":\"ORCID\",\"works\":{\"own\":1}}]}"; assertEquals(result, expectedResult); } @Test public void testDoSetORCIDFlagContent() { final MCRObject object = new MCRObject(); final MCRORCIDFlagContent flagContent = new MCRORCIDFlagContent(); MCRORCIDMetadataUtils.doSetORCIDFlagContent(object, flagContent); List<String> flags = object.getService().getFlags("MyCoRe-ORCID"); assertEquals(flags.size(), 1); final MCRORCIDUserInfo userInfo = new MCRORCIDUserInfo("ORCID"); flagContent.getUserInfos().add(userInfo); MCRORCIDMetadataUtils.doSetORCIDFlagContent(object, flagContent); flags = object.getService().getFlags("MyCoRe-ORCID"); assertEquals(flags.size(), 1); final MCRORCIDFlagContent result = MCRORCIDMetadataUtils.transformFlagContentString(flags.get(0)); assertEquals(flagContent, result); } @Test public void testDoRemoveORCIDFlag() { final MCRObject object = new MCRObject(); final MCRORCIDFlagContent flagContent = new MCRORCIDFlagContent(); MCRORCIDMetadataUtils.doSetORCIDFlagContent(object, flagContent); MCRORCIDMetadataUtils.removeORCIDFlag(object); assertEquals(object.getService().getFlags("MyCoRe-ORCID").size(), 0); } }
4,175
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDCommandsTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/test/java/org/mycore/orcid2/cli/MCRORCIDCommandsTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.cli; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import org.mycore.common.MCRJPATestCase; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.user.MCRORCIDUser; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; public class MCRORCIDCommandsTest extends MCRJPATestCase { private static final String ORCID_ID = "0000-0001-2345-6789"; private static final String ORCID_ACCESS_TOKEN = "token"; @Test public void migrateORCIDTokenAttributeTest() { final MCRUser user = new MCRUser("junit"); user.setUserAttribute(MCRORCIDCommands.ORCID_TOKEN_ATTRIBUTE_NAME, ORCID_ACCESS_TOKEN); user.setUserAttribute(MCRORCIDUser.ATTR_ORCID_ID, ORCID_ID); MCRUserManager.createUser(user); MCRORCIDCommands.migrateORCIDTokenAttributes(); assertEquals(2, user.getAttributes().size()); assertNull(user.getUserAttribute(MCRORCIDCommands.ORCID_TOKEN_ATTRIBUTE_NAME)); assertEquals(ORCID_ID, user.getUserAttribute(MCRORCIDUser.ATTR_ORCID_ID)); assertNotNull(user.getUserAttribute(MCRORCIDUser.ATTR_ORCID_CREDENTIAL + ORCID_ID)); final MCRORCIDUser orcidUser = new MCRORCIDUser(user); final MCRORCIDCredential credential = orcidUser.getCredentialByORCID(ORCID_ID); assertNotNull(credential); assertEquals(ORCID_ACCESS_TOKEN, credential.getAccessToken()); } }
2,275
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUserTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/test/java/org/mycore/orcid2/user/MCRORCIDUserTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.user; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.time.LocalDate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mycore.common.MCRJPATestCase; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; public class MCRORCIDUserTest extends MCRJPATestCase { private static final Logger LOGGER = LogManager.getLogger(); private static final String ORCID = "0000-0001-2345-6789"; private static final String ACCESS_TOKEN = "accessToken"; @Test public void testStoreGetCredentials() { MCRUser user = new MCRUser("junit"); MCRUserManager.createUser(user); MCRORCIDUser orcidUser = new MCRORCIDUser(user); assertEquals(0, orcidUser.getCredentials().size()); final MCRORCIDCredential credential = new MCRORCIDCredential(ACCESS_TOKEN); orcidUser.addCredential(ORCID, credential); // id_orcid + orcid_credential_orcid assertEquals(2, user.getAttributes().size()); assertNotNull(user.getUserAttribute("orcid_credential_" + ORCID)); assertEquals(ORCID, user.getUserAttribute("id_orcid")); assertEquals(credential, orcidUser.getCredentialByORCID(ORCID)); } @Test public void testRemoveAllCredentials() { MCRUser user = new MCRUser("junit"); MCRUserManager.createUser(user); MCRORCIDUser orcidUser = new MCRORCIDUser(user); final MCRORCIDCredential credential = new MCRORCIDCredential(ACCESS_TOKEN); orcidUser.addCredential(ORCID, credential); user.setUserAttribute("test", "test"); orcidUser.removeAllCredentials(); // id_orcid + test assertEquals(2, user.getAttributes().size()); assertEquals(ORCID, user.getUserAttribute("id_orcid")); assertEquals("test", user.getUserAttribute("test")); } @Test public void testSerialization() { final MCRORCIDCredential credential = new MCRORCIDCredential(ACCESS_TOKEN); credential.setTokenType("bearer"); credential.setRefreshToken("refreshToken"); credential.setScope("/read-limited"); credential.setExpiration(LocalDate.now()); final String credentialString = MCRORCIDUser.serializeCredential(credential); LOGGER.info(credentialString); final MCRORCIDCredential result = MCRORCIDUser.deserializeCredential(credentialString); assertEquals(credential.getAccessToken(), result.getAccessToken()); assertEquals(credential.getRefreshToken(), result.getRefreshToken()); assertEquals(credential.getTokenType(), result.getTokenType()); assertEquals(credential.getScope(), result.getScope()); assertEquals(credential.getExpiration(), result.getExpiration()); } }
3,668
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDConstants.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/MCRORCIDConstants.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2; import java.util.List; import org.mycore.common.config.MCRConfiguration2; /** * Provides general constants. */ public class MCRORCIDConstants { /** * Config prefix of mycore-orcid2 properties. */ public static final String CONFIG_PREFIX = "MCR.ORCID2."; /** * ORCID Base URL. */ public static final String ORCID_BASE_URL = MCRConfiguration2.getStringOrThrow(CONFIG_PREFIX + "BaseURL"); /** * List of all language codes supported by ORCID. */ public static final List<String> SUPPORTED_LANGUAGE_CODES = MCRConfiguration2 .getString(CONFIG_PREFIX + "SupportedLanguageCodes").stream() .flatMap(MCRConfiguration2::splitValue).toList(); }
1,466
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/MCRORCIDUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.streams.MCRMD5InputStream; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.mods.MCRMODSWrapper; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.oauth.MCRORCIDOAuthClient; import org.mycore.orcid2.util.MCRIdentifier; /** * Provides utility methods. */ public class MCRORCIDUtils { private static final MCRContentTransformer T_ORCID_MODS_FILTER = MCRContentTransformerFactory .getTransformer("ORCIDMODSFilter"); private static final List<String> TRUSTED_IDENTIFIER_TYPES = MCRConfiguration2 .getString(MCRORCIDConstants.CONFIG_PREFIX + "Object.TrustedIdentifierTyps").stream() .flatMap(MCRConfiguration2::splitValue).collect(Collectors.toList()); private static final List<String> PUBLISH_STATES = MCRConfiguration2 .getString(MCRORCIDConstants.CONFIG_PREFIX + "Work.PublishStates").stream() .flatMap(MCRConfiguration2::splitValue).toList(); /** * MD5 hashes String. * * @param input the input * @return hash as String */ public static String hashString(String input) { final byte[] bytes = input.getBytes(StandardCharsets.UTF_8); final MessageDigest md5Digest = MCRMD5InputStream.buildMD5Digest(); md5Digest.update(bytes); final byte[] digest = md5Digest.digest(); return MCRMD5InputStream.getMD5String(digest); } /** * Checks if MCRObjects' state is ready to publish. * * @param object the MCRObject * @return true if state is ready to publish or there is not state */ public static boolean checkPublishState(MCRObject object) { return getStateValue(object).map(s -> checkPublishState(s)).orElse(true); } /** * Checks if state is ready to publish. * * @param state the state * @return true if state is ready to publish */ public static boolean checkPublishState(String state) { if (PUBLISH_STATES.contains(state)) { return true; } return PUBLISH_STATES.size() == 1 && PUBLISH_STATES.contains("*"); } /** * Checks if MCRObject has empty MODS. * * @param object the MCRObject * @return true if MCRObject's MODS has children */ public static boolean checkEmptyMODS(MCRObject object) { final MCRMODSWrapper wrapper = new MCRMODSWrapper(object); return !wrapper.getMODS().getChildren().isEmpty(); } /** * Filters MCRObject. * * @param object the MCRObject * @return filtered MCRObject * @throws MCRORCIDException if filtering fails */ public static MCRObject filterObject(MCRObject object) { try { final MCRContent filtertedObjectContent = T_ORCID_MODS_FILTER .transform(new MCRJDOMContent(object.createXML())); return new MCRObject(filtertedObjectContent.asXML()); } catch (IOException | JDOMException e) { throw new MCRORCIDException("Filter transformation failed", e); } } /** * Compares String with auth client's client id. * * @param sourcePath source path * @return true if source path equals client id */ public static boolean isCreatedByThisApplication(String sourcePath) { return Objects.equals(sourcePath, MCRORCIDOAuthClient.CLIENT_ID); } /** * Builds a modsCollection Element and adds given elements. * * @param elements List of elements * @return Element containing elements */ public static Element buildMODSCollection(List<Element> elements) { final Element modsCollection = new Element("modsCollection", MCRConstants.MODS_NAMESPACE); elements.forEach(w -> modsCollection.addContent(w)); return modsCollection; } /** * Extracts all ORCID name identifiers of MCRObject. * * @param object the MCRObject * @return Set of ORCID MCRIdentifier */ public static Set<String> getORCIDs(MCRObject object) { return new MCRMODSWrapper(object).getElements("mods:name/mods:nameIdentifier[@type='orcid']").stream() .map(Element::getTextTrim).collect(Collectors.toSet()); } /** * Lists mods:name Elements. * * @param wrapper the MCRMODSWrapper * @return List of name elements */ public static List<Element> listNameElements(MCRMODSWrapper wrapper) { return wrapper.getElements("mods:name"); } /** * Returns mods:nameIdentifer. * * @param nameElement the mods:name Element * @return Set of MCRIdentifier */ public static Set<MCRIdentifier> getNameIdentifiers(Element nameElement) { return nameElement.getChildren("nameIdentifier", MCRConstants.MODS_NAMESPACE).stream() .map(e -> getIdentfierFromElement(e)) .collect(Collectors.toSet()); } /** * Returns mods:nameIdentifer. * * @param wrapper the MCRMODSWrapper * @return Set of MCRIdentifier */ public static Set<MCRIdentifier> getNameIdentifiers(MCRMODSWrapper wrapper) { return wrapper.getElements("mods:nameIdentifier").stream().map(e -> getIdentfierFromElement(e)) .collect(Collectors.toSet()); } /** * Checks if identifier name is trusted. * Trusted identifier types can be defined as follows: * * MCR.ORCID2.Object.TrustedIdentifierTypes= * * If empty, identifier is trusted * * @param name identifier name * @return true if identifier is trusted */ public static boolean checkTrustedIdentifier(String name) { if (TRUSTED_IDENTIFIER_TYPES.size() > 0) { return TRUSTED_IDENTIFIER_TYPES.contains(name); } return true; } private static MCRIdentifier getIdentfierFromElement(Element element) { return new MCRIdentifier(element.getAttributeValue("type"), element.getTextTrim()); } private static Optional<String> getStateValue(MCRObject object) { return Optional.ofNullable(object.getService().getState()).map(MCRCategoryID::getId); } }
7,616
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDTransformerHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/MCRORCIDTransformerHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2; import java.io.IOException; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.common.MCRConstants; import org.mycore.common.content.MCRStringContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.orcid2.exception.MCRORCIDTransformationException; /** * Provides transformer methods. */ public class MCRORCIDTransformerHelper { private static final MCRContentTransformer T_BIBTEX2MODS = MCRContentTransformerFactory .getTransformer("BibTeX2MODS"); /** * Converts BibTeX String to MODS. * * @param bibTeX BibTex String * @return MODS Element * @throws MCRORCIDTransformationException if transformation fails */ public static Element transformBibTeXToMODS(String bibTeX) { Element modsCollection = null; try { modsCollection = T_BIBTEX2MODS.transform(new MCRStringContent(bibTeX)).asXML().getRootElement(); } catch (IOException | JDOMException e) { throw new MCRORCIDTransformationException("BibTeX to mods transformation failed", e); } final Element mods = modsCollection.getChild("mods", MCRConstants.MODS_NAMESPACE); // Remove mods:extension containing the original BibTeX: mods.removeChildren("extension", MCRConstants.MODS_NAMESPACE); return mods; } }
2,197
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDOAuthAccessTokenResponse.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/oauth/MCRORCIDOAuthAccessTokenResponse.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.oauth; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; /** * Represents the ORCID OAuth access token response. * * See <a href="https://members.orcid.org/api/oauth/3legged-oauth">ORCID documentation</a> */ @XmlRootElement(name = "ORCIDOAuthAccessTokenResponse") public class MCRORCIDOAuthAccessTokenResponse { private String accessToken; private String tokenType; private String refreshToken; private String expiresIn; private String name; private String scope; private String orcid; /** * Default constructor. */ @SuppressWarnings("PMD.UnnecessaryConstructor") public MCRORCIDOAuthAccessTokenResponse() { // This explicit constructor is required by JAXB } /** * Returns the access token. * * @return access token */ @JsonProperty("access_token") @XmlElement(name = "accessToken") public String getAccessToken() { return accessToken; } /** * Sets the access token. * * @param accessToken the access token */ public void setAccessToken(String accessToken) { this.accessToken = accessToken; } /** * Returns the refresh token. * * @return refresh token */ @JsonProperty("refresh_token") @XmlElement(name = "refreshToken") public String getRefreshToken() { return refreshToken; } /** * Sets the refresh token. * * @param refreshToken the refresh token */ public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } /** * Returns the token type. * * @return token type */ @JsonProperty("token_type") @XmlElement(name = "tokenType") public String getTokenType() { return tokenType; } /** * Sets the token type. * * @param tokenType the token type */ public void setTokenType(String tokenType) { this.tokenType = tokenType; } /** * Returns the token life time in seconds. * * @return token life time */ @JsonProperty("expires_in") @XmlElement(name = "expiresIn") public String getExpiresIn() { return expiresIn; } /** * Sets the life time in seconds. * * @param expiresIn life time in seconds */ public void setExpiresIn(String expiresIn) { this.expiresIn = expiresIn; } /** * Returns the scope. * * @return scope */ @JsonProperty("scope") @XmlElement(name = "scope") public String getScope() { return scope; } /** * Sets the scope. * * @param scope scope to set */ public void setScope(String scope) { this.scope = scope; } /** * Returns the name. * * @return name */ @JsonProperty("name") @XmlElement(name = "name") public String getName() { return name; } /** * Sets the name. * * @param name the name */ public void setName(String name) { this.name = name; } /** * Returns the ORCID iD. * * @return ORCID iD */ @JsonProperty("orcid") @XmlElement(name = "orcid") public String getORCID() { return orcid; } /** * Sets the ORCID iD. * * @param orcid the ORCID iD */ public void setORCID(String orcid) { this.orcid = orcid; } @Override public int hashCode() { return Objects.hash(accessToken, tokenType, refreshToken, expiresIn, name, scope, orcid); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRORCIDOAuthAccessTokenResponse other = (MCRORCIDOAuthAccessTokenResponse) obj; return Objects.equals(accessToken, other.accessToken) && Objects.equals(expiresIn, other.expiresIn) && Objects.equals(name, other.name) && Objects.equals(refreshToken, other.refreshToken) && Objects.equals(scope, other.scope) && Objects.equals(tokenType, other.tokenType) && Objects.equals(orcid, other.orcid); } }
5,211
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDOAuthClient.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/oauth/MCRORCIDOAuthClient.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.oauth; import java.util.Objects; import org.mycore.common.config.MCRConfiguration2; import org.mycore.orcid2.MCRORCIDConstants; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.Form; import jakarta.ws.rs.core.Response; /** * Client for the OAuth2 API of orcid.org. * Used to exchange or revoke access tokens. * Minimum configuration requires to set: * * MCR.ORCID2.BaseURL * MCR.ORCID2.OAuth.ClientID * MCR.ORCID2.OAuth.ClientSecret */ public class MCRORCIDOAuthClient { private static final String CONFIG_PREFIX = MCRORCIDConstants.CONFIG_PREFIX + "OAuth."; /** * Client id of the client. */ public static final String CLIENT_ID = MCRConfiguration2.getStringOrThrow(CONFIG_PREFIX + "ClientID"); private static final String CLIENT_SECRET = MCRConfiguration2.getStringOrThrow(CONFIG_PREFIX + "ClientSecret"); private final WebTarget webTarget; private MCRORCIDOAuthClient() { webTarget = ClientBuilder.newClient().target(MCRORCIDConstants.ORCID_BASE_URL).path("oauth"); } /** * Initializes and returns client instance. * * @return client instance */ public static MCRORCIDOAuthClient getInstance() { return LazyInstanceHelper.INSTANCE; } /** * Revokes given bearer access token. * * @param token revoke token * @throws MCRORCIDRequestException if request fails */ public void revokeToken(String token) { Form form = new Form(); form.param("client_id", CLIENT_ID); form.param("client_secret", CLIENT_SECRET); form.param("token", token); final Response response = webTarget.path("revoke").request().post(Entity.form(form)); if (!Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.SUCCESSFUL)) { handleError(response); } } /** * Exchanges authorization code for an MCRORCIDOAuthAccessTokenResponse. * * @param code the ORCID auth code * @param redirectURI the redirect URI * @return the MCRORCIDOAuthAccessTokenResponse * @throws MCRORCIDRequestException if request fails * @see MCRORCIDOAuthAccessTokenResponse */ public MCRORCIDOAuthAccessTokenResponse exchangeCode(String code, String redirectURI) { Form form = new Form(); form.param("client_id", CLIENT_ID); form.param("client_secret", CLIENT_SECRET); form.param("grant_type", "authorization_code"); form.param("code", code); form.param("redirect_uri", redirectURI); final Response response = webTarget.path("token").request().post(Entity.form(form)); if (!Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.SUCCESSFUL)) { handleError(response); } return response.readEntity(MCRORCIDOAuthAccessTokenResponse.class); } private void handleError(Response response) { throw new MCRORCIDRequestException(response); } private static class LazyInstanceHelper { static final MCRORCIDOAuthClient INSTANCE = new MCRORCIDOAuthClient(); } }
4,036
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDOAuthResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/oauth/resources/MCRORCIDOAuthResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.oauth.resources; import java.io.InputStream; import java.net.URI; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJAXBContent; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.jersey.MCRJerseyUtil; import org.mycore.frontend.jersey.access.MCRRequireLogin; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import org.mycore.orcid2.MCRORCIDConstants; import org.mycore.orcid2.MCRORCIDUtils; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.oauth.MCRORCIDOAuthAccessTokenResponse; import org.mycore.orcid2.oauth.MCRORCIDOAuthClient; import org.mycore.orcid2.user.MCRORCIDSessionUtils; import org.mycore.orcid2.user.MCRORCIDUser; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; import jakarta.servlet.http.HttpServletRequest; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.UriBuilder; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; /** * Resource for ORCID OAuth methods. */ @Path("orcid/oauth") public class MCRORCIDOAuthResource { private static final Logger LOGGER = LogManager.getLogger(MCRORCIDOAuthResource.class); private static final String CONFIG_PREFIX = MCRORCIDConstants.CONFIG_PREFIX + "OAuth."; private static final String SCOPE = MCRConfiguration2.getString(CONFIG_PREFIX + "Scope").orElse(null); private static final boolean IS_PREFILL_REGISTRATION_FORM = MCRConfiguration2 .getOrThrow(MCRORCIDConstants.CONFIG_PREFIX + "PreFillRegistrationForm", Boolean::parseBoolean); private final String redirectURI = "rsc/orcid/oauth"; @Context HttpServletRequest req; /** * Handles ORCID code request. * * @param code the code * @param state the state * @param error the error * @param errorDescription the errorDescription * @return Response * @throws WebApplicationException is request is invalid or error */ @GET @Produces(MediaType.TEXT_HTML) @MCRRestrictedAccess(MCRRequireLogin.class) public InputStream handleCodeRequest(@QueryParam("code") String code, @QueryParam("state") String state, @QueryParam("error") String error, @QueryParam("error_description") String errorDescription) { try { MCRContent result = null; if (code != null) { final String userID = MCRUserManager.getCurrentUser().getUserID(); if (state == null || !Objects.equals(MCRORCIDUtils.hashString(userID), state)) { throw new WebApplicationException(Status.BAD_REQUEST); } final String codeTrimmed = code.trim(); if (codeTrimmed.isEmpty()) { throw new WebApplicationException(Status.BAD_REQUEST); } result = handleCode(codeTrimmed); } else if (error != null) { result = handleError(error, errorDescription); } else { throw new WebApplicationException(Status.BAD_REQUEST); } return MCRJerseyUtil.transform(result.asXML(), req).getInputStream(); } catch (Exception e) { throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } } /** * Returns authorization URI * * @param scope the scope * @return auth URI * @throws WebApplicationException if scope is null */ @GET @Path("init") @MCRRestrictedAccess(MCRRequireLogin.class) public Response getOAuthURI(@QueryParam("scope") String scope) { String langCode = MCRSessionMgr.getCurrentSession().getCurrentLanguage(); if (!MCRORCIDConstants.SUPPORTED_LANGUAGE_CODES.contains(langCode)) { // use english as fallback langCode = "en"; } final String userID = MCRUserManager.getCurrentUser().getUserID(); final String state = MCRORCIDUtils.hashString(userID); if (scope != null) { return Response.seeOther(buildRequestCodeURI(scope, state, langCode)).build(); } else if (SCOPE != null) { return Response.seeOther(buildRequestCodeURI(SCOPE, state, langCode)).build(); } else { throw new WebApplicationException("Scope is required", Status.BAD_REQUEST); } } /** * Builds the URL where to redirect the user's browser to initiate a three-way * authorization and request permission to access the given scopes. If * * MCR.ORCID2.PreFillRegistrationForm=true * * submits the current user's email address, first and last name to the ORCID * registration form to simplify registration. May be disabled for more data * privacy. * * @param code the code * @return url to request authorization code */ private MCRContent handleCode(String code) { try { final MCRORCIDOAuthAccessTokenResponse accessTokenResponse = MCRORCIDOAuthClient.getInstance() .exchangeCode(code, MCRFrontendUtil.getBaseURL() + redirectURI); final MCRORCIDCredential credential = accessTokenResponseToUserCredential(accessTokenResponse); final MCRORCIDUser orcidUser = MCRORCIDSessionUtils.getCurrentUser(); orcidUser.addCredential(accessTokenResponse.getORCID(), credential); MCRUserManager.updateUser(orcidUser.getUser()); return marshalOAuthAccessTokenResponse(accessTokenResponse); } catch (IllegalArgumentException e) { throw new MCRORCIDException("Cannot create response", e); } catch (MCRORCIDRequestException e) { throw new MCRORCIDException( "Cannot exchange token. Response was: " + e.getResponse().readEntity(String.class), e); } } private MCRContent handleError(String error, String errorDescription) { LOGGER.error(error); try { return marshalOAuthErrorResponse(new MCRORCIDOAuthErrorResponse(error, errorDescription)); } catch (IllegalArgumentException e) { throw new MCRORCIDException("Cannot create response", e); } } private MCRORCIDCredential accessTokenResponseToUserCredential(MCRORCIDOAuthAccessTokenResponse response) { final MCRORCIDCredential credential = new MCRORCIDCredential(response.getAccessToken()); credential.setTokenType(response.getTokenType()); credential.setRefreshToken(response.getRefreshToken()); final LocalDate expireDate = LocalDateTime.now(ZoneId.systemDefault()) .plusSeconds(Integer.parseInt(response.getExpiresIn())) .toLocalDate(); credential.setExpiration(expireDate); credential.setScope(response.getScope()); return credential; } private static MCRContent marshalOAuthErrorResponse(MCRORCIDOAuthErrorResponse errorResponse) { try { return new MCRJAXBContent(JAXBContext.newInstance(MCRORCIDOAuthErrorResponse.class), errorResponse); } catch (JAXBException e) { throw new IllegalArgumentException("Invalid auth response"); } } private static MCRContent marshalOAuthAccessTokenResponse(MCRORCIDOAuthAccessTokenResponse tokenResponse) { try { return new MCRJAXBContent(JAXBContext.newInstance(MCRORCIDOAuthAccessTokenResponse.class), tokenResponse); } catch (JAXBException e) { throw new IllegalArgumentException("Invalid token response"); } } private URI buildRequestCodeURI(String scope, String state, String langCode) { final UriBuilder builder = UriBuilder.fromPath(MCRORCIDConstants.ORCID_BASE_URL); builder.path("oauth/authorize"); builder.queryParam("redirect_uri", MCRFrontendUtil.getBaseURL() + redirectURI); builder.queryParam("client_id", MCRORCIDOAuthClient.CLIENT_ID); builder.queryParam("response_type", "code"); builder.queryParam("scope", scope); builder.queryParam("prompt", "login"); builder.queryParam("lang", langCode); builder.queryParam("state", state); if (IS_PREFILL_REGISTRATION_FORM) { preFillRegistrationForm(builder); } return builder.build(); } /** * * Adds current user's email address, first and last name as params to URIBuilder. * * @param builder the builder * See <a href="https://members.orcid.org/api/resources/customize">ORCID documentation</a> */ private static void preFillRegistrationForm(UriBuilder builder) { MCRUser user = MCRUserManager.getCurrentUser(); String email = user.getEMailAddress(); if (email != null) { builder.queryParam("email", email); } String name = user.getRealName(); String firstName = null; String lastName = name; if (name.contains(",")) { String[] nameParts = name.split(","); if (nameParts.length == 2) { firstName = nameParts[1].trim(); lastName = nameParts[0].trim(); } } else if (name.contains(" ")) { String[] nameParts = name.split(" "); if (nameParts.length == 2) { firstName = nameParts[0].trim(); lastName = nameParts[1].trim(); } } if (firstName != null) { builder.queryParam("given_names", firstName); } if (lastName != null) { builder.queryParam("family_names", lastName); } } @XmlRootElement(name = "ORCIDOAuthErrorResponse") static class MCRORCIDOAuthErrorResponse { @XmlElement(name = "error") private final String error; @XmlElement(name = "errorDescription") private final String errorDescription; MCRORCIDOAuthErrorResponse() { this(null, null); } MCRORCIDOAuthErrorResponse(String error, String errorDescription) { this.error = error; this.errorDescription = errorDescription; } } }
11,683
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDSearchImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/client/MCRORCIDSearchImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.client; import org.mycore.orcid2.client.MCRORCIDSearch; /** * See {@link org.mycore.orcid2.client.MCRORCIDSearch}. */ public enum MCRORCIDSearchImpl implements MCRORCIDSearch { DEFAULT("search"), EXPANDED("expanded-search"); private final String path; MCRORCIDSearchImpl(String path) { this.path = path; } @Override public String getPath() { return path; } }
1,166
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDClientErrorHandlerImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/client/MCRORCIDClientErrorHandlerImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.client; import org.mycore.orcid2.client.MCRORCIDClientErrorHandler; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import org.orcid.jaxb.model.v3.release.error.OrcidError; import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.core.Response; /** * See {@link org.mycore.orcid2.client.MCRORCIDClientErrorHandler}. */ public class MCRORCIDClientErrorHandlerImpl implements MCRORCIDClientErrorHandler { @Override public void handleErrorResponse(Response response) { if (response.hasEntity()) { response.bufferEntity(); try { final OrcidError error = response.readEntity(OrcidError.class); throw new MCRORCIDRequestException(error.getDeveloperMessage(), response); } catch (ProcessingException e) { try { final String error = response.readEntity(String.class); throw new MCRORCIDRequestException(error, response); } catch (ProcessingException f) { // ignore } } } throw new MCRORCIDRequestException("Unknown error", response); } }
1,942
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDClientHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/client/MCRORCIDClientHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.client; import java.util.Locale; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.orcid2.client.MCRORCIDClientFactory; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.user.MCRORCIDUserUtils; import org.orcid.jaxb.model.v3.release.error.OrcidError; import jakarta.ws.rs.core.Response; /** * Provides utility methods for v3 client. */ public class MCRORCIDClientHelper { private static final Logger LOGGER = LogManager.getLogger(); /** * Fetches API with best credential. * If credential exist for an ORCID iD, the Member API is requested with the token. * If a problem occurs during the request or no credential exist, * the general Member/Public API is requested as a fallback. * * @param orcid the ORCID iD * @param section the section * @param <T> the result class * @param valueType type of the response * @param putCodes optional put codes * @return the result as specified type * @throws MCRORCIDRequestException if the request fails */ public static <T> T fetchWithBestCredentials(String orcid, MCRORCIDSectionImpl section, Class<T> valueType, long... putCodes) { if (getClientFactory().checkMemberMode()) { MCRORCIDCredential credential = null; try { credential = MCRORCIDUserUtils.getCredentialByORCID(orcid); } catch (MCRORCIDException e) { LOGGER.warn("Error with credential for {}. Trying to use read client as fallback...", orcid, e); } if (credential != null) { try { return getClientFactory().createUserClient(orcid, credential).fetch(section, valueType, putCodes); } catch (MCRORCIDRequestException e) { final Response response = e.getResponse(); if (Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.CLIENT_ERROR)) { LOGGER.info( "Request with credential for orcid {} has failed with status code {} and error: {}\n" + "Token has probably expired. Trying to use read client as fallback...", orcid, response.getStatus(), e.getMessage()); } else { throw e; } } } } return getClientFactory().createReadClient().fetch(orcid, section, valueType, putCodes); } /** * Returns debug string for OrcidError. * * @param error the OrcidError * @return the debug message */ public static String createDebugMessageFromORCIDError(OrcidError error) { final StringBuilder builder = new StringBuilder(); builder.append(String.format(Locale.ROOT, "response code: %d\n", error.getResponseCode())); builder.append(String.format(Locale.ROOT, "developer message: %s\n", error.getDeveloperMessage())); builder.append(String.format(Locale.ROOT, "user message: %s\n", error.getUserMessage())); builder.append(String.format(Locale.ROOT, "error code: %s", error.getErrorCode())); return builder.toString(); } /** * Returns v3 MCRORCIDClientFactory. * * @return MCRORCIDClientFactory */ public static MCRORCIDClientFactory getClientFactory() { return MCRORCIDClientFactory.getInstance("V3"); } }
4,434
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDSectionImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/client/MCRORCIDSectionImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.client; import org.mycore.orcid2.client.MCRORCIDSection; /** * See {@link org.mycore.orcid2.client.MCRORCIDSection}. */ public enum MCRORCIDSectionImpl implements MCRORCIDSection { ALL(""), ACTIVITIES("activities"), ADDRESS("address"), BIOGRAPHY("biography"), DISTINCTION("distinction"), DISTINCTION_SUMMARY("distinction/summaray"), DISTINCTIONS("distinctions"), EDUCATION("education"), EDUCATION_SUMMARY("education/summary"), EDUCATIONS("educations"), EMAIL("email"), EMPLOYMENT("employment"), EMPLOYMENT_SUMMARY("employment/summary"), EMPLOYMENTS("employments"), EXTERNAL_IDENTIFIERS("external-identifiers"), FUNDING("funding"), FUNDING_SUMMARY("funding/summary"), FUNDINGS("fundings"), INVITED_POSITION("invited-position"), INVITED_POSITION_SUMMARY("invited-position/summary"), INVITED_POSITIONS("invited-positions"), KEYWORDS("keywords"), MEMBERSHIP("membership"), MEMBERSHIP_SUMMARY("membership/summary"), MEMBERSHIPS("memberships"), NOTIFICATION_PERMISSION("notification-permission"), OTHER_NAMES("other-names"), PEER_REVIEW("peer-review"), PEER_REVIEW_SUMMARY("peer-review/summary"), PEER_REVIEWS("peer-reviews"), PERSON("person"), PERSON_DETAILS("person-details"), QUALIFICATION("qualification"), QUALIFICATION_SUMMARY("qualification/summary"), QUALIFICATIONS("qualifications"), RESEARCH_RESOURCE("research-resource"), RESEARCH_RESOURCE_SUMMARY("research-resource/summary"), RESEARCH_RESOURCES("research_resources"), RESEARCHER_URLS("researcher-urls"), SERVICE("service"), SERVICE_SUMMARY("service/summary"), SERVICES("services"), WORK("work"), WORK_SUMMARY("work/summary"), WORKS("works"); private final String path; MCRORCIDSectionImpl(String path) { this.path = path; } @Override public String getPath() { return path; } }
2,717
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkTransformerHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/transformer/MCRORCIDWorkTransformerHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.transformer; import java.io.IOException; import java.util.Objects; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.common.MCRConstants; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJAXBContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.mods.merger.MCRMergeTool; import org.mycore.orcid2.MCRORCIDTransformerHelper; import org.mycore.orcid2.exception.MCRORCIDTransformationException; import org.orcid.jaxb.model.common.CitationType; import org.orcid.jaxb.model.v3.release.record.Citation; import org.orcid.jaxb.model.v3.release.record.Work; import org.orcid.jaxb.model.v3.release.record.summary.WorkSummary; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Unmarshaller; /** * Provides helper functions to transform between Work or WorkSummary and MODS MCRContent. */ public class MCRORCIDWorkTransformerHelper { private static final MCRContentTransformer T_MODS_WORK = MCRContentTransformerFactory .getTransformer("MODS2ORCIDv3Work"); private static final MCRContentTransformer T_WORK_MODS = MCRContentTransformerFactory .getTransformer("BaseORCIDv3Work2MODS"); private static final MCRContentTransformer T_SUMMARY_MODS = MCRContentTransformerFactory .getTransformer("BaseORCIDv3WorkSummary2MODS"); private static JAXBContext context = null; static { try { context = JAXBContext.newInstance(new Class[] { Work.class, WorkSummary.class }); } catch (JAXBException e) { throw new IllegalArgumentException("Could not init jaxb context"); } } /** * Transforms MODS MCRContent to Work. * * @param content the MODS MCRContent * @return the Work * @throws MCRORCIDTransformationException if transformation failed */ public static Work transformContent(MCRContent content) { try { return unmarshalWork(new MCRJDOMContent(MCRXMLParserFactory.getValidatingParser() .parseXML(T_MODS_WORK.transform(content)))); } catch (IOException | JDOMException e) { throw new MCRORCIDTransformationException(e); } } /** * Transforms Work to MODS MCRContent. * Merges BibLaTeX using transformer * * @param work the Work * @return the MODS MCRContent * @throws MCRORCIDTransformationException if transformation failed */ public static MCRContent transformWork(Work work) { checkContext(); final MCRJAXBContent<Work> workContent = new MCRJAXBContent(context, work); Element mods = null; try { mods = T_WORK_MODS.transform(workContent).asXML().detachRootElement() .getChild("mods", MCRConstants.MODS_NAMESPACE).detach(); } catch (IOException | JDOMException e) { throw new MCRORCIDTransformationException(e); } final Citation citation = work.getWorkCitation(); if (citation != null && Objects.equals(citation.getWorkCitationType(), CitationType.BIBTEX)) { final Element modsBibTeX = MCRORCIDTransformerHelper.transformBibTeXToMODS(citation.getCitation()); MCRMergeTool.merge(mods, modsBibTeX); } return new MCRJDOMContent(mods); } /** * Transforms WorkSummary to mods MCRContent. * * @param work the WorkSummary * @return the MODS MCRContent * @throws MCRORCIDTransformationException if transformation failed */ public static MCRContent transformWorkSummary(WorkSummary work) { checkContext(); final MCRJAXBContent<WorkSummary> workContent = new MCRJAXBContent(context, work); Element mods = null; try { mods = T_SUMMARY_MODS.transform(workContent).asXML().detachRootElement() .getChild("mods", MCRConstants.MODS_NAMESPACE).detach(); } catch (IOException | JDOMException e) { throw new MCRORCIDTransformationException(e); } return new MCRJDOMContent(mods); } private static Work unmarshalWork(MCRContent content) { checkContext(); try { final Unmarshaller unmarshaller = context.createUnmarshaller(); return (Work) unmarshaller.unmarshal(content.getInputSource()); } catch (IOException | JAXBException e) { throw new MCRORCIDTransformationException(e); } } private static void checkContext() { if (context == null) { throw new MCRORCIDTransformationException("Jaxb context is not initialized"); } } }
5,622
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDObjectResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/rest/resources/MCRORCIDObjectResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.rest.resources; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRPersistenceException; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.MCRUserInformation; import org.mycore.common.content.MCRJDOMContent; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.jersey.access.MCRRequireLogin; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import org.mycore.orcid2.MCRORCIDUtils; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.user.MCRORCIDSessionUtils; import org.mycore.orcid2.user.MCRORCIDUser; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.orcid2.v3.transformer.MCRORCIDWorkTransformerHelper; import org.mycore.orcid2.v3.work.MCRORCIDWorkService; import org.mycore.orcid2.v3.work.MCRORCIDWorkUtils; import org.mycore.restapi.annotations.MCRRequireTransaction; import org.orcid.jaxb.model.v3.release.record.Work; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; /** * Basic resource for general methods. */ @Path("/v1/") public class MCRORCIDObjectResource { private static final Logger LOGGER = LogManager.getLogger(); /** * Returns the publication status for a given MCRObjectID in the current user's ORCID profile, e.g. * * { * "isUsersPublication": true, * "isInORCIDProfile": true, * } * * @param objectID the MCRObjectID * @return the publication status * @throws WebApplicationException if request fails */ @GET @Path("object-status/v3/{objectID}") @Produces(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRRequireLogin.class) public MCRORCIDPublicationStatus getObjectStatus(@PathParam("objectID") MCRObjectID objectID) { final MCRObject object = getObject(objectID); final MCRORCIDUser orcidUser = MCRORCIDSessionUtils.getCurrentUser(); final Set<String> orcids = getMatchingORCIDs(object, orcidUser); if (orcids.isEmpty()) { // assumption that a publication cannot be in the profile, it is if not users. return new MCRORCIDPublicationStatus(false, false); } if (orcids.size() > 1) { // should not happen throw new WebApplicationException(Status.BAD_REQUEST); } final String orcid = orcids.iterator().next(); final MCRORCIDCredential credential = orcidUser.getCredentialByORCID(orcid); if (credential == null) { return new MCRORCIDPublicationStatus(true, false); } try { final Work work = MCRORCIDWorkTransformerHelper.transformContent(new MCRJDOMContent(object.createXML())); final Set<MCRIdentifier> identifiers = MCRORCIDWorkUtils.listTrustedIdentifiers(work); final boolean result = new MCRORCIDWorkService(orcid, credential).checkOwnWorkExists(identifiers); return new MCRORCIDPublicationStatus(true, result); } catch (Exception e) { LOGGER.error("Error while retrieving status: ", e); throw new WebApplicationException(Status.BAD_REQUEST); } } /** * Creates MCRObject in ORCID profile for given MCRORCIDCredential. * * @param objectID the MCRObjectID * @return the Response * @throws WebApplicationException if request fails * @see MCRORCIDWorkService#createWork */ @POST @Path("create-work/v3/{objectID}") @MCRRestrictedAccess(MCRRequireLogin.class) @MCRRequireTransaction public Response createObject(@PathParam("objectID") MCRObjectID objectID) { final MCRObject object = getObject(objectID); final MCRORCIDUser orcidUser = MCRORCIDSessionUtils.getCurrentUser(); final String orcid = getMatchingORCID(object, orcidUser); final MCRORCIDCredential credential = getCredential(orcidUser, orcid); final MCRSession session = MCRSessionMgr.getCurrentSession(); final MCRUserInformation savedUserInformation = session.getUserInformation(); session.setUserInformation(MCRSystemUserInformation.getGuestInstance()); session.setUserInformation(MCRSystemUserInformation.getJanitorInstance()); try { new MCRORCIDWorkService(orcid, credential).createWork(object); } catch (Exception e) { LOGGER.error("Error while creating: ", e); throw new WebApplicationException(Status.BAD_REQUEST); } finally { session.setUserInformation(MCRSystemUserInformation.getGuestInstance()); session.setUserInformation(savedUserInformation); } return Response.ok().build(); } private MCRORCIDCredential getCredential(MCRORCIDUser orcidUser, String orcid) { final MCRORCIDCredential credential = orcidUser.getCredentialByORCID(orcid); if (credential == null || credential.getAccessToken() == null) { throw new WebApplicationException(Status.BAD_REQUEST); } return credential; } private MCRObject getObject(MCRObjectID objectID) { if (!MCRMetadataManager.exists(objectID)) { throw new WebApplicationException(Status.NOT_FOUND); } try { return MCRMetadataManager.retrieveMCRObject(objectID); } catch (MCRPersistenceException e) { throw new WebApplicationException(Status.BAD_REQUEST); } } private String getMatchingORCID(MCRObject object, MCRORCIDUser orcidUser) { final Set<String> orcids = getMatchingORCIDs(object, orcidUser); if (orcids.isEmpty()) { return null; } if (orcids.size() == 1) { return orcids.iterator().next(); } throw new WebApplicationException(Status.BAD_REQUEST); } private Set<String> getMatchingORCIDs(MCRObject object, MCRORCIDUser orcidUser) { final Set<String> orcids = MCRORCIDUtils.getORCIDs(object); orcids.retainAll(orcidUser.getORCIDs()); return orcids; } static class MCRORCIDPublicationStatus { private boolean isUsersPublication; private boolean isInORCIDProfile; MCRORCIDPublicationStatus(boolean isUsersPublication, boolean isInORCIDProfile) { this.isUsersPublication = isUsersPublication; this.isInORCIDProfile = isInORCIDProfile; } public boolean isUsersPublication() { return isUsersPublication; } public boolean isInORCIDProfile() { return isInORCIDProfile; } } }
7,835
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/work/MCRORCIDWorkService.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.work; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.content.MCRJDOMContent; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.orcid2.MCRORCIDUtils; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.client.MCRORCIDUserClient; import org.mycore.orcid2.client.exception.MCRORCIDInvalidScopeException; import org.mycore.orcid2.client.exception.MCRORCIDNotFoundException; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.exception.MCRORCIDWorkAlreadyExistsException; import org.mycore.orcid2.metadata.MCRORCIDMetadataUtils; import org.mycore.orcid2.metadata.MCRORCIDPutCodeInfo; import org.mycore.orcid2.metadata.MCRORCIDUserInfo; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.orcid2.v3.client.MCRORCIDClientHelper; import org.mycore.orcid2.v3.client.MCRORCIDSearchImpl; import org.mycore.orcid2.v3.client.MCRORCIDSectionImpl; import org.mycore.orcid2.v3.transformer.MCRORCIDWorkTransformerHelper; import org.orcid.jaxb.model.message.ScopeConstants; import org.orcid.jaxb.model.v3.release.record.Work; import org.orcid.jaxb.model.v3.release.record.summary.WorkSummary; import org.orcid.jaxb.model.v3.release.record.summary.Works; import org.orcid.jaxb.model.v3.release.search.Search; import jakarta.ws.rs.core.Response; /** * Provides functionalities to create, update or delete works in ORCID profile. */ public class MCRORCIDWorkService { private static final Logger LOGGER = LogManager.getLogger(); private final String orcid; private final MCRORCIDCredential credential; /** * Creates new MCRORCIDWorkService instance. * * @param orcid the ORCID iD * @param credential the MCRORCIDCredential */ public MCRORCIDWorkService(String orcid, MCRORCIDCredential credential) { this.orcid = orcid; this.credential = credential; } /** * Creates MCRObject in ORCID profile for given MCRORCIDCredential and updates flag. * * @param object the MCRObject * @throws MCRORCIDException if cannot create work, transformation fails or cannot update flags */ public void createWork(MCRObject object) { if (!MCRORCIDUtils.checkPublishState(object)) { throw new MCRORCIDException("Object has wrong state"); } final MCRObject filteredObject = MCRORCIDUtils.filterObject(object); if (!MCRORCIDUtils.checkEmptyMODS(filteredObject)) { throw new MCRORCIDException("Filtered MODS is empty."); } try { final MCRORCIDUserInfo userInfo = Optional .ofNullable(MCRORCIDMetadataUtils.getUserInfoByORCID(object, orcid)) .orElse(new MCRORCIDUserInfo(orcid)); if (userInfo.getWorkInfo() == null) { userInfo.setWorkInfo(new MCRORCIDPutCodeInfo()); } final Work work = MCRORCIDWorkTransformerHelper .transformContent(new MCRJDOMContent(filteredObject.createXML())); final Set<MCRIdentifier> trustedIdentifiers = MCRORCIDWorkUtils.listTrustedIdentifiers(work); doUpdateWorkInfo(trustedIdentifiers, userInfo.getWorkInfo(), orcid, credential); if (userInfo.getWorkInfo().hasOwnPutCode()) { // there is an inconsistent state throw new MCRORCIDWorkAlreadyExistsException(); } else { doCreateWork(work, userInfo.getWorkInfo(), orcid, credential); } MCRORCIDMetadataUtils.updateUserInfoByORCID(object, orcid, userInfo); MCRMetadataManager.update(object); } catch (Exception e) { throw new MCRORCIDException("Cannot create work", e); } } /** * Deletes Work in ORCID profile and updates flag. * * @param object the MCRObject * @throws MCRORCIDException if delete fails */ public void deleteWork(MCRObject object) { try { final MCRORCIDUserInfo userInfo = Optional .ofNullable(MCRORCIDMetadataUtils.getUserInfoByORCID(object, orcid)) .orElse(new MCRORCIDUserInfo(orcid)); if (userInfo.getWorkInfo() == null) { userInfo.setWorkInfo(new MCRORCIDPutCodeInfo()); } final MCRObject filteredObject = MCRORCIDUtils.filterObject(object); final Work work = MCRORCIDWorkTransformerHelper .transformContent(new MCRJDOMContent(filteredObject.createXML())); // do not trust user/work info doUpdateWorkInfo(MCRORCIDWorkUtils.listTrustedIdentifiers(work), userInfo.getWorkInfo(), orcid, credential); doDeleteWork(userInfo.getWorkInfo(), orcid, credential); MCRORCIDMetadataUtils.updateUserInfoByORCID(object, orcid, userInfo); MCRMetadataManager.update(object); } catch (Exception e) { throw new MCRORCIDException("Cannot remove work", e); } } /** * Checks if Work is published in ORCID profile. * * @param identifiers the identifiers * @return true if found matching own work in profile * @throws MCRORCIDException look up request fails */ public boolean checkOwnWorkExists(Set<MCRIdentifier> identifiers) { final MCRORCIDPutCodeInfo workInfo = new MCRORCIDPutCodeInfo(); doUpdateWorkInfo(identifiers, workInfo, orcid, credential); return workInfo.hasOwnPutCode(); } /** * Deletes Work in ORCID profile and updates MCRORCIDPutCodeInfo. * * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDRequestException if the request fails * @throws MCRORCIDNotFoundException if specified Work does not exist * @throws MCRORCIDInvalidScopeException if scope is invalid */ protected static void doDeleteWork(MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential) { removeWork(workInfo.getOwnPutCode(), orcid, credential); workInfo.setOwnPutCode(-1); } /** * Creates Work and updates MCRORCIDPutCodeInfo. * * @param work the Work * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDRequestException if the request fails * @throws MCRORCIDInvalidScopeException if scope is invalid */ protected static void doCreateWork(Work work, MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential) { workInfo.setOwnPutCode(createWork(work, orcid, credential)); } /** * Updates Work and MCRORCIDPutCodeInfo. * * @param putCode the putCode * @param work the Work * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDRequestException if the request fails * @throws MCRORCIDNotFoundException if specified Work does not exist * @throws MCRORCIDInvalidScopeException if scope is invalid */ protected static void doUpdateWork(long putCode, Work work, String orcid, MCRORCIDCredential credential) { final Work remoteWork = fetchWork(putCode, orcid, credential); if (!MCRORCIDWorkUtils.checkWorkEquality(work, remoteWork)) { updateWork(work, orcid, credential, putCode); } else { LOGGER.info("Update of work of user {} with put code {} not required.", orcid, putCode); } } /** * Lists matching ORCID iDs based on search via Work. * * @param identifiers Set of MCRIdentifier * @return Set of ORCID iDs as String * @throws MCRORCIDException if request fails */ protected static Set<String> findMatchingORCIDs(Set<MCRIdentifier> identifiers) { final String query = buildORCIDIdentifierSearchQuery(identifiers); try { return MCRORCIDClientHelper.getClientFactory().createReadClient() .search(MCRORCIDSearchImpl.DEFAULT, query, Search.class).getResults().stream() .map(r -> r.getOrcidIdentifier().getPath()).collect(Collectors.toSet()); } catch (MCRORCIDRequestException e) { throw new MCRORCIDException("Error while finding matching ORCID iDs", e); } } /** * Updates work info for MCRORCIDCredential with MCRIdentifier as reference. * * @param identifiers the identifiers * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDException look up request fails */ protected static void doUpdateWorkInfo(Set<MCRIdentifier> identifiers, MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential) { if (credential.getAccessToken() != null) { try { final List<WorkSummary> summaries = MCRORCIDClientHelper.getClientFactory() .createUserClient(orcid, credential).fetch(MCRORCIDSectionImpl.WORKS, Works.class) .getWorkGroup().stream().flatMap(g -> g.getWorkSummary().stream()).toList(); MCRORCIDWorkSummaryUtils .updateWorkInfoFromSummaries(identifiers, summaries, workInfo); } catch (MCRORCIDRequestException e) { throw new MCRORCIDException("Error during update", e); } } else { doUpdateWorkInfo(identifiers, workInfo, orcid); } } /** * Updates work info for ORCID iD with MCRIdentifier as reference. * * @param identifiers the identifiers * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @throws MCRORCIDException look up request fails */ protected static void doUpdateWorkInfo(Set<MCRIdentifier> identifiers, MCRORCIDPutCodeInfo workInfo, String orcid) { try { final List<WorkSummary> summaries = MCRORCIDClientHelper.getClientFactory().createReadClient() .fetch(orcid, MCRORCIDSectionImpl.WORKS, Works.class).getWorkGroup().stream() .flatMap(g -> g.getWorkSummary().stream()).toList(); MCRORCIDWorkSummaryUtils.updateWorkInfoFromSummaries(identifiers, summaries, workInfo); } catch (MCRORCIDRequestException e) { throw new MCRORCIDException("Error during update", e); } } private static Work fetchWork(long putCode, String orcid, MCRORCIDCredential credential) { try { return MCRORCIDClientHelper.getClientFactory().createUserClient(orcid, credential) .fetch(MCRORCIDSectionImpl.WORK, Work.class, putCode); } catch (MCRORCIDRequestException e) { if (Objects.equals(e.getResponse().getStatus(), Response.Status.NOT_FOUND.getStatusCode())) { throw new MCRORCIDNotFoundException(e.getResponse()); } throw e; } } private static void updateWork(Work work, String orcid, MCRORCIDCredential credential, long putCode) { checkScope(credential); try { final MCRORCIDUserClient memberClient = MCRORCIDClientHelper.getClientFactory().createUserClient(orcid, credential); work.setPutCode(putCode); memberClient.update(MCRORCIDSectionImpl.WORK, putCode, work); } catch (MCRORCIDRequestException e) { if (Objects.equals(e.getResponse().getStatus(), Response.Status.NOT_FOUND.getStatusCode())) { throw new MCRORCIDNotFoundException(e.getResponse()); } throw e; } } private static long createWork(Work work, String orcid, MCRORCIDCredential credential) { checkScope(credential); return MCRORCIDClientHelper.getClientFactory().createUserClient(orcid, credential) .create(MCRORCIDSectionImpl.WORK, work); } private static void removeWork(long putCode, String orcid, MCRORCIDCredential credential) { checkScope(credential); MCRORCIDClientHelper.getClientFactory().createUserClient(orcid, credential).delete(MCRORCIDSectionImpl.WORK, putCode); } private static String buildORCIDIdentifierSearchQuery(Set<MCRIdentifier> identifiers) { String query = ""; for (MCRIdentifier i : List.copyOf(identifiers)) { if (!query.isEmpty()) { query += " OR "; } final String value = i.getValue(); query += String.format(Locale.ROOT, "%s-self:(%s OR %s OR %s)", i.getType(), value, value.toUpperCase(Locale.ROOT), value.toLowerCase(Locale.ROOT)); } return query; } private static void checkScope(MCRORCIDCredential credential) { if (credential.getScope() != null && !credential.getScope().contains(ScopeConstants.ACTIVITIES_UPDATE)) { throw new MCRORCIDInvalidScopeException(); } } }
14,149
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/work/MCRORCIDWorkUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.work; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.mods.merger.MCRMergeTool; import org.mycore.orcid2.MCRORCIDUtils; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.exception.MCRORCIDTransformationException; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.orcid2.v3.transformer.MCRORCIDWorkTransformerHelper; import org.orcid.jaxb.model.common.Relationship; import org.orcid.jaxb.model.v3.release.common.Contributor; import org.orcid.jaxb.model.v3.release.common.ContributorAttributes; import org.orcid.jaxb.model.v3.release.record.ExternalIDs; import org.orcid.jaxb.model.v3.release.record.Work; import org.orcid.jaxb.model.v3.release.record.WorkContributors; /** * Provides utility methods for ORCID Work. */ public class MCRORCIDWorkUtils { /** * Transforms and merges List of works to Element. * * @param works List of works * @return merged Element * @throws MCRORCIDException if build fails * @see #buildUnmergedMODSFromWorks */ public static Element buildMergedMODSFromWorks(List<Work> works) { return mergeElements(buildUnmergedMODSFromWorks(works)); } /** * Transforms List of works to List of elements. * * @param works List of works * @return List of elements * @throws MCRORCIDException if build fails */ public static List<Element> buildUnmergedMODSFromWorks(List<Work> works) { final List<Element> modsElements = new ArrayList<>(); works.forEach(w -> { try { modsElements.add(MCRORCIDWorkTransformerHelper.transformWork(w).asXML().detachRootElement()); } catch (IOException | JDOMException | MCRORCIDTransformationException e) { throw new MCRORCIDException("Build failed", e); } }); return modsElements; } /** * Lists trusted identifiers as Set of MCRIdentifier. * Considers only identifiers with relationship 'self' * * @param work the Work * @return Set of MCRIdentifier * @see MCRORCIDUtils#checkTrustedIdentifier */ public static Set<MCRIdentifier> listTrustedIdentifiers(Work work) { return work.getExternalIdentifiers().getExternalIdentifier().stream() .filter(i -> Objects.equals(i.getRelationship(), Relationship.SELF)) .filter(i -> MCRORCIDUtils.checkTrustedIdentifier(i.getType())) .map(i -> new MCRIdentifier(i.getType(), i.getValue())).collect(Collectors.toSet()); } /** * Compares works and possibly ignores the credit name of the contributors. * * @param localWork the local Work * @param remoteWork the remote work * @return true if localWork equals remoteWork */ public static boolean checkWorkEquality(Work localWork, Work remoteWork) { return Objects.equals(localWork.getWorkTitle(), remoteWork.getWorkTitle()) && Objects.equals(localWork.getShortDescription(), remoteWork.getShortDescription()) && Objects.equals(localWork.getWorkCitation(), remoteWork.getWorkCitation()) && Objects.equals(localWork.getWorkType(), remoteWork.getWorkType()) && Objects.equals(localWork.getPublicationDate(), remoteWork.getPublicationDate()) && Objects.equals(localWork.getUrl(), remoteWork.getUrl()) && Objects.equals(localWork.getJournalTitle(), remoteWork.getJournalTitle()) && Objects.equals(localWork.getLanguageCode(), remoteWork.getLanguageCode()) && Objects.equals(localWork.getCountry(), remoteWork.getCountry()) && equalExternalIdentifiers(localWork.getExternalIdentifiers(), remoteWork.getExternalIdentifiers()) && equalWorkContributors(localWork.getWorkContributors(), remoteWork.getWorkContributors()); } /** * Compares two ExternalIDs. * * @param a First ExternalIDs * @param b Second ExternalIDs * @return true if both are regarded equal */ private static boolean equalExternalIdentifiers(ExternalIDs a, ExternalIDs b) { if (!Objects.equals(a, b)) { if (a == null || b == null) { return false; } else { Set<MCRIdentifier> aIds = a.getExternalIdentifier().stream() .map(i -> new MCRIdentifier(i.getType(), i.getValue())).collect(Collectors.toSet()); Set<MCRIdentifier> bIds = b.getExternalIdentifier().stream() .map(i -> new MCRIdentifier(i.getType(), i.getValue())).collect(Collectors.toSet()); if (!Objects.equals(aIds, bIds)) { return false; } } } return true; } /** * Compares two WorkContributors. * * @param a First WorkContributors * @param b Second WorkContributors * @return true if both are regarded equal */ private static boolean equalWorkContributors(WorkContributors a, WorkContributors b) { if (!Objects.equals(a, b)) { if (a == null || b == null) { return false; } else { final List<Contributor> aContributor = a.getContributor(); final List<Contributor> bContributor = b.getContributor(); if (aContributor.size() != bContributor.size()) { return false; } final Iterator<Contributor> itl = aContributor.iterator(); final Iterator<Contributor> itr = bContributor.iterator(); while (itl.hasNext()) { final Contributor ca = itl.next(); final Contributor cb = itr.next(); /* The comparision of ContributorAttributes is currently broken in the ORCID model * (https://github.com/ORCID/orcid-model/issues/46) and the Object.equals() test will currently * always be true. Once the issue has been fixed equalContributorAttributes() can be replaced * by Object.equals() */ if (!Objects.equals(ca.getContributorOrcid(), cb.getContributorOrcid()) || (ca.getContributorOrcid() == null && cb.getContributorOrcid() == null && !Objects.equals(ca.getCreditName(), cb.getCreditName())) || !Objects.equals(ca.getContributorEmail(), cb.getContributorEmail()) || !equalContributorAttributes(ca.getContributorAttributes(), cb.getContributorAttributes())) { return false; } } } } return true; } /* Temporary Workaround for issue in ORCID model (https://github.com/ORCID/orcid-model/issues/46) */ private static boolean equalContributorAttributes(ContributorAttributes a, ContributorAttributes b) { if (!Objects.equals(a, b)) { if (a == null || b == null) { return false; } else { if (!Objects.equals(a.getContributorSequence(), b.getContributorSequence()) || !Objects.equals(a.getContributorRole(), b.getContributorRole())) { return false; } } } return true; } /** * Merges List of MODS elements to one Element using MCRMergeTool. * * @param elements List of Element * @return merged Element */ private static Element mergeElements(List<Element> elements) { final Element result = elements.get(0); elements.stream().skip(1).forEach(e -> MCRMergeTool.merge(result, e)); return result; } }
8,749
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkSummaryUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/work/MCRORCIDWorkSummaryUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.work; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.orcid2.MCRORCIDUtils; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.exception.MCRORCIDTransformationException; import org.mycore.orcid2.metadata.MCRORCIDPutCodeInfo; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.orcid2.v3.transformer.MCRORCIDWorkTransformerHelper; import org.orcid.jaxb.model.v3.release.record.summary.WorkSummary; /** * Provides utility methods for ORCID WorkSummary. */ public class MCRORCIDWorkSummaryUtils { /** * Transforms List of work summaries to List of elements. * * @param works List of work summaries * @return List of elements * @throws MCRORCIDException if build fails */ public static List<Element> buildUnmergedMODSFromWorkSummaries(List<WorkSummary> works) { final List<Element> modsElements = new ArrayList<>(); works.forEach(w -> { try { modsElements.add(MCRORCIDWorkTransformerHelper.transformWorkSummary(w).asXML().detachRootElement()); } catch (IOException | JDOMException | MCRORCIDTransformationException e) { throw new MCRORCIDException("Build failed", e); } }); return modsElements; } // TODO ignore case for identifiers/values // TODO identifiers may be case sensitive? /** * Returns a Stream of WorkSummaries matching a Set of MCRIdentifiers. * * @param identifiers the Set of MCRIdentifiers * @param workSummaries List of WorkSummaries * @return Stream of matching WorkSummaries */ public static Stream<WorkSummary> findMatchingSummariesByIdentifiers(Set<MCRIdentifier> identifiers, List<WorkSummary> workSummaries) { if (identifiers.isEmpty()) { return Stream.empty(); } return workSummaries.stream() .filter( w -> hasMatch( w.getExternalIdentifiers().getExternalIdentifier().stream() .map(i -> new MCRIdentifier(i.getType(), i.getValue())).collect(Collectors.toSet()), identifiers)); } /** * Updates work info based on List of MCRIdentfier and List of matching WorkSummary as reference. * * @param identifiers List of MCRIdentifier * @param summaries List of WorkSummary * @param workInfo the initial work info */ protected static void updateWorkInfoFromSummaries(Set<MCRIdentifier> identifiers, List<WorkSummary> summaries, MCRORCIDPutCodeInfo workInfo) { final Supplier<Stream<WorkSummary>> matchingWorksSupplier = () -> findMatchingSummariesByIdentifiers(identifiers, summaries); long ownPutCode = workInfo.getOwnPutCode(); if (ownPutCode > 0 && !checkPutCodeExistsInSummaries(summaries, ownPutCode)) { // ownPutCode is outdated because if does not exist in summaries anymore workInfo.setOwnPutCode(-1); } else if (ownPutCode == 0) { workInfo.setOwnPutCode(getPutCodeCreatedByThisAppFromSummaries(matchingWorksSupplier.get())); } workInfo.setOtherPutCodes(getPutCodesNotCreatedByThisAppFromSummaries(matchingWorksSupplier.get())); } /** * Checks Stream of WorkSummary for WorkSummary created by this application. * * @param summaries Stream of WorkSummary * @return Optional of WorkSummary * @see MCRORCIDUtils#isCreatedByThisApplication */ private static Optional<WorkSummary> findSummaryCreateByThisApplication(Stream<WorkSummary> summaries) { return summaries.filter(s -> MCRORCIDUtils.isCreatedByThisApplication(s.retrieveSourcePath())).findFirst(); } private static boolean checkPutCodeExistsInSummaries(List<WorkSummary> works, long putCode) { return works.stream().filter(w -> w.getPutCode().equals(putCode)).findAny().isPresent(); } private static long[] getPutCodesNotCreatedByThisAppFromSummaries(Stream<WorkSummary> works) { return works.filter(w -> !MCRORCIDUtils.isCreatedByThisApplication(w.retrieveSourcePath())) .map(WorkSummary::getPutCode).mapToLong(l -> (long) l).toArray(); } private static long getPutCodeCreatedByThisAppFromSummaries(Stream<WorkSummary> works) { return findSummaryCreateByThisApplication(works).map(WorkSummary::getPutCode).orElse(0l); } /** * Checks if Set A of as matching element in Set B. * * @param a Set A * @param b Set B * @return true if there is an element of A in B */ private static boolean hasMatch(Set<MCRIdentifier> a, Set<MCRIdentifier> b) { a.retainAll(b); return !a.isEmpty(); } }
5,768
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkEventHandlerImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/v3/work/MCRORCIDWorkEventHandlerImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.v3.work; import java.util.Set; import org.mycore.common.content.MCRJDOMContent; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.metadata.MCRORCIDPutCodeInfo; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.orcid2.v3.transformer.MCRORCIDWorkTransformerHelper; import org.mycore.orcid2.work.MCRORCIDWorkEventHandler; import org.orcid.jaxb.model.v3.release.record.Work; /** * See {@link org.mycore.orcid2.work.MCRORCIDWorkEventHandler}. */ public class MCRORCIDWorkEventHandlerImpl extends MCRORCIDWorkEventHandler<Work> { @Override protected void removeWork(MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential) { MCRORCIDWorkService.doDeleteWork(workInfo, orcid, credential); } @Override protected void createWork(Work work, MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential) { MCRORCIDWorkService.doCreateWork(work, workInfo, orcid, credential); } @Override protected void updateWork(long putCode, Work work, String orcid, MCRORCIDCredential credential) { MCRORCIDWorkService.doUpdateWork(putCode, work, orcid, credential); } @Override protected void updateWorkInfo(Set<MCRIdentifier> identifiers, MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential) { MCRORCIDWorkService.doUpdateWorkInfo(identifiers, workInfo, orcid, credential); } @Override protected void updateWorkInfo(Set<MCRIdentifier> identifiers, MCRORCIDPutCodeInfo workInfo, String orcid) { MCRORCIDWorkService.doUpdateWorkInfo(identifiers, workInfo, orcid); } @Override protected Set<MCRIdentifier> listTrustedIdentifiers(Work work) { return MCRORCIDWorkUtils.listTrustedIdentifiers(work); } @Override protected Set<String> findMatchingORCIDs(Set<MCRIdentifier> identifiers) { return MCRORCIDWorkService.findMatchingORCIDs(identifiers); } @Override protected Work transformObject(MCRJDOMContent object) { return MCRORCIDWorkTransformerHelper.transformContent(object); } }
2,880
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDClientConstants.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDClientConstants.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; /** * Provides client constants. */ public class MCRORCIDClientConstants { /** * Default ORCID XML media type. */ public static final String ORCID_XML_MEDIA_TYPE = "application/vnd.orcid+xml"; }
978
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDReadClientImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDReadClientImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; import java.util.HashMap; import java.util.Map; import java.util.Objects; import jakarta.ws.rs.core.Response; /** * Provides an ORCID Client with read methods. * Can be used to talk to Public or Member API. */ public class MCRORCIDReadClientImpl extends MCRORCIDBaseClient implements MCRORCIDReadClient { private static final int DEFAULT_SEARCH_LIMIT = 1000; /** * Creates a new Client with given API URL. * Can be used to read ORCID Public API. * * @param restURL URL of ORCID API */ public MCRORCIDReadClientImpl(String restURL) { super(restURL, null); } /** * Creates a new Client with given API URL and token. * * @param restURL URL of ORCID API * @param token the access token */ public MCRORCIDReadClientImpl(String restURL, String token) { super(restURL, token); } @Override public <T> T fetch(String orcid, MCRORCIDSection section, Class<T> valueType, long... putCodes) { return doFetch(orcid, section, valueType, putCodes); } @Override public <T> T search(MCRORCIDSearch type, String query, int offset, int limit, Class<T> valueType) { return doSearch(type.getPath(), query, offset, limit, valueType); } @Override public <T> T search(MCRORCIDSearch type, String query, Class<T> valueType) { return search(type, query, 0, DEFAULT_SEARCH_LIMIT, valueType); } private <T> T doSearch(String path, String query, int offset, int limit, Class<T> valueType) { if (offset < 0 || limit < 0) { throw new IllegalArgumentException("Offset or limit must be positive."); } final Map<String, Object> queryMap = new HashMap<String, Object>(); queryMap.put("q", query); queryMap.put("start", offset); queryMap.put("rows", limit); final Response response = fetch(path + "/", queryMap); if (!Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.SUCCESSFUL)) { handleError(response); } return response.readEntity(valueType); } }
2,882
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDSearch.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDSearch.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; /** * Interface for ORCID search sections. */ public interface MCRORCIDSearch extends MCRORCIDType { }
867
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDBaseClient.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDBaseClient.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import org.mycore.orcid2.client.filter.MCRORCIDAuthenticationFilter; import org.mycore.orcid2.client.filter.MCRORCIDXMLReader; import org.mycore.orcid2.client.filter.MCRORCIDXMLWriter; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; /** * Basic ORCID client. * Defines basic setup and reading methods. */ abstract class MCRORCIDBaseClient { /** * ORCID XML media type. */ protected static final MediaType ORCID_XML_MEDIA_TYPE = MediaType .valueOf(MCRORCIDClientConstants.ORCID_XML_MEDIA_TYPE); private final WebTarget baseTarget; private MCRORCIDClientErrorHandler errorHandler; /** * Creates MCRORCIDBaseClient with rest url and token. * * @param restURL rest url * @param token the token */ protected MCRORCIDBaseClient(String restURL, String token) { final Client client = ClientBuilder.newClient(); client.register(new MCRORCIDXMLReader<Object>()); client.register(new MCRORCIDXMLWriter()); Optional.ofNullable(token).ifPresent(t -> client.register(new MCRORCIDAuthenticationFilter(t))); this.baseTarget = client.target(restURL.endsWith("/") ? restURL : restURL + "/"); } /** * Registers error handler. * * @param errorHandler the error handler */ public void registerErrorHandler(MCRORCIDClientErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Fetches ORCID with given query params. * * @param path the path * @param queryMap the query params * @return the Response */ protected Response fetch(String path, Map<String, Object> queryMap) { WebTarget target = baseTarget.path(path); for (Map.Entry<String, Object> entry : queryMap.entrySet()) { target = target.queryParam(entry.getKey(), entry.getValue()); } return target.request(ORCID_XML_MEDIA_TYPE).get(); } /** * Fetches section/object of orcid profile and wraps response into type. * * @param orcid the ORCID iD * @param section the ORCID section * @param <T> the result class * @param valueType the result class * @param putCodes optional put code(s) * @return transformed section/object * @throws MCRORCIDRequestException if request fails */ protected <T> T doFetch(String orcid, MCRORCIDSection section, Class<T> valueType, long... putCodes) { final String putCodeString = (putCodes == null || putCodes.length == 0) ? "" : StringUtils.join(putCodes, ','); final Response response = fetch( String.format(Locale.ROOT, "%s/%s/%s", orcid, section.getPath(), putCodeString)); if (!Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.SUCCESSFUL)) { handleError(response); } return response.readEntity(valueType); // may ProcessingException } /** * Handles error response. * * @param response the error response * @throws MCRORCIDRequestException always */ protected void handleError(Response response) { if (errorHandler != null) { errorHandler.handleErrorResponse(response); } throw new MCRORCIDRequestException(response); } /** * Returns the base WebTarget of client. * * @return base WebTarget */ protected WebTarget getBaseTarget() { return baseTarget; } private Response fetch(String path) { return fetch(path, Collections.emptyMap()); } }
4,708
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUserClient.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDUserClient.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; /** * Interface for ORCID client which bound to specific MCRCredential. */ public interface MCRORCIDUserClient { /** * Fetches section/object and wraps response into type. * * @param section the ORCID section * @param <T> the result class * @param type the result class * @param putCodes optional put code(s) * @return transformed section/object * @throws org.mycore.orcid2.client.exception.MCRORCIDRequestException if request fails */ <T> T fetch(MCRORCIDSection section, Class<T> type, long... putCodes); /** * Creates object in section. * * @param section the ORCID section * @param object the element * @return put code of created object * @throws org.mycore.orcid2.client.exception.MCRORCIDRequestException if request fails */ long create(MCRORCIDSection section, Object object); /** * Updates object in section by put code. * * @param section the ORCID section * @param putCode the put code * @param object the object * @throws org.mycore.orcid2.client.exception.MCRORCIDRequestException if request fails */ void update(MCRORCIDSection section, long putCode, Object object); /** * Deletes object in section by put code. * * @param section the ORCID section * @param putCode the put code * @throws org.mycore.orcid2.client.exception.MCRORCIDRequestException if request fails */ void delete(MCRORCIDSection section, long putCode); }
2,286
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDClientFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDClientFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.orcid2.MCRORCIDConstants; import org.mycore.orcid2.exception.MCRORCIDException; /** * Factory for various ORCID clients. */ public class MCRORCIDClientFactory { private static final Logger LOGGER = LogManager.getLogger(); private static final String CONFIG_PREFIX = MCRORCIDConstants.CONFIG_PREFIX + "Client."; private static final String READ_PUBLIC_TOKEN = MCRConfiguration2.getString(CONFIG_PREFIX + "ReadPublicToken") .orElse(null); private static Map<String, MCRORCIDClientFactory> factories = new HashMap<>(); private final String publicAPI; private final String memberAPI; private final MCRORCIDClientErrorHandler errorHandler; private final ReadClientMode mode; private MCRORCIDReadClient readClient = null; private MCRORCIDClientFactory(String version) { final String prefix = CONFIG_PREFIX + version; publicAPI = MCRConfiguration2.getStringOrThrow(prefix + ".PublicAPI"); memberAPI = MCRConfiguration2.getStringOrThrow(prefix + ".MemberAPI"); final String modeString = MCRConfiguration2.getStringOrThrow(prefix + ".APIMode"); errorHandler = MCRConfiguration2.<MCRORCIDClientErrorHandler>getInstanceOf(prefix + ".ErrorHandler.Class") .orElse(null); try { mode = ReadClientMode.valueOf(modeString.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new MCRConfigurationException("Unknown APIMode: " + modeString); } } /** * Returns an instance of a factory for a version. * * @param version the version * @return MCRORCIDClientFactory * @throws MCRConfigurationException if factory cannot be initialized */ public static MCRORCIDClientFactory getInstance(String version) { MCRORCIDClientFactory factory = null; if (factories.containsKey(version)) { factory = factories.get(version); } else { factory = new MCRORCIDClientFactory(version); factories.put(version, factory); } return factory; } /** * Creates a MCRORCIDReadClient for ORCID Member API. * Member API does not limit the number of results * 24 requests per second; 60 burst * Public API is limited to 10,000 results * 24 requests per second; 40 burst * * @throws MCRORCIDException if MCR.ORCID2.Client.ReadPublicToken is required but not set * @return MCRORCIDReadClient */ public MCRORCIDReadClient createReadClient() { if (readClient == null) { readClient = initReadClient(); } return readClient; } /** * Creates a MCRORCIDUserClient for user with MCRORCIDCredential. * * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @return MCRORCIDClient * @throws MCRORCIDException if client is not in member mode */ public MCRORCIDUserClient createUserClient(String orcid, MCRORCIDCredential credential) { if (checkMemberMode()) { MCRORCIDUserClientImpl client = new MCRORCIDUserClientImpl(memberAPI, orcid, credential); client.registerErrorHandler(errorHandler); return client; } else { throw new MCRORCIDException("Client is not in member mode"); } } /** * Checks if API is in member mode. * * @return true if member mode is enabled */ public boolean checkMemberMode() { return Objects.equals(mode, ReadClientMode.MEMBER); } private MCRORCIDReadClient initReadClient() { MCRORCIDReadClientImpl client = null; if (checkMemberMode()) { if (READ_PUBLIC_TOKEN == null) { throw new MCRORCIDException("MCR.ORCID2.Client.ReadPublicToken is not set"); } client = new MCRORCIDReadClientImpl(memberAPI, READ_PUBLIC_TOKEN); } else { if (READ_PUBLIC_TOKEN == null) { LOGGER.info("MCR.ORCID2.Client.ReadPublicToken is not set."); } client = new MCRORCIDReadClientImpl(publicAPI, READ_PUBLIC_TOKEN); } client.registerErrorHandler(errorHandler); return client; } enum ReadClientMode { PUBLIC, MEMBER } }
5,386
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDClientErrorHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDClientErrorHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import jakarta.ws.rs.core.Response; /** * Handles client error. */ public interface MCRORCIDClientErrorHandler { /** * Extracts error response and throws MCRORCIDRequestException * * @param response the Response * @throws MCRORCIDRequestException always */ void handleErrorResponse(Response response); }
1,173
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDSection.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDSection.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; /** * Interface for ORCID sections. */ public interface MCRORCIDSection extends MCRORCIDType { }
861
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUserClientImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDUserClientImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; import java.net.URI; import java.util.Locale; import java.util.Objects; import jakarta.ws.rs.HttpMethod; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.Response; /** * See {@link MCRORCIDUserClient}. * Write actions require the member API and a corresponding scope. */ public class MCRORCIDUserClientImpl extends MCRORCIDBaseClient implements MCRORCIDUserClient { private final WebTarget baseTarget; private final String orcid; /** * Creates an MCRORCIDUserClient with given API URL and MCRORCIDCredential. * * @param restURL rest URL of ORCID API URL * @param orcid the ORCID iD * @param credential the MCRORCIDCredential */ public MCRORCIDUserClientImpl(String restURL, String orcid, MCRORCIDCredential credential) { super(restURL, credential.getAccessToken()); this.orcid = orcid; this.baseTarget = getBaseTarget().path(orcid); } @Override public <T> T fetch(MCRORCIDSection section, Class<T> valueType, long... putCodes) { return doFetch(orcid, section, valueType, putCodes); } @Override public long create(MCRORCIDSection section, Object object) { final Response response = write(section.getPath(), HttpMethod.POST, object); if (!Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.SUCCESSFUL)) { handleError(response); } return Long.parseLong(getLastPathSegment(response.getLocation())); } @Override public void update(MCRORCIDSection section, long putCode, Object object) { final Response response = write(String.format(Locale.ROOT, "%s/%d", section.getPath(), putCode), HttpMethod.PUT, object); if (!Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.SUCCESSFUL)) { handleError(response); } } @Override public void delete(MCRORCIDSection section, long putCode) { final Response response = delete(String.format(Locale.ROOT, "%s/%d", section.getPath(), putCode)); if (!Objects.equals(response.getStatusInfo().getFamily(), Response.Status.Family.SUCCESSFUL)) { handleError(response); } } private Response delete(String path) { return this.baseTarget.path(path).request().delete(); } private Response write(String path, String method, Object object) { return this.baseTarget.path(path).request().build(method, Entity.entity(object, ORCID_XML_MEDIA_TYPE)).invoke(); } private String getLastPathSegment(URI uri) { final String path = uri.getPath(); return path.substring(path.lastIndexOf('/') + 1); } }
3,500
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDType.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDType.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; /** * Base interface for ORCID sections. */ public interface MCRORCIDType { /** * Returns path of section. * * @return the path */ String getPath(); }
945
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDCredential.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDCredential.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; import java.time.LocalDate; import java.util.Locale; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents the ORCID credential including access token. */ public class MCRORCIDCredential { private String accessToken; private String refreshToken; private String tokenType; private String scope; private LocalDate expiration; /** * Creates MCRORCIDCredential object with access token. * * @param accessToken the access token */ public MCRORCIDCredential(String accessToken) { this.accessToken = accessToken; } /** * Creates empty MCRORCIDCredential object. */ public MCRORCIDCredential() { } /** * Returns the access token. * * @return access token */ @JsonProperty("access_token") public String getAccessToken() { return accessToken; } /** * Sets the access token. * * @param accessToken the access token */ public void setAccessToken(String accessToken) { this.accessToken = accessToken; } /** * Returns the refresh token. * * @return refresh token */ @JsonProperty("refresh_token") public String getRefreshToken() { return refreshToken; } /** * Sets the refresh token. * * @param refreshToken the refresh token */ public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } /** * Returns the token type. * * @return token type */ @JsonProperty("token_type") public String getTokenType() { return tokenType; } /** * Sets the token type. * * @param tokenType the token type */ public void setTokenType(String tokenType) { this.tokenType = tokenType; } /** * Returns the scope. * * @return scope */ @JsonProperty("scope") public String getScope() { return scope; } /** * Sets the scope. * * @param scope scope to set */ public void setScope(String scope) { this.scope = scope; } /** * Returns the expire date. * * @return expiration */ public LocalDate getExpiration() { return expiration; } /** * Sets the expire date. * * @param expiration expiration to set */ public void setExpiration(LocalDate expiration) { this.expiration = expiration; } @Override public int hashCode() { return Objects.hash(accessToken, refreshToken, scope, tokenType, expiration); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRORCIDCredential other = (MCRORCIDCredential) obj; return Objects.equals(accessToken, other.accessToken) && Objects.equals(refreshToken, other.refreshToken) && Objects.equals(scope, other.scope) && Objects.equals(tokenType, other.tokenType) && Objects.equals(expiration, other.expiration); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(String.format(Locale.ROOT, "access token: %s\n", accessToken)); builder.append(String.format(Locale.ROOT, "refresh token: %s\n", refreshToken)); builder.append(String.format(Locale.ROOT, "scope: %s", scope)); return builder.toString(); } }
4,428
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDReadClient.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/MCRORCIDReadClient.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client; /** * Interface for client that is at least compatible with ORCID Public or Member API. */ public interface MCRORCIDReadClient { /** * Fetches section/object of ORCID profile and wraps response into type. * * @param orcid the ORCID iD * @param section the ORCID section * @param <T> the result class * @param valueType the result class * @param putCodes optional put code(s) * @return transformed section/object * @throws org.mycore.orcid2.client.exception.MCRORCIDRequestException if request fails */ <T> T fetch(String orcid, MCRORCIDSection section, Class<T> valueType, long... putCodes); /** * Queries section and wraps result into given class. * * @param type the search section type * @param query the query * @param <T> the result type * @param valueType the result type * @return search result * @throws org.mycore.orcid2.client.exception.MCRORCIDRequestException if request fails */ <T> T search(MCRORCIDSearch type, String query, Class<T> valueType); /** * Queries section and wraps result into given class. * * @param type the search section type * @param query the query * @param offset offset * @param limit limit * @param <T> the result type * @param valueType the result type * @return search result * @throws org.mycore.orcid2.client.exception.MCRORCIDRequestException if request fails */ <T> T search(MCRORCIDSearch type, String query, int offset, int limit, Class<T> valueType); }
2,343
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDAuthenticationFilter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/filter/MCRORCIDAuthenticationFilter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client.filter; import java.io.IOException; import jakarta.ws.rs.client.ClientRequestContext; import jakarta.ws.rs.client.ClientRequestFilter; /** * Adds token as Bearer token to request. */ public class MCRORCIDAuthenticationFilter implements ClientRequestFilter { private final String token; /** * Creates request filter for bearer authentication. * * @param token the token */ public MCRORCIDAuthenticationFilter(String token) { this.token = token; } public void filter(ClientRequestContext requestContext) throws IOException { requestContext.getHeaders().add("Authorization", "Bearer " + this.token); } }
1,430
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDXMLReader.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/filter/MCRORCIDXMLReader.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client.filter; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import org.mycore.orcid2.client.MCRORCIDClientConstants; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.ext.MessageBodyReader; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; /** * Transforms response body to respective object. */ @Consumes(MCRORCIDClientConstants.ORCID_XML_MEDIA_TYPE) public class MCRORCIDXMLReader<T> implements MessageBodyReader<T> { @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // handled by consumes annotation return true; } @Override public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try { final JAXBContext jaxbContext = JAXBContext.newInstance(type); return type.cast(jaxbContext.createUnmarshaller().unmarshal(entityStream)); } catch (JAXBException e) { throw new ProcessingException("Error while serializing object.", e); } } }
2,213
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDXMLWriter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/filter/MCRORCIDXMLWriter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client.filter; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import org.mycore.orcid2.client.MCRORCIDClientConstants; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.ProcessingException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.ext.MessageBodyWriter; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; /** * Transforms request body to ORCID XML. */ @Consumes(MCRORCIDClientConstants.ORCID_XML_MEDIA_TYPE) public class MCRORCIDXMLWriter implements MessageBodyWriter<Object> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { // handled by consumes annotation return true; } @Override public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException { try { final JAXBContext jaxbContext = JAXBContext.newInstance(type); jaxbContext.createMarshaller().marshal(object, out); } catch (JAXBException e) { throw new ProcessingException("Error while deserializing object.", e); } } }
2,117
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDRequestException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/exception/MCRORCIDRequestException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client.exception; import org.mycore.orcid2.exception.MCRORCIDException; import jakarta.ws.rs.core.Response; /** * This class is used if a request fails. */ public class MCRORCIDRequestException extends MCRORCIDException { private static final long serialVersionUID = 1L; /** * The response. */ private final Response response; /** * Creates exception with response. * * @param response the response */ public MCRORCIDRequestException(Response response) { this("Request failed", response); } /** * Creates exception with message and response. * * @param message the message * @param response the response */ public MCRORCIDRequestException(String message, Response response) { super(message); this.response = response; } /** * Returns the response. * * @return the response */ public Response getResponse() { return response; } }
1,747
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDNotFoundException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/exception/MCRORCIDNotFoundException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client.exception; import jakarta.ws.rs.core.Response; /** * This class is used if a resource was not found */ public class MCRORCIDNotFoundException extends MCRORCIDRequestException { private static final long serialVersionUID = 1L; /** * Creates exception with response. * * @param response the response */ public MCRORCIDNotFoundException(Response response) { super("Resource not found", response); } }
1,208
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDInvalidScopeException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/client/exception/MCRORCIDInvalidScopeException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.client.exception; import org.mycore.orcid2.exception.MCRORCIDException; /** * This class is used if a scope is invalid. */ public class MCRORCIDInvalidScopeException extends MCRORCIDException { private static final long serialVersionUID = 1L; /** * Creates new MCRORCIDInvalidScopeException. */ public MCRORCIDInvalidScopeException() { super("Invalid scope"); } }
1,157
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUserInfo.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/metadata/MCRORCIDUserInfo.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.metadata; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents model for an ORCID user info. */ public class MCRORCIDUserInfo { private String orcid; private MCRORCIDPutCodeInfo workInfo; /** * Initialises new MCRORCIDUserInfo with ORCID iD. * * @param orcid the ORCID iD */ public MCRORCIDUserInfo(String orcid) { this.orcid = orcid; } /** * Initialises new MCRORCIDUserInfo. */ public MCRORCIDUserInfo() { } /** * Returns the ORCID iD. * * @return the ORCID iD */ @JsonProperty("orcid") public String getORCID() { return orcid; } /** * Sets ORCID iD. * * @param orcid the ORCID iD */ public void setORCID(String orcid) { this.orcid = orcid; } /** * Returns MCRORCIDPutCodeInfo for works. * * @return MCRORCIDPutCodeInfo for works */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("works") public MCRORCIDPutCodeInfo getWorkInfo() { return workInfo; } /** * Sets works MCRORCIDPutCodeInfo. * * @param workInfo the work info */ public void setWorkInfo(MCRORCIDPutCodeInfo workInfo) { this.workInfo = workInfo; } @Override public int hashCode() { return Objects.hash(orcid, workInfo); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRORCIDUserInfo other = (MCRORCIDUserInfo) obj; return Objects.equals(orcid, other.orcid) && Objects.equals(workInfo, other.workInfo); } }
2,647
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDFlagContent.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/metadata/MCRORCIDFlagContent.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.metadata; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * Represents model for ORCID flag content. */ public class MCRORCIDFlagContent { private List<MCRORCIDUserInfo> userInfos = new ArrayList<>(); /** * Initializes new MCRORCIDFlagContent object with List of MCRORCIDUserInfo. * * @param userInfos List of MCRORCIDUserInfo */ public MCRORCIDFlagContent(List<MCRORCIDUserInfo> userInfos) { this.userInfos = userInfos; } /** * Initializes new MCRORCIDFlagContent object. */ public MCRORCIDFlagContent() { } /** * Returns List of MCRORCIDUserInfo. * * @return List of MCRORCIDUserInfo */ public List<MCRORCIDUserInfo> getUserInfos() { return userInfos; } /** * Sets MCRORCIDUserInfos. * * @param userInfos List of MCRORCIDUserInfo */ public void setUserInfos(List<MCRORCIDUserInfo> userInfos) { this.userInfos = userInfos; } /** * Returns MCRORCIDUserInfo by ORCID iD. * * @param orcid the ORCID iD * @return MCRORCIDUserInfo or null */ public MCRORCIDUserInfo getUserInfoByORCID(String orcid) { return userInfos.stream().filter(c -> c.getORCID().equals(orcid)).findFirst().orElse(null); } /** * Updates MCRORCIDUserInfo by ORCID iD. * * @param orcid the ORCID iD * @param userInfo the MCRORCIDUserInfo */ public void updateUserInfoByORCID(String orcid, MCRORCIDUserInfo userInfo) { removeUserInfoByORCID(orcid); userInfos.add(userInfo); } /** * Removes MCRORCIDUserInfo by ORCID iD. * * @param orcid the ORCID iD */ public void removeUserInfoByORCID(String orcid) { userInfos = userInfos.stream().filter(c -> !c.getORCID().equals(orcid)).collect(Collectors.toList()); } @Override public int hashCode() { return Objects.hash(userInfos); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRORCIDFlagContent other = (MCRORCIDFlagContent) obj; return Objects.equals(userInfos, other.userInfos); } }
3,175
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDMetadataUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/metadata/MCRORCIDMetadataUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.metadata; import java.util.List; import java.util.Objects; import java.util.Optional; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.orcid2.MCRORCIDConstants; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.exception.MCRORCIDTransformationException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Handles metadata for ORCID stuff. */ public class MCRORCIDMetadataUtils { /** * Controls the saving of other put codes. */ public static boolean SAVE_OTHER_PUT_CODES = MCRConfiguration2.getOrThrow(MCRORCIDConstants.CONFIG_PREFIX + "Metadata.WorkInfo.SaveOtherPutCodes", Boolean::parseBoolean); /** * Name of ORCID flag. */ protected static final String ORCID_FLAG = "MyCoRe-ORCID"; /** * Returns MCRORCIDFlagContent of orcid flag. * * @param object the MCRObject * @return the MCRORCIDFlagContent or null * @throws MCRORCIDException if orcid flag is broken */ public static MCRORCIDFlagContent getORCIDFlagContent(MCRObject object) { try { return getORCIDFlagContentString(object).map(s -> transformFlagContentString(s)).orElse(null); } catch (MCRORCIDTransformationException e) { throw new MCRORCIDException("ORCID flag of object " + object.getId() + "is broken", e); } } /** * Sets ORCID flag of MCRObject and updates MCRObject. * * @param object the MCRObject * @param flagContent the MCRORCIDFlagContent * @throws MCRORCIDException if update fails */ public static void setORCIDFlagContent(MCRObject object, MCRORCIDFlagContent flagContent) { try { doSetORCIDFlagContent(object, flagContent); } catch (MCRPersistenceException e) { throw new MCRORCIDException("Could not update list of object " + object.getId(), e); } } /** * Removes ORCID flag from MCRObject and updates MCRObject. * * @param object the MCRObject * @throws MCRORCIDException if cannot remove flag */ public static void removeORCIDFlag(MCRObject object) { object.getService().removeFlags(ORCID_FLAG); } /** * Returns MCRORCIDUserInfo by ORCID iD for MCRObject. * * @param object the MCRObject * @param orcid the ORCID iD * @return the MCRORCIDUserInfo or null * @throws MCRORCIDException if MCRORCIDUserInfo is broken */ public static MCRORCIDUserInfo getUserInfoByORCID(MCRObject object, String orcid) { return Optional.ofNullable(getORCIDFlagContent(object)).map(f -> f.getUserInfoByORCID(orcid)).orElse(null); } /** * Updates MCRORCIDUserInfo by ORCID iD for MCROject and updates MCRObject. * * @param object the MCRObject * @param orcid the ORCID iD * @param userInfo the MCRORCIDUserInfo * @throws MCRORCIDException if update fails */ public static void updateUserInfoByORCID(MCRObject object, String orcid, MCRORCIDUserInfo userInfo) { final MCRORCIDFlagContent flagContent = Optional.ofNullable(getORCIDFlagContent(object)) .orElse(new MCRORCIDFlagContent()); flagContent.updateUserInfoByORCID(orcid, userInfo); setORCIDFlagContent(object, flagContent); } /** * Removes all work infos excluding orcids * * @param object the MCRObject * @param orcids List of ORCID iDs * @throws MCRORCIDException if clean up fails */ public static void cleanUpWorkInfosExcludingORCIDs(MCRObject object, List<String> orcids) { final MCRORCIDFlagContent flagContent = getORCIDFlagContent(object); // nothing to clean up if (flagContent == null) { return; } flagContent.getUserInfos().forEach(i -> { if (!orcids.contains(i.getORCID())) { i.setWorkInfo(null); } }); setORCIDFlagContent(object, flagContent); } /** * Sets ORCID flag of MCRObject. * * @param object the MCRObject * @param flagContent the MCRORCIDFlagContent * @throws MCRORCIDException if update fails */ protected static void doSetORCIDFlagContent(MCRObject object, MCRORCIDFlagContent flagContent) { removeORCIDFlags(object); if (!SAVE_OTHER_PUT_CODES) { // may rudimentary approach flagContent.getUserInfos().stream().map(MCRORCIDUserInfo::getWorkInfo).filter(Objects::nonNull) .forEach(w -> w.setOtherPutCodes(null)); } String flagContentString = null; try { flagContentString = transformFlagContent(flagContent); } catch (MCRORCIDTransformationException e) { throw new MCRORCIDException("Could not update list of object " + object.getId(), e); } addORCIDFlag(object, flagContentString); } /** * Transforms MCRORCIDFlagContent to String. * * @param flagContent the MCRORCIDFlagContent * @return MCRORCIDFlagContent as String * @throws MCRORCIDTransformationException if collection transformation fails */ protected static String transformFlagContent(MCRORCIDFlagContent flagContent) { try { return new ObjectMapper().writeValueAsString(flagContent); } catch (JsonProcessingException e) { throw new MCRORCIDTransformationException(e); } } /** * Transforms flag content as String to MCRORCIDFlagContent. * * @param flagContentString MCRORCIDFlagContent as String * @return MCRORCIDFlagContent * @throws MCRORCIDTransformationException if string transformation fails */ protected static MCRORCIDFlagContent transformFlagContentString(String flagContentString) { try { return new ObjectMapper().readValue(flagContentString, MCRORCIDFlagContent.class); } catch (JsonProcessingException e) { throw new MCRORCIDTransformationException(e); } } private static Optional<String> getORCIDFlagContentString(MCRObject object) { return object.getService().getFlags(ORCID_FLAG).stream().findFirst(); } private static void addORCIDFlag(MCRObject object, String content) { object.getService().addFlag(ORCID_FLAG, content); } private static void removeORCIDFlags(MCRObject object) { object.getService().removeFlags(ORCID_FLAG); } }
7,394
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDPutCodeInfo.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/metadata/MCRORCIDPutCodeInfo.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.metadata; import java.util.Arrays; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * Represents model for own and other ORCID put codes. */ public class MCRORCIDPutCodeInfo { private long ownPutCode; private long[] otherPutCodes; /** * Initialises a new MCRORCIDPutCodeInfo with own and other put codes. * * @param ownPutCode own put code * @param otherPutCodes List of other put codes */ public MCRORCIDPutCodeInfo(long ownPutCode, long[] otherPutCodes) { this.ownPutCode = ownPutCode; this.otherPutCodes = otherPutCodes; } /** * Initialises a new MCRORCIDPutCodeInfo with own put code. * * @param ownPutCode own put code */ public MCRORCIDPutCodeInfo(long ownPutCode) { this.ownPutCode = ownPutCode; } /** * Initialises a new MCRORCIDPutCodeInfo. */ public MCRORCIDPutCodeInfo() { } /** * Returns own put code. * * @return own put code */ @JsonInclude(JsonInclude.Include.NON_DEFAULT) @JsonProperty("own") public long getOwnPutCode() { return ownPutCode; } /** * Checks if object has own put code. * * @return true if there is an own put code */ public boolean hasOwnPutCode() { return ownPutCode > 0; } /** * Checks if object had own put code. * * @return true if put code is -1 */ public boolean hadOwnPutCode() { return ownPutCode == -1; } /** * Sets own put code. * * @param putCode own put code */ public void setOwnPutCode(long putCode) { ownPutCode = putCode; } /** * Returns other put codes. * * @return other put codes */ @JsonProperty("other") @JsonInclude(JsonInclude.Include.NON_DEFAULT) public long[] getOtherPutCodes() { return otherPutCodes; } /** * Sets other put codes. * * @param putCodes other put codes */ public void setOtherPutCodes(long[] putCodes) { this.otherPutCodes = putCodes; } /** * Checks if there are other put codes. * * @return true if there are other put codes */ public boolean hasOtherPutCodes() { return otherPutCodes != null && otherPutCodes.length > 0; } /** * Adds put code to other put codes. * * @param putCode put code */ public void addOtherPutCode(long putCode) { if (otherPutCodes == null) { otherPutCodes = new long[1]; otherPutCodes[0] = putCode; } else { otherPutCodes = Arrays.copyOf(otherPutCodes, otherPutCodes.length + 1); otherPutCodes[otherPutCodes.length - 1] = putCode; } } @Override public int hashCode() { return Objects.hash(ownPutCode, Arrays.hashCode(otherPutCodes)); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRORCIDPutCodeInfo other = (MCRORCIDPutCodeInfo) obj; return (ownPutCode == other.ownPutCode) && Arrays.equals(otherPutCodes, other.otherPutCodes); } }
4,181
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDValidationHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/validation/MCRORCIDValidationHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.validation; import org.mycore.orcid2.client.MCRORCIDCredential; /** * Provides validation methods. */ public class MCRORCIDValidationHelper { /** * Validates MCRORCIDCredential. * * @param credential the MCRORCIDCredential * @return true if credential is valid */ public static boolean validateCredential(MCRORCIDCredential credential) { final String accessToken = credential.getAccessToken(); return accessToken != null && !accessToken.isEmpty(); } /** * Validates an ORCID iD. * * @param orcid ORCID iD * @return true if ORCID iD is valid */ public static boolean validateORCID(String orcid) { if (orcid.length() < 16) { return false; } final char checkDigit = orcid.charAt(orcid.length() - 1); final String rawORCID = orcid.substring(0, orcid.length() - 1).replaceAll("\\D+", ""); if (rawORCID.length() != 15) { return false; } return checkDigit == generateCheckDigit(rawORCID); } /** * Generates check digit as per ISO 7064 11,2. * * @param baseDigits base digits * @return check digit */ private static char generateCheckDigit(String baseDigits) { int total = 0; for (int i = 0; i < baseDigits.length(); i++) { int digit = Character.getNumericValue(baseDigits.charAt(i)); total = (total + digit) * 2; } int remainder = total % 11; int result = (12 - remainder) % 11; return result == 10 ? 'X' : (char) (result + '0'); } }
2,369
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/cli/MCRORCIDCommands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.cli; import java.util.List; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.user.MCRORCIDUser; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; /** * Provides CLI commands for orcid2. */ @MCRCommandGroup( name = "ORCID2") public class MCRORCIDCommands { private static final Logger LOGGER = LogManager.getLogger(); /** * ORCiD token user attribute name. */ protected static final String ORCID_TOKEN_ATTRIBUTE_NAME = "token_orcid"; /** * Migrates all ORCID token user attributes to MCRORCIDCredential. * * @throws MCRORCIDException if migration fails * @throws MCRException if there is more than ORCiD attribute for one user */ @MCRCommand(syntax = "migrate all orcid access token attributes", help = "Migrates orcid user access token attributes to orcid2 oauth credential") public static void migrateORCIDTokenAttributes() { final List<MCRUser> users = MCRUserManager.listUsers(null, null, null, null, ORCID_TOKEN_ATTRIBUTE_NAME, null, 0, Integer.MAX_VALUE); for (MCRUser user : users) { String orcid = null; orcid = user.getUserAttribute(MCRORCIDUser.ATTR_ORCID_ID); final String token = user.getUserAttribute(ORCID_TOKEN_ATTRIBUTE_NAME); if (orcid == null) { LOGGER.info("Ignored {}, ORCiD attribute is missing.", user.getUserName()); continue; } final MCRORCIDCredential credential = new MCRORCIDCredential(token); credential.setTokenType("bearer"); final MCRORCIDUser orcidUser = new MCRORCIDUser(user); orcidUser.addCredential(orcid, credential); user.getAttributes().removeIf(a -> Objects.equals(a.getName(), ORCID_TOKEN_ATTRIBUTE_NAME)); MCRUserManager.updateUser(user); } LOGGER.info("Migrated all user attributes."); } }
3,056
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/exception/MCRORCIDException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.exception; import org.mycore.common.MCRException; /** * General mycore-orcid2 exception. */ public class MCRORCIDException extends MCRException { private static final long serialVersionUID = 1L; /** * Creates a new MCRORCIDException with message. * * @param message the message */ public MCRORCIDException(String message) { super(message); } /** * Creates a new MCRORCIDException with message and cause. * * @param message the message * @param cause the cause */ public MCRORCIDException(String message, Throwable cause) { super(message, cause); } }
1,401
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDTransformationException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/exception/MCRORCIDTransformationException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.exception; /** * This exception concerns errors when transforming. */ public class MCRORCIDTransformationException extends MCRORCIDException { private static final long serialVersionUID = 1L; /** * Creates a new MCRORCIDTransformationException with message. * * @param message the message */ public MCRORCIDTransformationException(String message) { super(message); } /** * Creates a new MCRORCIDTransformationException with default message and cause. * * @param cause the cause */ public MCRORCIDTransformationException(Throwable cause) { super("Transformation failed", cause); } /** * Creates a new MCRORCIDTransformationException with message and cause. * * @param message the message * @param cause the cause */ public MCRORCIDTransformationException(String message, Throwable cause) { super(message, cause); } }
1,708
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkAlreadyExistsException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/exception/MCRORCIDWorkAlreadyExistsException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.exception; /** * This exception concerns errors when a work already exists in a ORCID profile. */ public class MCRORCIDWorkAlreadyExistsException extends MCRORCIDException { private static final long serialVersionUID = 1L; /** * Creates a new MCRORCIDWorkAlreadyExistsException with default message. */ public MCRORCIDWorkAlreadyExistsException() { super("Work already exists"); } /** * Creates a new MCRORCIDWorkAlreadyExistsException with default message and cause. * * @param cause the cause */ public MCRORCIDWorkAlreadyExistsException(Throwable cause) { super("Work already exists", cause); } }
1,434
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUser.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/user/MCRORCIDUser.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.user; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mods.MCRMODSWrapper; import org.mycore.orcid2.MCRORCIDConstants; import org.mycore.orcid2.MCRORCIDUtils; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.orcid2.validation.MCRORCIDValidationHelper; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserAttribute; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Provides functionality to interact with MCRUser that is also an ORCID user. * Handles the updating of user. */ public class MCRORCIDUser { /** * List of trusted name identifier types. */ public static final List<String> TRUSTED_NAME_IDENTIFIER_TYPES = MCRConfiguration2 .getString(MCRORCIDConstants.CONFIG_PREFIX + "User.TrustedNameIdentifierTypes").stream() .flatMap(MCRConfiguration2::splitValue).collect(Collectors.toList()); /** * Id prefix for user attributes. */ public static final String ATTR_ID_PREFIX = "id_"; /** * Prefix for ORCID credential user attribute. */ public static final String ATTR_ORCID_CREDENTIAL = "orcid_credential_"; /** * Prefix for ORCID user properties user attribute. */ public static final String ATTR_ORCID_USER_PROPERTIES = "orcid_user_properties_"; /** * ORCID iD user attribute name. */ public static final String ATTR_ORCID_ID = ATTR_ID_PREFIX + "orcid"; private static final String WORK_EVENT_HANDLER_PROPERTY_PREFIX = "MCR.ORCID2.WorkEventHandler."; private static final boolean ALWAYS_UPDATE = MCRConfiguration2 .getBoolean(WORK_EVENT_HANDLER_PROPERTY_PREFIX + "AlwaysUpdateWork").orElse(false); private static final boolean CREATE_FIRST = MCRConfiguration2 .getBoolean(WORK_EVENT_HANDLER_PROPERTY_PREFIX + "CreateFirstWork").orElse(false); private static final boolean CREATE_OWN_DUPLICATE = MCRConfiguration2 .getBoolean(WORK_EVENT_HANDLER_PROPERTY_PREFIX + "CreateDuplicateWork").orElse(false); private static final boolean RECREATE_DELETED = MCRConfiguration2 .getBoolean(WORK_EVENT_HANDLER_PROPERTY_PREFIX + "RecreateDeletedWork").orElse(false); private final MCRUser user; /** * Wraps MCRUser to MCRORCIDUser. * * @param user the MCRUser */ public MCRORCIDUser(MCRUser user) { this.user = user; } /** * Returns MCRUser. * * @return MCRUser */ public MCRUser getUser() { return user; } /** * Adds ORCID iD to user's user attributes. * * @param orcid the ORCID iD * @throws MCRORCIDException if ORCID iD is invalid */ public void addORCID(String orcid) { if (!MCRORCIDValidationHelper.validateORCID(orcid)) { throw new MCRORCIDException("Invalid ORCID iD"); } final MCRUserAttribute attribute = new MCRUserAttribute(ATTR_ORCID_ID, orcid); // allow more than one ORCID iD per user if (!user.getAttributes().contains(attribute)) { user.getAttributes().add(new MCRUserAttribute(ATTR_ORCID_ID, orcid)); } } /** Returns user's ORCID iDs. * * @return ORCID iDs as set */ public Set<String> getORCIDs() { return user.getAttributes().stream() .filter(a -> Objects.equals(a.getName(), ATTR_ORCID_ID)) .map(MCRUserAttribute::getValue).collect(Collectors.toSet()); } /** * Sets MCRORCIDCredential to user's MCRUserAttribute. * Also, adds ORCID iD to user attributes. * * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDException if credential is invalid * @see MCRORCIDUser#addORCID */ public void addCredential(String orcid, MCRORCIDCredential credential) { addORCID(orcid); if (!MCRORCIDValidationHelper.validateCredential(credential)) { throw new MCRORCIDException("Credential is invalid"); } String credentialString = null; try { credentialString = serializeCredential(credential); } catch (IllegalArgumentException e) { throw new MCRORCIDException("Credential is invalid"); } user.setUserAttribute(getCredentialAttributeNameByORCID(orcid), credentialString); } /** * Removes all MCRORCIDCredential attributes. */ public void removeAllCredentials() { final SortedSet<MCRUserAttribute> attributes = user.getAttributes(); final SortedSet<MCRUserAttribute> toKeep = new TreeSet<MCRUserAttribute>(); for (MCRUserAttribute attribute : attributes) { if (!attribute.getName().startsWith(ATTR_ORCID_CREDENTIAL)) { toKeep.add(attribute); } } // because of Hibernate issues user.setAttributes(toKeep); } /** * Removes MCROCIDCredential by ORCID iD if exists. * * @param orcid the ORCID iD */ public void removeCredentialByORCID(String orcid) { final SortedSet<MCRUserAttribute> attributes = user.getAttributes(); final SortedSet<MCRUserAttribute> toKeep = new TreeSet<MCRUserAttribute>(); for (MCRUserAttribute attribute : attributes) { if (!attribute.getName().equals(getCredentialAttributeNameByORCID(orcid))) { toKeep.add(attribute); } } // because of Hibernate issues user.setAttributes(toKeep); } /** * Checks if user has MCRORCIDCredential. * * @return true if user has at least one MCRORCIDCredential */ public boolean hasCredentials() { return user.getAttributes().stream() .filter(attribute -> attribute.getName().startsWith(ATTR_ORCID_CREDENTIAL)).findAny().isPresent(); } /** * Checks if user MCRORCIDCredential for ORCID iD. * * @param orcid the ORCID iD * @return true if user has MCRORCIDCredential for ORCID iD */ public boolean hasCredential(String orcid) { return user.getAttributes().stream() .filter(attribute -> attribute.getName().equals(getUserPropertiesAttributeNameByORCID(orcid))) .findAny().isPresent(); } /** * Returns user's MCRORCIDCredential from user attributes. * * @return Map of MCRORCIDCredentials * @throws MCRORCIDException if at least one MCRORCIDCredential is corrupt */ public Map<String, MCRORCIDCredential> getCredentials() { try { return user.getAttributes().stream() .filter(a -> a.getName().startsWith(ATTR_ORCID_CREDENTIAL)) .collect(Collectors.toMap(a -> a.getName().substring(ATTR_ORCID_CREDENTIAL.length()), a -> deserializeCredential(a.getValue()))); } catch (IllegalArgumentException e) { throw new MCRORCIDException("Found corrupt credential", e); } } /** * Gets user's MCRORCIDCredential by ORCID iD. * * @param orcid the ORCID iD * @return MCRCredentials or null * @throws MCRORCIDException if the MCRORCIDCredential is corrupt */ public MCRORCIDCredential getCredentialByORCID(String orcid) { try { return Optional.ofNullable(getCredentialAttributeValueByORCID(orcid)) .map(s -> deserializeCredential(s)).orElse(null); } catch (IllegalArgumentException e) { throw new MCRORCIDException("Credential is corrupt", e); } } /** * Checks if user owns object by user by name identifiers. * * @param objectID objects id * @return true is user owns object * @throws MCRORCIDException if check fails */ public boolean isMyPublication(MCRObjectID objectID) { MCRObject object = null; try { object = MCRMetadataManager.retrieveMCRObject(objectID); } catch (MCRPersistenceException e) { throw new MCRORCIDException("Cannot check publication", e); } // TODO uniqueness of IDs final Set<MCRIdentifier> nameIdentifiers = MCRORCIDUtils.getNameIdentifiers(new MCRMODSWrapper(object)); nameIdentifiers.retainAll(getTrustedIdentifiers()); return !nameIdentifiers.isEmpty(); } /** * Returns users identifiers. * * @return Set of MCRIdentifier */ public Set<MCRIdentifier> getIdentifiers() { return user.getAttributes().stream().filter(a -> a.getName().startsWith(ATTR_ID_PREFIX)) .map(a -> new MCRIdentifier(a.getName().substring(ATTR_ID_PREFIX.length()), a.getValue())) .collect(Collectors.toSet()); } /** * Returns all trusted identifiers. * Trusted name identifier type can be defined as follows: * * MCR.ORCID2.User.TrustedNameIdentifierTypes= * * @return Set of trusted MCRIdentifier */ public Set<MCRIdentifier> getTrustedIdentifiers() { return getIdentifiers().stream().filter(i -> TRUSTED_NAME_IDENTIFIER_TYPES.contains(i.getType())) .collect(Collectors.toSet()); } /** * Returns MCRORCIDUserProperties by ORCID iD. * Takes system properties as fallback. * * @param orcid the ORCID iD * @return MCRORCIDUserProperties */ public MCRORCIDUserProperties getUserPropertiesByORCID(String orcid) { try { return Optional.ofNullable(getUserPropertiesAttributeValueByORCID(orcid)) .map(p -> deserializeUserProperties(p)) .orElse(new MCRORCIDUserProperties(ALWAYS_UPDATE, CREATE_OWN_DUPLICATE, CREATE_FIRST, RECREATE_DELETED)); } catch (IllegalArgumentException e) { throw new MCRORCIDException("Found corrupt user properites", e); } } /** * Sets MCRORCIDUserProperties for ORCID iD. * * @param orcid the ORCID iD * @param userProperties the MCRORCIDUserProperties */ public void setUserProperties(String orcid, MCRORCIDUserProperties userProperties) { String userPropertiesString = null; try { userPropertiesString = serializeUserProperties(userProperties); } catch (IllegalArgumentException e) { throw new MCRORCIDException("User properties are invalid"); } user.setUserAttribute(getUserPropertiesAttributeNameByORCID(orcid), userPropertiesString); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MCRORCIDUser other = (MCRORCIDUser) obj; return Objects.equals(user, other.user); } /** * Serializes MCRORCIDCredential to String. * * @param credential MCRORCIDCredential * @return MCRORCIDCredential as String * @throws IllegalArgumentException if serialization fails */ protected static String serializeCredential(MCRORCIDCredential credential) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setSerializationInclusion(Include.NON_NULL); return mapper.writeValueAsString(credential); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } } /** * Deserializes String to MCRORCIDCredential. * * @param credentialString MCRORCIDCredential as String * @return MCRORCIDCredential * @throws IllegalArgumentException if deserialization fails */ protected static MCRORCIDCredential deserializeCredential(String credentialString) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); return mapper.readValue(credentialString, MCRORCIDCredential.class); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } } private static String serializeUserProperties(MCRORCIDUserProperties userProperties) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.setSerializationInclusion(Include.NON_NULL); return mapper.writeValueAsString(userProperties); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } } private static MCRORCIDUserProperties deserializeUserProperties(String userPropertiesString) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); return mapper.readValue(userPropertiesString, MCRORCIDUserProperties.class); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e); } } private String getCredentialAttributeValueByORCID(String orcid) { return user.getUserAttribute(getCredentialAttributeNameByORCID(orcid)); } private static String getCredentialAttributeNameByORCID(String orcid) { return ATTR_ORCID_CREDENTIAL + orcid; } private String getUserPropertiesAttributeValueByORCID(String orcid) { return user.getUserAttribute(getUserPropertiesAttributeNameByORCID(orcid)); } private static String getUserPropertiesAttributeNameByORCID(String orcid) { return ATTR_ORCID_USER_PROPERTIES + orcid; } }
14,999
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUserProperties.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/user/MCRORCIDUserProperties.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.user; /** * Model form MCRORCIDUser properties. */ public class MCRORCIDUserProperties { private boolean alwaysUpdateWork; private boolean createDuplicateWork; private boolean createFirstWork; private boolean recreateDeletedWork; /** * Constructs new MCRORCIDUserProperties. */ MCRORCIDUserProperties() { this(false, false, false, false); } /** * Constructs new MCRORCIDUserProperties. * * @param alwaysUpdateWork if always update * @param createDuplicateWork if create own duplicate * @param createFirstWork if create own * @param recreateDeletedWork if recreate deleted */ MCRORCIDUserProperties(boolean alwaysUpdateWork, boolean createDuplicateWork, boolean createFirstWork, boolean recreateDeletedWork) { this.alwaysUpdateWork = alwaysUpdateWork; this.createDuplicateWork = createDuplicateWork; this.createFirstWork = createFirstWork; this.recreateDeletedWork = recreateDeletedWork; } /** * Returns always update work property. * * @return true if always update */ public boolean isAlwaysUpdateWork() { return alwaysUpdateWork; } /** * Sets always update work property. * * @param alwaysUpdateWork is always update work */ public void setAlwaysUpdateWork(boolean alwaysUpdateWork) { this.alwaysUpdateWork = alwaysUpdateWork; } /** * Returns create duplicate work property. * * @return true if create duplicate work */ public boolean isCreateDuplicateWork() { return createDuplicateWork; } /** * Sets create duplicate work property. * * @param createDuplicateWork is create duplicate work */ public void setCreateDuplicateWork(boolean createDuplicateWork) { this.createDuplicateWork = createDuplicateWork; } /** * Returns create first work property. * * @return true if create first work */ public boolean isCreateFirstWork() { return createFirstWork; } /** * Sets create first work property. * * @param createFirstWork is create first work */ public void setCreateFirstWork(boolean createFirstWork) { this.createFirstWork = createFirstWork; } /** * Returns recreate deleted work property. * * @return true if recreate deleted work */ public boolean isRecreateDeletedWork() { return recreateDeletedWork; } /** * Sets recreate deleted work property. * * @param recreateDeletedWork recreate deleted work */ public void setRecreateDeleted(boolean recreateDeletedWork) { this.recreateDeletedWork = recreateDeletedWork; } }
3,554
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDUserUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/user/MCRORCIDUserUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.user; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.oauth.MCRORCIDOAuthClient; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; /** * Provides utility methods for MCRORCIDUser. */ public class MCRORCIDUserUtils { /** * Returns MCRORCIDCredential by ORCID iD. * * @param orcid the ORCID iD * @return MCRORCIDCredential or null * @throws MCRORCIDException if the credential is corrupt or there is more than one user */ public static MCRORCIDCredential getCredentialByORCID(String orcid) { return Optional.ofNullable(getORCIDUserByORCID(orcid)).map(u -> u.getCredentialByORCID(orcid)).orElse(null); } /** * Returns MCRORCIDUser by ORCID iD. * * @param orcid the ORCID iD * @return MCRORCIDUser or null * @throws MCRORCIDException if there is more than one matching user */ public static MCRORCIDUser getORCIDUserByORCID(String orcid) { final Set<MCRUser> users = MCRUserManager.getUsers(MCRORCIDUser.ATTR_ORCID_ID, orcid) .collect(Collectors.toSet()); if (users.isEmpty()) { return null; } else if (users.size() == 1) { return new MCRORCIDUser(users.iterator().next()); } throw new MCRORCIDException("Found more than one user for" + orcid); } /** * Returns Set of MCRUser for given MCRIdentifier. * * @param id the MCRIdentifier * @return Set of MCRUser */ public static Set<MCRUser> getUserByID(MCRIdentifier id) { return MCRUserManager.getUsers(MCRORCIDUser.ATTR_ID_PREFIX + id.getType(), id.getValue()) .collect(Collectors.toSet()); } /** * Revokes orcid access token of MCRORCIDUser by ORCID iD. * * @param orcidUser the MCRORCIDUser * @param orcid the ORCID iD * @throws MCRORCIDException if credential does not exist or revoke request fails */ public static void revokeCredentialByORCID(MCRORCIDUser orcidUser, String orcid) { final MCRORCIDCredential credential = Optional.ofNullable(orcidUser.getCredentialByORCID(orcid)) .orElseThrow(() -> new MCRORCIDException("Credential does not exist")); try { MCRORCIDOAuthClient.getInstance().revokeToken(credential.getAccessToken()); orcidUser.removeCredentialByORCID(orcid); MCRUserManager.updateUser(orcidUser.getUser()); } catch (MCRORCIDRequestException e) { throw new MCRORCIDException("Revoke failed", e); } } }
3,597
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDSessionUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/user/MCRORCIDSessionUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.user; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; /** * Provides ORCID session utilities. */ public class MCRORCIDSessionUtils { private static final String KEY_ORCID_USER = "ORCID_USER"; /** * Initializes current user's MCRORCIDUser. * * @return current MCRUser as MCRORCIDUser */ public static MCRORCIDUser getCurrentUser() { final MCRSession session = MCRSessionMgr.getCurrentSession(); final String userID = session.getUserInformation().getUserID(); // refetch user because of rest issues final MCRUser user = MCRUserManager.getUser(userID); MCRORCIDUser orcidUser = (MCRORCIDUser) session.get(KEY_ORCID_USER); if ((orcidUser == null) || !orcidUser.getUser().equals(user)) { orcidUser = new MCRORCIDUser(user); session.put(KEY_ORCID_USER, orcidUser); } return orcidUser; } }
1,768
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDApp.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/rest/MCRORCIDApp.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.rest; import org.apache.logging.log4j.LogManager; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.jersey.access.MCRRequestScopeACLFilter; import org.mycore.restapi.MCRCORSResponseFilter; import org.mycore.restapi.MCRIgnoreClientAbortInterceptor; import org.mycore.restapi.MCRSessionFilter; import org.mycore.restapi.MCRTransactionFilter; import org.mycore.restapi.converter.MCRObjectIDParamConverterProvider; import jakarta.ws.rs.ApplicationPath; /** * ORCID API REST app. */ @ApplicationPath("/api/orcid") public class MCRORCIDApp extends ResourceConfig { /** * Creates ORCID API app. */ public MCRORCIDApp() { super(); initAppName(); property(ServerProperties.APPLICATION_NAME, getApplicationName()); packages(getRestPackages()); property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true); register(MCRSessionFilter.class); register(MCRTransactionFilter.class); register(MCRORCIDFeature.class); register(MCRObjectIDParamConverterProvider.class); register(MCRCORSResponseFilter.class); register(MCRRequestScopeACLFilter.class); register(MCRIgnoreClientAbortInterceptor.class); } private void initAppName() { setApplicationName("MyCoRe ORCID-API " + getVersion()); LogManager.getLogger().info("Initiialize {}", getApplicationName()); } private String getVersion() { return "1.0"; } private String[] getRestPackages() { return MCRConfiguration2.getOrThrow("MCR.ORCID2.API.Resource.Packages", MCRConfiguration2::splitValue) .toArray(String[]::new); } }
2,543
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDFeature.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/rest/MCRORCIDFeature.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.rest; import java.lang.reflect.Method; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.jersey.feature.MCRJerseyDefaultFeature; import org.mycore.restapi.MCREnableTransactionFilter; import org.mycore.restapi.annotations.MCRRequireTransaction; import jakarta.ws.rs.container.ResourceInfo; import jakarta.ws.rs.core.FeatureContext; import jakarta.ws.rs.ext.Provider; /** * Jersey configuration for ORCID end point. */ @Provider public class MCRORCIDFeature extends MCRJerseyDefaultFeature { @Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { Class<?> resourceClass = resourceInfo.getResourceClass(); Method resourceMethod = resourceInfo.getResourceMethod(); if (requiresTransaction(resourceClass, resourceMethod)) { context.register(MCREnableTransactionFilter.class); } super.configure(resourceInfo, context); } /** * Checks if the class/method is annotated by {@link MCRRequireTransaction}. * * @param resourceClass the class to check * @param resourceMethod the method to check * @return true if one ore both is annotated and requires transaction */ protected boolean requiresTransaction(Class<?> resourceClass, Method resourceMethod) { return resourceClass.getAnnotation(MCRRequireTransaction.class) != null || resourceMethod.getAnnotation(MCRRequireTransaction.class) != null; } @Override protected List<String> getPackages() { return MCRConfiguration2.getString("MCR.ORCID2.API.Resource.Packages").map(MCRConfiguration2::splitValue) .orElse(Stream.empty()) .collect(Collectors.toList()); } @Override protected void registerSessionHookFilter(FeatureContext context) { // don't register transaction filter, is already implemented by MCRSessionFilter } @Override protected void registerTransactionFilter(FeatureContext context) { // don't register transaction filter, is already implemented by MCRSessionFilter } @Override protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) { super.registerAccessFilter(context, resourceClass, resourceMethod); } }
3,153
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/rest/resources/MCRORCIDResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.rest.resources; import java.util.Map; import org.mycore.frontend.jersey.access.MCRRequireLogin; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.user.MCRORCIDSessionUtils; import org.mycore.orcid2.user.MCRORCIDUser; import org.mycore.orcid2.user.MCRORCIDUserProperties; import org.mycore.orcid2.user.MCRORCIDUserUtils; import org.mycore.restapi.annotations.MCRRequireTransaction; import org.mycore.user2.MCRUserManager; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; /** * Base resource for ORCID methods. */ @Path("v1") public class MCRORCIDResource { /** * Returns the ORCID status of the current user as JSON, e.g. * * { * orcids: ['0000-0001-5484-889X'], * trustedOrcids: ['0000-0001-5484-889X'], * } * @return the user status * @throws WebApplicationException if user is guest */ @GET @Path("user-status") @Produces(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRRequireLogin.class) public MCRORCIDUserStatus getUserStatus() { final MCRORCIDUser user = MCRORCIDSessionUtils.getCurrentUser(); final String[] orcids = user.getORCIDs().toArray(String[]::new); final String[] credentials = user.getCredentials().entrySet().stream().map(Map.Entry::getKey) .toArray(String[]::new); return new MCRORCIDUserStatus(orcids, credentials); } /** * Revokes ORCID iD for current user. * * @param orcid the ORCID iD * @return Response * @throws WebApplicationException if ORCID iD is null, user is guest or revoke fails */ @POST @Path("revoke/{orcid}") @MCRRequireTransaction @MCRRestrictedAccess(MCRRequireLogin.class) public Response revoke(@PathParam("orcid") String orcid) { if (orcid == null) { throw new WebApplicationException(Status.BAD_REQUEST); } final MCRORCIDUser orcidUser = MCRORCIDSessionUtils.getCurrentUser(); try { MCRORCIDUserUtils.revokeCredentialByORCID(orcidUser, orcid); } catch (MCRORCIDException e) { throw new WebApplicationException(e, Status.BAD_REQUEST); } return Response.ok().build(); } /** * Returns MCRORCIDUserProperties for ORCID iD. * * @param orcid the ORCID iD * @return the MCRORCIDUserProperties * @throws WebApplicationException if ORCID iD is null, user is guest */ @GET @Path("{orcid}/user-properties") @Produces(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRRequireLogin.class) public MCRORCIDUserProperties setUserProperties(@PathParam("orcid") String orcid) { if (orcid == null) { throw new WebApplicationException(Status.BAD_REQUEST); } final MCRORCIDUser orcidUser = MCRORCIDSessionUtils.getCurrentUser(); return orcidUser.getUserPropertiesByORCID(orcid); } /** * Updates MCRORCIDUserProperties for ORCID iD. * * @param orcid the ORCID iD * @param userProperties the MCRORCIDUserProperties * @return Response * @throws WebApplicationException if ORCID iD is null, user is guest or set fails */ @PUT @Path("{orcid}/user-properties") @MCRRequireTransaction @Consumes(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRRequireLogin.class) public Response setUserProperties(@PathParam("orcid") String orcid, MCRORCIDUserProperties userProperties) { if (orcid == null) { throw new WebApplicationException(Status.BAD_REQUEST); } final MCRORCIDUser orcidUser = MCRORCIDSessionUtils.getCurrentUser(); try { orcidUser.setUserProperties(orcid, userProperties); MCRUserManager.updateUser(orcidUser.getUser()); } catch (MCRORCIDException e) { throw new WebApplicationException(e, Status.BAD_REQUEST); } return Response.ok().build(); } static class MCRORCIDUserStatus { private String[] orcids; private String[] trustedOrcids; MCRORCIDUserStatus(String[] orcids, String[] trustedOrcids) { this.orcids = orcids; this.trustedOrcids = trustedOrcids; } public String[] getOrcids() { return orcids; } public String[] getTrustedOrcids() { return trustedOrcids; } } }
5,548
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDHashResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/util/MCRORCIDHashResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.util; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.common.MCRException; import org.mycore.common.MCRUtils; /** * Provides URIResolver to hash string. */ public class MCRORCIDHashResolver implements URIResolver { /** * Hashes given input with given algoritm. * * Syntax: <code>hash:{input}:{algorithm}:{?salt}:{?iterations}</code> * * input and salt will be url decoded * * @param href * URI in the syntax above * @param base * not used * * @return hashed input as hex string * @throws MCRException query is invalid or hash algorithm is not supported * @see javax.xml.transform.URIResolver */ @Override public Source resolve(String href, String base) throws TransformerException { final String[] split = href.split(":", 4); if (split.length < 3) { throw new IllegalArgumentException("Invalid format of uri for retrieval of hash: " + href); } final String input = URLDecoder.decode(split[1], StandardCharsets.UTF_8); final String algorithm = split[2]; String result = null; try { if (split.length == 3) { result = MCRUtils.hashString(input, algorithm, null, 1); } else { final String optional = split[3]; final int separatorIndex = optional.indexOf(":"); if (separatorIndex >= 0) { final String salt = URLDecoder.decode(optional.substring(0, separatorIndex), StandardCharsets.UTF_8); final int iterations = Integer.parseInt(optional.substring(separatorIndex + 1)); result = MCRUtils.hashString(input, algorithm, salt.getBytes(StandardCharsets.UTF_8), iterations); } else { final String salt = URLDecoder.decode(optional, StandardCharsets.UTF_8); result = MCRUtils.hashString(input, algorithm, salt.getBytes(StandardCharsets.UTF_8), 1); } } } catch (NumberFormatException e) { throw new MCRException("Invalid format of uri for retrieval of hash: " + href); } final Element root = new Element("string"); root.setText(result); return new JDOMSource(root); } }
3,337
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifier.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/util/MCRIdentifier.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.util; import java.util.Locale; import java.util.Objects; /** * Class to store IDs. */ public class MCRIdentifier { private final String type; private final String value; /** * Constructs new MCRIdentifier object with type and value. * * @param type the id type * @param value the id value */ public MCRIdentifier(String type, String value) { this.type = type; this.value = value; } /** * Returns the id type. * * @return id type */ public String getType() { return type; } /** * Returns the id value. * * @return id value */ public String getValue() { return value; } @Override public int hashCode() { return Objects.hash(type, value); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MCRIdentifier identifier = (MCRIdentifier) obj; return Objects.equals(type, identifier.type) && Objects.equals(value, identifier.value); } @Override public String toString() { return String.format(Locale.ROOT, "%s:%s", type, value); } }
2,107
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRORCIDWorkEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid2/src/main/java/org/mycore/orcid2/work/MCRORCIDWorkEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.orcid2.work; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mods.MCRMODSWrapper; import org.mycore.orcid2.MCRORCIDUtils; import org.mycore.orcid2.client.MCRORCIDCredential; import org.mycore.orcid2.client.exception.MCRORCIDInvalidScopeException; import org.mycore.orcid2.client.exception.MCRORCIDNotFoundException; import org.mycore.orcid2.client.exception.MCRORCIDRequestException; import org.mycore.orcid2.exception.MCRORCIDException; import org.mycore.orcid2.metadata.MCRORCIDFlagContent; import org.mycore.orcid2.metadata.MCRORCIDMetadataUtils; import org.mycore.orcid2.metadata.MCRORCIDPutCodeInfo; import org.mycore.orcid2.metadata.MCRORCIDUserInfo; import org.mycore.orcid2.user.MCRORCIDUser; import org.mycore.orcid2.user.MCRORCIDUserProperties; import org.mycore.orcid2.user.MCRORCIDUserUtils; import org.mycore.orcid2.util.MCRIdentifier; import org.mycore.user2.MCRUser; import org.orcid.jaxb.model.message.ScopeConstants; /** * When a publication is created or updated locally in this application, * collects all ORCID name identifiers from the MODS metadata, * looks up login users that have one of these identifiers stored in their user attributes, * checks if these users have an ORCID profile we know of * and have authorized us to update their profile as trusted party, * and then creates/updates the publication in the works section of that profile. */ public abstract class MCRORCIDWorkEventHandler<T> extends MCREventHandlerBase { private static final Logger LOGGER = LogManager.getLogger(); private static final boolean COLLECT_EXTERNAL_PUT_CODES = MCRConfiguration2 .getBoolean("MCR.ORCID2.WorkEventHandler.CollectExternalPutCodes").orElse(false); private static final boolean SAVE_OTHER_PUT_CODES = MCRConfiguration2 .getBoolean("MCR.ORCID2.Metadata.WorkInfo.SaveOtherPutCodes").orElse(false); @Override protected void handleObjectCreated(MCREvent evt, MCRObject object) { handlePublication(object); } @Override protected void handleObjectUpdated(MCREvent evt, MCRObject object) { handlePublication(object); } @Override protected void handleObjectDeleted(MCREvent evt, MCRObject object) { final MCRObjectID objectID = object.getId(); LOGGER.info("Start deleting {} to ORCID.", objectID); if (!MCRMODSWrapper.isSupported(object)) { return; } try { final T work = transformObject(new MCRJDOMContent(object.createXML())); final Set<MCRIdentifier> identifiers = listTrustedIdentifiers(work); final MCRORCIDFlagContent flagContent = Optional .ofNullable(MCRORCIDMetadataUtils.getORCIDFlagContent(object)).orElse(new MCRORCIDFlagContent()); final Map<String, MCRORCIDUser> toDelete = listUserOrcidPairFromFlag(flagContent); toDelete.putAll(listUserOrcidPairFromObject(object)); deleteWorks(toDelete, identifiers, flagContent); LOGGER.info("Finished deleting {} from ORCID successfully.", objectID); } catch (Exception e) { LOGGER.warn("Error while deleting object {}.", objectID, e); } } @SuppressWarnings("PMD.NPathComplexity") private void handlePublication(MCRObject object) { final MCRObjectID objectID = object.getId(); LOGGER.info("Start publishing {} to ORCID.", objectID); if (!MCRMODSWrapper.isSupported(object)) { LOGGER.info("MODS object is required. Skipping {}...", objectID); return; } MCRObject filteredObject = null; try { filteredObject = MCRORCIDUtils.filterObject(object); } catch (MCRORCIDException e) { LOGGER.warn("Error while filtering {}.", objectID); return; } if (!MCRORCIDUtils.checkEmptyMODS(filteredObject)) { LOGGER.info("Filtered MODS is empty. Skipping {}...", objectID); return; } if (!MCRORCIDUtils.checkPublishState(object)) { LOGGER.info("Object has wrong state. Skipping {}...", objectID); tryCollectAndSaveExternalPutCodes(filteredObject); return; } if (MCRMetadataManager.exists(objectID)) { final MCRObject outdatedObject = MCRMetadataManager.retrieveMCRObject(objectID); if (MCRXMLHelper.deepEqual(new MCRMODSWrapper(object).getMODS(), new MCRMODSWrapper(outdatedObject).getMODS())) { LOGGER.info("Metadata does not changed. Skipping {}...", objectID); tryCollectAndSaveExternalPutCodes(filteredObject); return; } } final MCRORCIDFlagContent flagContent = Optional.ofNullable(MCRORCIDMetadataUtils.getORCIDFlagContent(object)) .orElse(new MCRORCIDFlagContent()); final Map<String, MCRORCIDUser> userOrcidPairFromFlag = listUserOrcidPairFromFlag(flagContent); final Map<String, MCRORCIDUser> userOrcidPairFromObject = listUserOrcidPairFromObject(object); final Map<String, MCRORCIDUser> toDelete = new HashMap<>(userOrcidPairFromFlag); toDelete.keySet().removeAll(userOrcidPairFromObject.keySet()); final Map<String, MCRORCIDUser> toPublish = new HashMap<>(userOrcidPairFromFlag); toPublish.putAll(userOrcidPairFromObject); toPublish.keySet().removeAll(toDelete.keySet()); if (toDelete.isEmpty() && toPublish.isEmpty()) { LOGGER.info("Nothing to delete or publish. Skipping {}...", objectID); tryCollectAndSaveExternalPutCodes(filteredObject); return; } try { final T work = transformObject(new MCRJDOMContent(filteredObject.createXML())); final Set<MCRIdentifier> identifiers = listTrustedIdentifiers(work); if (!toDelete.isEmpty()) { deleteWorks(toDelete, identifiers, flagContent); } final Set<String> successfulPublished = new HashSet<>(); if (!toPublish.isEmpty()) { publishWorks(toPublish, identifiers, work, flagContent, successfulPublished); } if (COLLECT_EXTERNAL_PUT_CODES && SAVE_OTHER_PUT_CODES) { collectExternalPutCodes(flagContent, identifiers, successfulPublished); } LOGGER.info("Finished publishing {} to ORCID successfully.", objectID); } catch (Exception e) { LOGGER.warn("Error while publishing {} to ORCID.", objectID, e); } finally { try { MCRORCIDMetadataUtils.setORCIDFlagContent(object, flagContent); } catch (MCRORCIDException e) { LOGGER.warn("Error while setting ORCID flag content to {}.", objectID, e); } } } private void deleteWorks(Map<String, MCRORCIDUser> userOrcidPair, Set<MCRIdentifier> identifiers, MCRORCIDFlagContent flagContent) { for (Map.Entry<String, MCRORCIDUser> entry : userOrcidPair.entrySet()) { final String orcid = entry.getKey(); final MCRORCIDUser user = entry.getValue(); final MCRORCIDUserInfo userInfo = Optional.ofNullable(flagContent.getUserInfoByORCID(orcid)) .orElse(new MCRORCIDUserInfo(orcid)); if (userInfo.getWorkInfo() == null) { userInfo.setWorkInfo(new MCRORCIDPutCodeInfo()); } try { final MCRORCIDCredential credential = user.getCredentialByORCID(orcid); if (credential == null) { // user is no longer an author and we no longer have credentials continue; } updateWorkInfo(identifiers, userInfo.getWorkInfo(), orcid, credential); if (userInfo.getWorkInfo().hasOwnPutCode()) { removeWork(userInfo.getWorkInfo(), orcid, credential); flagContent.updateUserInfoByORCID(orcid, userInfo); } } catch (MCRORCIDNotFoundException e) { userInfo.getWorkInfo().setOwnPutCode(-1); flagContent.updateUserInfoByORCID(orcid, userInfo); } catch (Exception e) { LOGGER.warn("Error while deleting {}", userInfo.getWorkInfo().getOwnPutCode(), e); } } } private void publishWorks(Map<String, MCRORCIDUser> userOrcidPair, Set<MCRIdentifier> identifiers, T work, MCRORCIDFlagContent flagContent, Set<String> successful) { for (Map.Entry<String, MCRORCIDUser> entry : userOrcidPair.entrySet()) { final String orcid = entry.getKey(); final MCRORCIDUser user = entry.getValue(); try { final MCRORCIDCredential credential = user.getCredentialByORCID(orcid); if (credential == null) { continue; } final String scope = credential.getScope(); if (scope != null && !scope.contains(ScopeConstants.ACTIVITIES_UPDATE)) { LOGGER.info("The scope is invalid. Skipping..."); continue; } final MCRORCIDUserInfo userInfo = Optional.ofNullable(flagContent.getUserInfoByORCID(orcid)) .orElse(new MCRORCIDUserInfo(orcid)); if (userInfo.getWorkInfo() == null) { userInfo.setWorkInfo(new MCRORCIDPutCodeInfo()); } updateWorkInfo(identifiers, userInfo.getWorkInfo(), orcid, credential); publishWork(work, user.getUserPropertiesByORCID(orcid), userInfo.getWorkInfo(), orcid, credential); successful.add(orcid); flagContent.updateUserInfoByORCID(orcid, userInfo); } catch (Exception e) { LOGGER.warn("Error while publishing Work to {}", orcid, e); } } } private void publishWork(T work, MCRORCIDUserProperties userProperties, MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential) { if (workInfo.hasOwnPutCode()) { if (userProperties.isAlwaysUpdateWork()) { try { updateWork(workInfo.getOwnPutCode(), work, orcid, credential); } catch (MCRORCIDNotFoundException e) { if (userProperties.isRecreateDeletedWork()) { createWork(work, workInfo, orcid, credential); } } } } else if (workInfo.hadOwnPutCode()) { if (userProperties.isRecreateDeletedWork()) { createWork(work, workInfo, orcid, credential); } } else if (workInfo.hasOtherPutCodes()) { if (userProperties.isCreateDuplicateWork()) { createWork(work, workInfo, orcid, credential); } } else if (userProperties.isCreateFirstWork()) { createWork(work, workInfo, orcid, credential); } } private Map<String, MCRORCIDUser> listUserOrcidPairFromFlag(MCRORCIDFlagContent flagContent) { if (flagContent.getUserInfos() == null) { return new HashMap<>(); } final List<String> orcids = flagContent.getUserInfos().stream().filter(u -> u.getWorkInfo() != null) .filter(u -> u.getWorkInfo().hasOwnPutCode()).map(MCRORCIDUserInfo::getORCID).toList(); final Map<String, MCRORCIDUser> userOrcidPair = new HashMap<>(); for (String orcid : orcids) { try { userOrcidPair.put(orcid, MCRORCIDUserUtils.getORCIDUserByORCID(orcid)); } catch (MCRORCIDException e) { LOGGER.warn(e); } } return userOrcidPair; } private Map<String, MCRORCIDUser> listUserOrcidPairFromObject(MCRObject object) { final Map<String, MCRORCIDUser> userOrcidPair = new HashMap<>(); for (Element nameElement : MCRORCIDUtils.listNameElements(new MCRMODSWrapper(object))) { String orcid = null; final Set<MCRUser> users = new HashSet<MCRUser>(); for (MCRIdentifier id : listTrustedNameIdentifiers(nameElement)) { if (Objects.equals(id.getType(), "orcid")) { orcid = id.getValue(); } users.addAll(MCRORCIDUserUtils.getUserByID(id)); } if (orcid != null && users.size() == 1) { userOrcidPair.put(orcid, new MCRORCIDUser(users.iterator().next())); } else if (orcid != null && users.size() > 1) { final List<MCRORCIDUser> orcidUsers = new ArrayList<MCRORCIDUser>(); for (MCRUser user : users) { final MCRORCIDUser orcidUser = new MCRORCIDUser(user); if (orcidUser.hasCredential(orcid)) { orcidUsers.add(orcidUser); } } if (orcidUsers.size() == 1) { userOrcidPair.put(orcid, orcidUsers.get(0)); } else if (orcidUsers.size() > 1) { LOGGER.warn("This case is not implemented"); } } else if (orcid == null && users.size() == 1) { final MCRORCIDUser orcidUser = new MCRORCIDUser(users.iterator().next()); final Map<String, MCRORCIDCredential> pairs = orcidUser.getCredentials(); if (pairs.size() == 1) { userOrcidPair.put(pairs.entrySet().iterator().next().getKey(), orcidUser); } else if (pairs.size() > 1) { LOGGER.info("Try to find credentials for {}, but found more than one pair", users.iterator().next().getUserID()); } } else if (orcid == null && users.size() > 1) { LOGGER.warn("This case is not implemented"); } } return userOrcidPair; } private void tryCollectAndSaveExternalPutCodes(MCRObject object) { if (COLLECT_EXTERNAL_PUT_CODES && SAVE_OTHER_PUT_CODES) { try { collectAndSaveExternalPutCodes(object); } catch (Exception e) { LOGGER.warn("Error while collecting external put codes for {}.", object.getId(), e); } } } private void collectAndSaveExternalPutCodes(MCRObject object) { final MCRORCIDFlagContent flagContent = Optional.ofNullable(MCRORCIDMetadataUtils .getORCIDFlagContent(object)).orElse(new MCRORCIDFlagContent()); final T work = transformObject(new MCRJDOMContent(object.createXML())); final Set<MCRIdentifier> identifiers = listTrustedIdentifiers(work); collectExternalPutCodes(flagContent, identifiers, Collections.emptySet()); MCRORCIDMetadataUtils.setORCIDFlagContent(object, flagContent); } private void collectExternalPutCodes(MCRORCIDFlagContent flagContent, Set<MCRIdentifier> identifiers, Set<String> excludeORCIDs) { final Set<String> matchingOrcids = findMatchingORCIDs(identifiers); matchingOrcids.removeAll(excludeORCIDs); collectOtherPutCodes(identifiers, new ArrayList(matchingOrcids), flagContent); } private void collectOtherPutCodes(Set<MCRIdentifier> identifiers, List<String> orcids, MCRORCIDFlagContent flagContent) { orcids.forEach(orcid -> { try { final MCRORCIDUserInfo userInfo = Optional.ofNullable(flagContent.getUserInfoByORCID(orcid)) .orElse(new MCRORCIDUserInfo(orcid)); final MCRORCIDPutCodeInfo workInfo = userInfo.getWorkInfo(); if (workInfo == null) { userInfo.setWorkInfo(new MCRORCIDPutCodeInfo()); updateWorkInfo(identifiers, userInfo.getWorkInfo(), orcid); } else { updateWorkInfo(identifiers, workInfo, orcid); userInfo.getWorkInfo().setOtherPutCodes(workInfo.getOtherPutCodes()); } flagContent.updateUserInfoByORCID(orcid, userInfo); } catch (MCRORCIDException e) { LOGGER.warn("Could not collect put codes for {}.", orcid); } }); } private List<MCRIdentifier> listTrustedNameIdentifiers(Element nameElement) { return MCRORCIDUtils.getNameIdentifiers(nameElement).stream() .filter(i -> MCRORCIDUser.TRUSTED_NAME_IDENTIFIER_TYPES.contains(i.getType())).toList(); } /** * Lists trusted identifiers as Set of MCRIdentifier. * * @param work the Work * @return Set of MCRIdentifier */ abstract protected Set<MCRIdentifier> listTrustedIdentifiers(T work); /** * Lists matching ORCID iDs based on search via MCRIdentifier * * @param identifiers the MCRIdentifiers * @return Set of ORCID iDs as String * @throws MCRORCIDException if request fails */ abstract protected Set<String> findMatchingORCIDs(Set<MCRIdentifier> identifiers); /** * Removes Work in ORCID profile and updates MCRORCIDPutCodeInfo. * * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDInvalidScopeException if scope is invalid * @throws MCRORCIDRequestException if the request fails * @throws MCRORCIDNotFoundException if specified Work does not exist */ abstract protected void removeWork(MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential); /** * Updates Work in ORCID profile. * * @param putCode the put code * @param work the Work * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDInvalidScopeException if scope is invalid * @throws MCRORCIDRequestException if the request fails * @throws MCRORCIDNotFoundException if specified Work does not exist */ abstract protected void updateWork(long putCode, T work, String orcid, MCRORCIDCredential credential); /** * Creates Work in ORCID profile and updates MCRORCIDPutCodeInfo. * * @param work the Work * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDInvalidScopeException if scope is invalid * @throws MCRORCIDRequestException if the request fails */ abstract protected void createWork(T work, MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential); /** * Updates work info based on MCRIdentifier. * * @param identifiers the MCRIdentifier * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @param credential the MCRORCIDCredential * @throws MCRORCIDException look up request fails */ abstract protected void updateWorkInfo(Set<MCRIdentifier> identifiers, MCRORCIDPutCodeInfo workInfo, String orcid, MCRORCIDCredential credential); /** * Updates work info based on MCRIdentifier. * * @param identifiers the MCRIdentifier * @param workInfo the MCRORCIDPutCodeInfo * @param orcid the ORCID iD * @throws MCRORCIDException look up request fails */ abstract protected void updateWorkInfo(Set<MCRIdentifier> identifiers, MCRORCIDPutCodeInfo workInfo, String orcid); /** * Transforms MCRObject as MCRJDOMContent to Work. * * @param object the MCRObject * @return the Work */ @SuppressWarnings("TypeParameterUnusedInFormals") abstract protected <T> T transformObject(MCRJDOMContent object); }
21,289
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyUtilsTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/test/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyUtilsTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRSessionMgr; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; public class MCRAccessKeyUtilsTest extends MCRAccessKeyTestCase { private static final String READ_KEY = "blah"; private static final String WRITE_KEY = "blub"; private MCRObjectID objectId = null; private MCRObjectID derivateId = null; @Before @Override public void setUp() throws Exception { super.setUp(); objectId = getObject().getId(); derivateId = getDerivate().getId(); } @Test(expected = MCRAccessKeyException.class) public void testUnkownKey() { MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(objectId, READ_KEY); } @Test public void testSession() { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, READ_KEY); assertNotNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentSession(objectId)); assertNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentSession(derivateId)); MCRAccessKeyUtils.removeAccessKeySecretFromCurrentSession(objectId); assertNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentSession(objectId)); final MCRAccessKey accessKeyDerivate = new MCRAccessKey(WRITE_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(derivateId, accessKeyDerivate); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, WRITE_KEY); assertNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentSession(objectId)); assertNotNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentSession(derivateId)); } @Test public void testUser() { final MCRUser user = new MCRUser("junit"); MCRSessionMgr.getCurrentSession().setUserInformation(user); final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(objectId, READ_KEY); assertNotNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentUser(objectId)); MCRAccessKeyUtils.removeAccessKeySecretFromCurrentUser(objectId); assertNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentUser(objectId)); final MCRAccessKey accessKeyDerivate = new MCRAccessKey(WRITE_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(derivateId, accessKeyDerivate); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(objectId, WRITE_KEY); assertNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentUser(objectId)); assertNotNull(MCRAccessKeyUtils.getAccessKeySecretFromCurrentUser(derivateId)); } @Test public void testSessionOverride() { final MCRAccessKey accessKeyRead = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKeyRead); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, READ_KEY); final String readSecret = MCRAccessKeyUtils.getAccessKeySecretFromCurrentSession(objectId); final MCRAccessKey accessKeyWrite = new MCRAccessKey(WRITE_KEY, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, accessKeyWrite); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, WRITE_KEY); assertNotEquals(readSecret, MCRAccessKeyUtils.getAccessKeySecretFromCurrentSession(objectId)); } @Test public void testUserOverride() { final MCRUser user = new MCRUser("junit"); MCRSessionMgr.getCurrentSession().setUserInformation(user); final MCRAccessKey accessKeyRead = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKeyRead); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(objectId, READ_KEY); final String readSecret = MCRAccessKeyUtils.getAccessKeySecretFromCurrentUser(objectId); final MCRAccessKey accessKeyWrite = new MCRAccessKey(WRITE_KEY, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, accessKeyWrite); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(objectId, WRITE_KEY); assertNotEquals(readSecret, MCRAccessKeyUtils.getAccessKeySecretFromCurrentUser(objectId)); } @Test public void testCleanUpUserAttributes() { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); final MCRUser user = new MCRUser("junit"); MCRUserManager.createUser(user); MCRAccessKeyUtils.addAccessKeySecret(MCRUserManager.getUser("junit"), objectId, READ_KEY); final MCRAccessKey accessKey2 = new MCRAccessKey(READ_KEY, PERMISSION_READ); final MCRObjectID objectId2 = MCRObjectID.getInstance("mcr_object_00000002"); MCRAccessKeyManager.createAccessKey(objectId2, accessKey2); MCRAccessKeyUtils.addAccessKeySecret(MCRUserManager.getUser("junit"), objectId2, READ_KEY); final MCRUser user1 = new MCRUser("junit1"); MCRUserManager.createUser(user1); MCRAccessKeyUtils.addAccessKeySecret(MCRUserManager.getUser("junit1"), objectId, READ_KEY); MCRAccessKeyManager.removeAccessKey(objectId, MCRAccessKeyManager.hashSecret(READ_KEY, objectId)); MCRAccessKeyUtils.cleanUpUserAttributes(); assertNull(MCRAccessKeyUtils.getAccessKeySecret(MCRUserManager.getUser("junit"), objectId)); assertNull(MCRAccessKeyUtils.getAccessKeySecret(MCRUserManager.getUser("junit1"), objectId)); assertNotNull(MCRAccessKeyUtils.getAccessKeySecret(MCRUserManager.getUser("junit"), objectId2)); } }
7,096
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyTransformerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/test/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyTransformerTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; public class MCRAccessKeyTransformerTest extends MCRTestCase { private static final String OBJECT_ID = "mcr_test_00000001"; private static final String READ_KEY = "blah"; private static final String WRITE_KEY = "blub"; private static MCRObjectID objectId; @Override @Before public void setUp() throws Exception { super.setUp(); objectId = MCRObjectID.getInstance(OBJECT_ID); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString()); return testProperties; } @Test public void testAccessKeysTransform() { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); final List<MCRAccessKey> accessKeys = new ArrayList<>(); accessKeys.add(accessKey); final String json = MCRAccessKeyTransformer.jsonFromAccessKeys(accessKeys); final List<MCRAccessKey> transAccessKeys = MCRAccessKeyTransformer.accessKeysFromJson(json); final MCRAccessKey transAccessKey = transAccessKeys.get(0); assertNull(transAccessKey.getObjectId()); assertEquals(transAccessKey.getId(), 0); assertEquals(accessKey.getSecret(), transAccessKey.getSecret()); assertEquals(accessKey.getType(), transAccessKey.getType()); } @Test public void testElementTransform() throws IOException { final MCRAccessKey accessKeyRead = new MCRAccessKey(READ_KEY, PERMISSION_READ); final MCRAccessKey accessKeyWrite = new MCRAccessKey(WRITE_KEY, PERMISSION_WRITE); final List<MCRAccessKey> accessKeys = new ArrayList<>(); accessKeys.add(accessKeyRead); accessKeys.add(accessKeyWrite); final Element element = MCRAccessKeyTransformer.elementFromAccessKeys(accessKeys); new XMLOutputter(Format.getPrettyFormat()).output(element, System.out); final List<MCRAccessKey> transAccessKeys = MCRAccessKeyTransformer.accessKeysFromElement(objectId, element); assertEquals(2, transAccessKeys.size()); final MCRAccessKey transAccessKeyRead = transAccessKeys.get(0); assertEquals(accessKeyRead.getSecret(), transAccessKeyRead.getSecret()); assertEquals(accessKeyRead.getType(), transAccessKeyRead.getType()); } @Test public void testServiceTransform() throws IOException { final Element service = new Element("service"); final Element servFlags = new Element("servflags"); final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); final List<MCRAccessKey> accessKeys = new ArrayList<>(); accessKeys.add(accessKey); final String accessKeysJson = MCRAccessKeyTransformer.jsonFromAccessKeys(accessKeys); final Element servFlag = createServFlag("accesskeys", accessKeysJson); servFlags.addContent(servFlag); final Element sf1 = createServFlag("createdby", "administrator"); sf1.setText("administrator"); servFlags.addContent(sf1); service.addContent(servFlags); new XMLOutputter(Format.getPrettyFormat()).output(service, System.out); final List<MCRAccessKey> transAccessKeys = MCRAccessKeyTransformer.accessKeysFromElement(objectId, service); final MCRAccessKey transAccessKey = transAccessKeys.get(0); assertEquals(accessKey.getSecret(), transAccessKey.getSecret()); assertEquals(accessKey.getType(), transAccessKey.getType()); } private static Element createServFlag(final String type, final String content) { final Element servFlag = new Element("servflag"); servFlag.setAttribute("type", type); servFlag.setAttribute("inherited", "0"); servFlag.setAttribute("form", "plain"); servFlag.setText(content); return servFlag; } }
5,311
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyTestCase.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/test/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyTestCase.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import java.util.Map; import org.junit.After; import org.junit.Before; import org.mycore.access.MCRAccessBaseImpl; import org.mycore.common.MCRStoreTestCase; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; public class MCRAccessKeyTestCase extends MCRStoreTestCase { private static final String ACCESS_KEY_STRATEGY_PROP = "MCR.ACL.AccessKey.Strategy"; protected static final String ALLOWED_OBJECT_TYPES_PROP = ACCESS_KEY_STRATEGY_PROP + ".AllowedObjectTypes"; protected static final String ALLOWED_SESSION_PERMISSION_TYPES_PROP = ACCESS_KEY_STRATEGY_PROP + ".AllowedSessionPermissionTypes"; private static final String OBJECT_ID = "mcr_object_00000001"; private static final String DERIVATE_ID = "mcr_derivate_00000001"; private MCRObject object; private MCRDerivate derivate; @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties .put("MCR.Persistence.LinkTable.Store.Class", "org.mycore.backend.hibernate.MCRHIBLinkTableStore"); testProperties.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName()); testProperties.put("MCR.Metadata.Type.document", "true"); testProperties.put("MCR.Metadata.Type.object", Boolean.TRUE.toString()); testProperties.put("MCR.Metadata.Type.derivate", Boolean.TRUE.toString()); testProperties.put("MCR.Metadata.ObjectID.NumberPattern", "00000000"); return testProperties; } protected void setUpInstanceDefaultProperties() { MCRConfiguration2.set(ALLOWED_OBJECT_TYPES_PROP, "object,derivate"); MCRConfiguration2.set(ALLOWED_SESSION_PERMISSION_TYPES_PROP, "read,writedb"); } @Before @Override public void setUp() throws Exception { super.setUp(); object = new MCRObject(); object.setSchema("noSchema"); final MCRObjectID objectId = MCRObjectID.getInstance(OBJECT_ID); object.setId(objectId); MCRMetadataManager.create(object); derivate = new MCRDerivate(); derivate.setSchema("datamodel-derivate.xsd"); final MCRObjectID derivateId = MCRObjectID.getInstance(DERIVATE_ID); derivate.setId(derivateId); final MCRMetaIFS ifs = new MCRMetaIFS("internal", null); derivate.getDerivate().setInternals(ifs); MCRMetaLinkID metaLinkID = new MCRMetaLinkID("internal", 0); metaLinkID.setReference(objectId.toString(), null, null); derivate.getDerivate().setLinkMeta(metaLinkID); MCRMetadataManager.create(derivate); setUpInstanceDefaultProperties(); } @After @Override public void tearDown() throws Exception { MCRMetadataManager.delete(derivate); MCRMetadataManager.delete(object); super.tearDown(); } public MCRObject getObject() { return object; } public MCRDerivate getDerivate() { return derivate; } }
4,076
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyManagerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/test/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyManagerTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRException; import org.mycore.common.MCRJPATestCase; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyCollisionException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; public class MCRAccessKeyManagerTest extends MCRJPATestCase { private static final String OBJECT_ID = "mcr_test_00000001"; private static final String READ_KEY = "blah"; private static final String WRITE_KEY = "blub"; private static MCRObjectID objectId; @Override @Before public void setUp() throws Exception { super.setUp(); objectId = MCRObjectID.getInstance(OBJECT_ID); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString()); return testProperties; } @Test(expected = MCRAccessKeyCollisionException.class) public void testKeyAddCollison() { final MCRAccessKey accessKeyRead = new MCRAccessKey(WRITE_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKeyRead); final MCRAccessKey accessKeyWrite = new MCRAccessKey(WRITE_KEY, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, accessKeyWrite); } @Test public void testCreateKey() throws MCRException { final MCRAccessKey accessKeyRead = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKeyRead); final MCRAccessKey accessKey = MCRAccessKeyManager.getAccessKeyWithSecret(objectId, MCRAccessKeyManager.hashSecret(READ_KEY, objectId)); assertNotNull(accessKey); } @Test(expected = MCRAccessKeyCollisionException.class) public void testDuplicate() { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); final MCRAccessKey accessKeySame = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKeySame); } @Test public void testExistsKey() throws MCRException { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); assertTrue(MCRAccessKeyManager.listAccessKeys(objectId).size() > 0); } @Test public void testUpdateType() throws MCRException { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); final MCRAccessKey accessKeyNew = new MCRAccessKey(null, PERMISSION_WRITE); MCRAccessKeyManager.updateAccessKey(objectId, MCRAccessKeyManager.hashSecret(READ_KEY, objectId), accessKeyNew); final MCRAccessKey accessKeyUpdated = MCRAccessKeyManager.listAccessKeys(objectId).get(0); assertEquals(accessKeyNew.getType(), accessKeyUpdated.getType()); } @Test public void testUpdateIsActive() throws MCRException { MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); accessKey.setIsActive(false); MCRAccessKeyManager.updateAccessKey(objectId, MCRAccessKeyManager.hashSecret(READ_KEY, objectId), accessKey); accessKey = MCRAccessKeyManager.listAccessKeys(objectId).get(0); assertEquals(accessKey.getIsActive(), false); accessKey.setIsActive(true); MCRAccessKeyManager.updateAccessKey(objectId, MCRAccessKeyManager.hashSecret(READ_KEY, objectId), accessKey); accessKey = MCRAccessKeyManager.listAccessKeys(objectId).get(0); assertEquals(accessKey.getIsActive(), true); } @Test public void testDeleteKey() throws MCRException { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, accessKey); MCRAccessKeyManager.removeAccessKey(objectId, MCRAccessKeyManager.hashSecret(READ_KEY, objectId)); assertFalse(MCRAccessKeyManager.listAccessKeys(objectId).size() > 0); } }
5,458
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyStrategyHelperTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/test/java/org/mycore/mcr/acl/accesskey/strategy/MCRAccessKeyStrategyHelperTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey.strategy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mycore.access.MCRAccessManager.PERMISSION_DELETE; import static org.mycore.access.MCRAccessManager.PERMISSION_PREVIEW; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import static org.mycore.access.MCRAccessManager.PERMISSION_VIEW; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import java.util.Date; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; public class MCRAccessKeyStrategyHelperTest extends MCRTestCase { private static MCRAccessKey accessKey; @Override @Before public void setUp() throws Exception { super.setUp(); accessKey = new MCRAccessKey("bla", PERMISSION_READ); } @Test public void testSanitizePermission() { assertEquals(PERMISSION_DELETE, MCRAccessKeyStrategyHelper.sanitizePermission(PERMISSION_DELETE)); assertEquals(PERMISSION_READ, MCRAccessKeyStrategyHelper.sanitizePermission(PERMISSION_PREVIEW)); assertEquals(PERMISSION_READ, MCRAccessKeyStrategyHelper.sanitizePermission(PERMISSION_READ)); assertEquals(PERMISSION_READ, MCRAccessKeyStrategyHelper.sanitizePermission(PERMISSION_VIEW)); assertEquals(PERMISSION_WRITE, MCRAccessKeyStrategyHelper.sanitizePermission(PERMISSION_WRITE)); } @Test public void testVerifyAccessKey() { assertTrue(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); assertFalse(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_WRITE, accessKey)); accessKey.setType(PERMISSION_WRITE); assertTrue(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); assertTrue(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_WRITE, accessKey)); assertFalse(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_DELETE, accessKey)); } public void testVerifyAccessKeyIsActive() { assertTrue(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); accessKey.setIsActive(false); assertFalse(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); accessKey.setIsActive(true); assertTrue(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); } public void testVerifyAccessKeyExpiration() { assertTrue(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); accessKey.setExpiration(new Date()); assertFalse(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); accessKey.setExpiration(new Date(new Date().getTime() + (1000 * 60 * 60 * 24))); //tomorrow assertTrue(MCRAccessKeyStrategyHelper.verifyAccessKey(PERMISSION_READ, accessKey)); } }
3,722
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyStrategyTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/test/java/org/mycore/mcr/acl/accesskey/strategy/MCRAccessKeyStrategyTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey.strategy; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.MCRAccessKeyManager; import org.mycore.mcr.acl.accesskey.MCRAccessKeyTestCase; import org.mycore.mcr.acl.accesskey.MCRAccessKeyUtils; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; import org.mycore.user2.MCRUser; public class MCRAccessKeyStrategyTest extends MCRAccessKeyTestCase { private static final String READ_VALUE = "bla"; private static final String WRITE_VALUE = "blu"; private MCRAccessKeyStrategy strategy; private MCRObjectID objectId = null; private MCRObjectID derivateId = null; @Before @Override public void setUp() throws Exception { super.setUp(); objectId = getObject().getId(); derivateId = getDerivate().getId(); strategy = new MCRAccessKeyStrategy(); } @Test public void testDefaultPermission() { assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); final MCRAccessKey readKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, readKey); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, writeKey); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); } @Test public void testSessionFilter() { final MCRAccessKey readKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, readKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, READ_VALUE); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, writeKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, WRITE_VALUE); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); MCRConfiguration2.set(ALLOWED_SESSION_PERMISSION_TYPES_PROP, "read"); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); MCRConfiguration2.set(ALLOWED_SESSION_PERMISSION_TYPES_PROP, ""); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); MCRConfiguration2.set(ALLOWED_SESSION_PERMISSION_TYPES_PROP, "writedb"); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); } @Test public void testObjectFilter() { final MCRAccessKey derivateKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(derivateId, derivateKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(derivateId, READ_VALUE); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); final MCRAccessKey objectKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, objectKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, READ_VALUE); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); MCRConfiguration2.set(ALLOWED_OBJECT_TYPES_PROP, "object"); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); MCRConfiguration2.set(ALLOWED_OBJECT_TYPES_PROP, ""); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); MCRConfiguration2.set(ALLOWED_OBJECT_TYPES_PROP, "derivate"); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); } @Test public void testPermissionInheritance() { final MCRAccessKey readKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(derivateId, readKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(derivateId, READ_VALUE); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, writeKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, WRITE_VALUE); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); } @Test public void testObjectSession() { final MCRAccessKey readKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, readKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, READ_VALUE); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, writeKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(objectId, WRITE_VALUE); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); } @Test public void testObjectUser() { final MCRUser user = new MCRUser("junit"); MCRSessionMgr.getCurrentSession().setUserInformation(user); final MCRAccessKey readKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(objectId, readKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(objectId, READ_VALUE); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(objectId, writeKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(objectId, WRITE_VALUE); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); } @Test public void testDerivateSession() { final MCRAccessKey readKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(derivateId, readKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(derivateId, READ_VALUE); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(derivateId, writeKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(derivateId, WRITE_VALUE); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); } @Test public void testDerivateUser() { MCRUser user = new MCRUser("junit"); MCRSessionMgr.getCurrentSession().setUserInformation(user); final MCRAccessKey readKey = new MCRAccessKey(READ_VALUE, PERMISSION_READ); MCRAccessKeyManager.createAccessKey(derivateId, readKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(derivateId, READ_VALUE); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(derivateId, writeKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(derivateId, WRITE_VALUE); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(objectId.toString(), PERMISSION_WRITE)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); } @Test public void checkDominance() { MCRUser user = new MCRUser("junit"); MCRSessionMgr.getCurrentSession().setUserInformation(user); final MCRAccessKey writeKey = new MCRAccessKey(WRITE_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(derivateId, writeKey); MCRAccessKeyUtils.addAccessKeySecretToCurrentSession(derivateId, WRITE_VALUE); MCRConfiguration2.set(ALLOWED_SESSION_PERMISSION_TYPES_PROP, "read"); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertFalse(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); final MCRAccessKey writeKey2 = new MCRAccessKey(READ_VALUE, PERMISSION_WRITE); MCRAccessKeyManager.createAccessKey(derivateId, writeKey2); MCRAccessKeyUtils.addAccessKeySecretToCurrentUser(derivateId, READ_VALUE); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_READ)); assertTrue(strategy.checkPermission(derivateId.toString(), PERMISSION_WRITE)); } }
13,303
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/test/java/org/mycore/mcr/acl/accesskey/model/MCRAccessKeyTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey.model; import static org.junit.Assert.assertEquals; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import java.util.Map; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRAccessKeyTest extends MCRTestCase { private static final String READ_KEY = "blah"; @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString()); return testProperties; } @Test public void testKey() { final MCRAccessKey accessKey = new MCRAccessKey(READ_KEY, PERMISSION_READ); assertEquals(READ_KEY, accessKey.getSecret()); assertEquals(PERMISSION_READ, accessKey.getType()); } }
1,578
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.mycore.access.MCRAccessCacheHelper; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRException; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyException; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyNotFoundException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserAttribute; import org.mycore.user2.MCRUserManager; /** * Methods for setting and removing {@link MCRAccessKey} for users. */ public class MCRAccessKeyUtils { /** * Prefix for user attribute name for value */ public static final String ACCESS_KEY_PREFIX = "acckey_"; private static final String ACCESS_KEY_STRATEGY_PROP_PREFX = "MCR.ACL.AccessKey.Strategy"; private static final String ALLOWED_OBJECT_TYPES_PROP = ACCESS_KEY_STRATEGY_PROP_PREFX + ".AllowedObjectTypes"; private static final String ALLOWED_SESSION_PERMISSION_TYPES_PROP = ACCESS_KEY_STRATEGY_PROP_PREFX + ".AllowedSessionPermissionTypes"; private static Set<String> allowedObjectTypes = loadAllowedObjectTypes(); private static Set<String> allowedSessionPermissionTypes = loadAllowedSessionPermissionTypes(); private static Set<String> parseListStringToSet(final Optional<String> listString) { return listString.stream() .flatMap(MCRConfiguration2::splitValue) .collect(Collectors.toSet()); } private static Set<String> loadAllowedObjectTypes() { MCRConfiguration2.addPropertyChangeEventLister(ALLOWED_OBJECT_TYPES_PROP::equals, (p1, p2, p3) -> allowedObjectTypes = parseListStringToSet(p3)); return parseListStringToSet(MCRConfiguration2.getString(ALLOWED_OBJECT_TYPES_PROP)); } private static Set<String> loadAllowedSessionPermissionTypes() { MCRConfiguration2.addPropertyChangeEventLister(ALLOWED_SESSION_PERMISSION_TYPES_PROP::equals, (p1, p2, p3) -> allowedSessionPermissionTypes = parseListStringToSet(p3)); return parseListStringToSet(MCRConfiguration2.getString(ALLOWED_SESSION_PERMISSION_TYPES_PROP)); } /** * Adds the value of {@link MCRAccessKey} as an attribute to a {@link MCRSession} for {@link MCRObjectID}. * * @param session the {@link MCRSession} * @param objectId the {@link MCRObjectID} * @param value the value of a {@link MCRAccessKey} * @throws MCRException if there is no matching {@link MCRAccessKey} with the same value or not allowed. */ public static synchronized void addAccessKeySecretForObject(final MCRSession session, final MCRObjectID objectId, final String value) throws MCRException { if (!isAccessKeyForSessionAllowed()) { throw new MCRAccessKeyException("Access keys is not allowed."); } if (isAccessKeyForObjectTypeAllowed(objectId.getTypeId())) { final String secret = MCRAccessKeyManager.hashSecret(value, objectId); final MCRAccessKey accessKey = MCRAccessKeyManager.getAccessKeyWithSecret(objectId, secret); if (accessKey == null) { throw new MCRAccessKeyNotFoundException("Access key is invalid."); } else if (isAccessKeyForSessionAllowed(accessKey.getType())) { session.put(getAttributeName(objectId), secret); MCRAccessManager.invalidPermissionCacheByID(objectId.toString()); } else { throw new MCRAccessKeyException("Access key is not allowed."); } } else { throw new MCRAccessKeyException("Access key is not allowed."); } } /** * Adds the value of {@link MCRAccessKey} as an attribute to a {@link MCRSession} for {@link MCRObjectID} * including derivates. * * @param session the {@link MCRSession} * @param objectId the {@link MCRObjectID} * @param value the value of a {@link MCRAccessKey} * @throws MCRException if there is no matching {@link MCRAccessKey} with the same value or not allowed. */ public static synchronized void addAccessKeySecret(final MCRSession session, final MCRObjectID objectId, final String value) throws MCRException { if (!isAccessKeyForSessionAllowed()) { throw new MCRAccessKeyException("Access keys is not allowed."); } if ("derivate".equals(objectId.getTypeId())) { addAccessKeySecretForObject(session, objectId, value); } else { boolean success = false; try { addAccessKeySecretForObject(session, objectId, value); MCRAccessCacheHelper.clearPermissionCache(objectId.toString()); success = true; } catch (MCRAccessKeyException e) { // } final List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(objectId, 0, TimeUnit.SECONDS); for (final MCRObjectID derivateId : derivateIds) { try { addAccessKeySecretForObject(session, derivateId, value); success = true; } catch (MCRAccessKeyException e) { // } } if (!success) { throw new MCRAccessKeyException("Access key is invalid or is not allowed."); } } } /** * Adds the value of a {@link MCRAccessKey} as user attribute to a {@link MCRUser} for a {@link MCRObjectID}. * * @param user the {@link MCRUser} the value should assigned * @param objectId the {@link MCRObjectID} * @param value the value of a {@link MCRAccessKey} * @throws MCRException if there is no matching {@link MCRAccessKey} with the same value. */ public static synchronized void addAccessKeySecretForObject(final MCRUser user, final MCRObjectID objectId, final String value) throws MCRException { if (isAccessKeyForObjectTypeAllowed(objectId.getTypeId())) { final String secret = MCRAccessKeyManager.hashSecret(value, objectId); final MCRAccessKey accessKey = MCRAccessKeyManager.getAccessKeyWithSecret(objectId, secret); if (accessKey == null) { throw new MCRAccessKeyNotFoundException("Access key is invalid."); } else { user.setUserAttribute(getAttributeName(objectId), secret); MCRUserManager.updateUser(user); MCRAccessManager.invalidPermissionCacheByID(objectId.toString()); } } else { throw new MCRAccessKeyException("Access key is not allowed."); } } /** * Adds the value of a {@link MCRAccessKey} as user attribute to a {@link MCRUser} for a {@link MCRObjectID} * including derivates. * * @param user the {@link MCRUser} the value should assigned * @param objectId the {@link MCRObjectID} * @param value the value of a {@link MCRAccessKey} * @throws MCRException if there is no matching {@link MCRAccessKey} with the same value. */ public static synchronized void addAccessKeySecret(final MCRUser user, final MCRObjectID objectId, final String value) throws MCRException { if ("derivate".equals(objectId.getTypeId())) { addAccessKeySecretForObject(user, objectId, value); } else { boolean success = false; try { addAccessKeySecretForObject(user, objectId, value); MCRAccessCacheHelper.clearPermissionCache(objectId.toString()); success = true; } catch (MCRAccessKeyException e) { // } final List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(objectId, 0, TimeUnit.SECONDS); for (final MCRObjectID derivateId : derivateIds) { try { addAccessKeySecretForObject(user, derivateId, value); success = true; } catch (MCRAccessKeyException e) { // } } if (!success) { throw new MCRAccessKeyException("Access key is invalid or is not allowed."); } } } /** * Adds the value of {@link MCRAccessKey} as an attribute to the current {@link MCRSession} for {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} * @param value the value of a {@link MCRAccessKey} * @throws MCRException if there is no matching {@link MCRAccessKey} with the same value. */ public static synchronized void addAccessKeySecretToCurrentSession(final MCRObjectID objectId, final String value) throws MCRException { addAccessKeySecret(MCRSessionMgr.getCurrentSession(), objectId, value); } /** * Adds the value of {@link MCRAccessKey} as user attribute to the current {@link MCRUser} for {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} * @param value the value of a {@link MCRAccessKey} * @throws MCRException if there is no matching {@link MCRAccessKey} with the same value. */ public static synchronized void addAccessKeySecretToCurrentUser(final MCRObjectID objectId, final String value) throws MCRException { addAccessKeySecret(MCRUserManager.getCurrentUser(), objectId, value); } /** * Lists all users which own at least an access key user attribute in given range * * @param offset the offset * @param limit the limit * @return a list with all users which own at least an access key in given range */ private static List<MCRUser> listUsersWithAccessKey(final int offset, final int limit) { return MCRUserManager.listUsers(null, null, null, null, ACCESS_KEY_PREFIX + "*", null, offset, limit); } /** * Cleans all access key secret attributes of users if the corresponding key does not exist. */ public static void cleanUpUserAttributes() { final Set<MCRUserAttribute> validAttributes = new HashSet<>(); final Set<MCRUserAttribute> deadAttributes = new HashSet<>(); int offset = 0; final int limit = 1024; List<MCRUser> users = new ArrayList<>(); do { users = listUsersWithAccessKey(offset, limit); for (final MCRUser user : users) { final List<MCRUserAttribute> attributes = user.getAttributes() .stream() .filter(attribute -> attribute.getName().startsWith(MCRAccessKeyUtils.ACCESS_KEY_PREFIX)) .filter(attribute -> !validAttributes.contains(attribute)) .collect(Collectors.toList()); for (MCRUserAttribute attribute : attributes) { final String attributeName = attribute.getName(); final MCRObjectID objectId = MCRObjectID.getInstance(attributeName.substring( attributeName.indexOf("_") + 1)); if (deadAttributes.contains(attribute)) { MCRAccessKeyUtils.removeAccessKeySecret(user, objectId); } else { if (MCRAccessKeyManager.getAccessKeyWithSecret(objectId, attribute.getValue()) != null) { validAttributes.add(attribute); } else { MCRAccessKeyUtils.removeAccessKeySecret(user, objectId); deadAttributes.add(attribute); } } } } offset += limit; } while (users.size() == limit); } /** * Fetches access key value from session attribute for a {@link MCRObjectID}. * * @param session the {@link MCRSession} * @param objectId the {@link MCRObjectID} * @return secret or null */ public static synchronized String getAccessKeySecret(final MCRSession session, final MCRObjectID objectId) { final Object secret = session.get(getAttributeName(objectId)); if (secret != null) { return (String) secret; } return null; } /** * Fetches access key value from user attribute for a {@link MCRObjectID}. * * @param userInformation the {@link MCRUserInformation} * @param objectId the {@link MCRObjectID} * @return secret or null */ public static synchronized String getAccessKeySecret(final MCRUserInformation userInformation, final MCRObjectID objectId) { return userInformation.getUserAttribute(getAttributeName(objectId)); } /** * Fetches access key value from session attribute for a {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} * @return secret or null */ public static synchronized String getAccessKeySecretFromCurrentSession(final MCRObjectID objectId) { return getAccessKeySecret(MCRSessionMgr.getCurrentSession(), objectId); } /** * Fetches access key value from user attribute for a {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} * @return secret or null */ public static synchronized String getAccessKeySecretFromCurrentUser(final MCRObjectID objectId) { return getAccessKeySecret(MCRSessionMgr.getCurrentSession().getUserInformation(), objectId); } /** * Returns the attribute name for user and session of an access key value * * @param objectId the {@link MCRObjectID} * @return the attribute name */ private static String getAttributeName(final MCRObjectID objectId) { return ACCESS_KEY_PREFIX + objectId.toString(); } /** * Retrieves linked access key if exists from session * * @param session the {@link MCRSession} * @param objectId of a {@link MCRObjectID} * @return access key */ public static MCRAccessKey getLinkedAccessKey(final MCRSession session, final MCRObjectID objectId) { final String secret = getAccessKeySecret(session, objectId); if (secret != null) { return MCRAccessKeyManager.getAccessKeyWithSecret(objectId, secret); } return null; } /** * Retrieves linked access key if exists from user * * @param userInformation the {@link MCRUserInformation} * @param objectId of a {@link MCRObjectID} * @return access key */ public static MCRAccessKey getLinkedAccessKey(final MCRUserInformation userInformation, final MCRObjectID objectId) { final String secret = getAccessKeySecret(userInformation, objectId); if (secret != null) { return MCRAccessKeyManager.getAccessKeyWithSecret(objectId, secret); } return null; } /** * Retrieves linked access key if exists from current session * * @param objectId of a {@link MCRObjectID} * @return access key */ public static MCRAccessKey getLinkedAccessKeyFromCurrentSession(final MCRObjectID objectId) { return getLinkedAccessKey(MCRSessionMgr.getCurrentSession(), objectId); } /** * Retrieves linked access key if exists from current user * * @param objectId of a {@link MCRObjectID} * @return access key */ public static MCRAccessKey getLinkedAccessKeyFromCurrentUser(final MCRObjectID objectId) { return getLinkedAccessKey(MCRSessionMgr.getCurrentSession().getUserInformation(), objectId); } /** * Deletes the access key value attribute from given {@link MCRSession} for {@link MCRObjectID}. * * @param session the {@link MCRSession} * @param objectId the {@link MCRObjectID} */ public static synchronized void removeAccessKeySecret(final MCRSession session, final MCRObjectID objectId) { session.deleteObject(getAttributeName(objectId)); MCRAccessCacheHelper.clearPermissionCache(objectId.toString()); } /** * Deletes the access key value user attribute from given {@link MCRUser} for {@link MCRObjectID}. * * @param user the {@link MCRUser} * @param objectId the {@link MCRObjectID} */ public static synchronized void removeAccessKeySecret(final MCRUser user, final MCRObjectID objectId) { user.getAttributes().removeIf(ua -> ua.getName().equals(getAttributeName(objectId))); MCRUserManager.updateUser(user); MCRAccessCacheHelper.clearPermissionCache(objectId.toString()); } /** * Deletes access key value attribute from current {@link MCRSession} for a {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} */ public static synchronized void removeAccessKeySecretFromCurrentSession(final MCRObjectID objectId) { removeAccessKeySecret(MCRSessionMgr.getCurrentSession(), objectId); } /** * Deletes access key value user attribute from current {@link MCRUser} for a {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} */ public static synchronized void removeAccessKeySecretFromCurrentUser(final MCRObjectID objectId) { removeAccessKeySecret(MCRUserManager.getCurrentUser(), objectId); } public static boolean isAccessKeyForSessionAllowed() { return !allowedSessionPermissionTypes.isEmpty(); } public static boolean isAccessKeyForSessionAllowed(final String permission) { return allowedSessionPermissionTypes.contains(permission); } public static boolean isAccessKeyForObjectTypeAllowed(final String type) { return allowedObjectTypes.contains(type); } public static Set<String> getAllowedSessionPermissionTypes() { return allowedSessionPermissionTypes; } }
19,131
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectService; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyTransformationException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; /** * This class contains EventHandler methods to manage access keys of * MCRObjects and MCRDerivates. * */ public class MCRAccessKeyEventHandler extends MCREventHandlerBase { private static final Logger LOGGER = LogManager.getLogger(); /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase#handleObjectCreated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectCreated(MCREvent evt, MCRObject obj) { handleBaseCreated(obj); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase#handleObjectUpdated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectUpdated(MCREvent evt, MCRObject obj) { handleBaseUpdated(obj); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase#handleObjectDeleted(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectDeleted(MCREvent evt, MCRObject obj) { handleBaseDeleted(obj); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase#handleDerivateCreated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRDerivate) */ @Override protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) { handleBaseCreated(der); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase#handleDerivateUpdated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRDerivate) */ @Override protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) { handleBaseUpdated(der); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase#handleDerivateDeleted(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRDerivate) */ @Override protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) { handleBaseDeleted(der); } /** * Add all {@link MCRAccessKey} from servflags to object. * * Then the servlag will be deleted. * @param obj the {@link MCRBase} */ private void handleBaseCreated(final MCRBase obj) { final MCRObjectService service = obj.getService(); try { final List<MCRAccessKey> accessKeys = MCRAccessKeyTransformer .accessKeysFromElement(obj.getId(), service.createXML()); if (accessKeys.size() > 0) { MCRAccessKeyManager.addAccessKeys(obj.getId(), accessKeys); } } catch (MCRAccessKeyTransformationException e) { LOGGER.warn("Access keys can not be handled."); } service.removeFlags(MCRAccessKeyTransformer.ACCESS_KEY_TYPE); } /** * Removes {@link MCRAccessKey} string for servflags. * * {@link MCRAccessKey} string will not handled * @param obj the {@link MCRBase} */ private void handleBaseUpdated(final MCRBase obj) { final MCRObjectService service = obj.getService(); service.removeFlags(MCRAccessKeyTransformer.ACCESS_KEY_TYPE); } /** * Deletes all {@link MCRAccessKey} for given {@link MCRBase} * * @param obj the {@link MCRBase} */ private void handleBaseDeleted(final MCRBase obj) { MCRAccessKeyManager.clearAccessKeys(obj.getId()); } }
4,799
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import static java.nio.charset.StandardCharsets.UTF_8; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessCacheHelper; import org.mycore.access.MCRAccessManager; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRUtils; import org.mycore.common.config.MCRConfiguration2; import org.mycore.crypt.MCRCipher; import org.mycore.crypt.MCRCipherManager; import org.mycore.crypt.MCRCryptKeyFileNotFoundException; import org.mycore.crypt.MCRCryptKeyNoPermissionException; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyCollisionException; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyException; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyInvalidSecretException; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyInvalidTypeException; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyNotFoundException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; import jakarta.persistence.EntityManager; /** * Methods to manage {@link MCRAccessKey}. */ public final class MCRAccessKeyManager { private static final Logger LOGGER = LogManager.getLogger(); private static final String SECRET_STORAGE_MODE_PROP_PREFX = "MCR.ACL.AccessKey.Secret.Storage.Mode"; private static final String SECRET_STORAGE_MODE = MCRConfiguration2 .getStringOrThrow(SECRET_STORAGE_MODE_PROP_PREFX); private static final int HASHING_ITERATIONS = MCRConfiguration2 .getInt(SECRET_STORAGE_MODE_PROP_PREFX + ".Hash.Iterations").orElse(1000); /** * Returns all access keys for given {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} * @return {@link MCRAccessKey} list */ public static synchronized List<MCRAccessKey> listAccessKeys(final MCRObjectID objectId) { final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); final List<MCRAccessKey> accessKeys = em.createNamedQuery("MCRAccessKey.getWithObjectId", MCRAccessKey.class) .setParameter("objectId", objectId) .getResultList(); for (MCRAccessKey accessKey : accessKeys) { em.detach(accessKey); } return accessKeys; } /** * Checks the quality of the permission. * * @param type permission type * @return true if valid or false */ public static boolean isValidType(final String type) { return (MCRAccessManager.PERMISSION_READ.equals(type) || MCRAccessManager.PERMISSION_WRITE.equals(type)); } /** * Checks the quality of the secret. * * @param secret the secret * @return true if valid or false */ public static boolean isValidSecret(final String secret) { return secret.length() > 0; } /** * Encrypts secret and uses {@link MCRObjectID} as salt. * * @param secret the secret * @param objectId the {@link MCRObjectID} * @return hashed secret * @throws MCRException if encryption fails */ public static String hashSecret(final String secret, final MCRObjectID objectId) throws MCRException { switch (SECRET_STORAGE_MODE) { case "plain" -> { return secret; } case "crypt" -> { try { final MCRCipher cipher = MCRCipherManager.getCipher("accesskey"); return cipher.encrypt(objectId.toString() + secret); } catch (MCRCryptKeyFileNotFoundException | MCRCryptKeyNoPermissionException e) { throw new MCRException(e); } } case "hash" -> { try { return MCRUtils.asSHA256String(HASHING_ITERATIONS, objectId.toString().getBytes(UTF_8), secret); } catch (NoSuchAlgorithmException e) { throw new MCRException("Cannot hash secret.", e); } } default -> throw new MCRException("Please configure a valid storage mode for secret."); } } /** * Creates a {@link MCRAccessKey} for given {@link MCRObjectID}. * Hashed the secret * * @param objectId the {@link MCRObjectID} * @param accessKey access key with secret * @throws MCRException key is not valid */ public static synchronized void createAccessKey(final MCRObjectID objectId, final MCRAccessKey accessKey) throws MCRException { final String secret = accessKey.getSecret(); if (secret == null || !isValidSecret(secret)) { throw new MCRAccessKeyInvalidSecretException("Incorrect secret."); } accessKey.setSecret(hashSecret(secret, objectId)); accessKey.setCreatedBy(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID()); accessKey.setCreated(new Date()); accessKey.setLastModifiedBy(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID()); accessKey.setLastModified(new Date()); if (accessKey.getIsActive() == null) { accessKey.setIsActive(true); } addAccessKey(objectId, accessKey); } /** * Adds a {@link MCRAccessKey} for given {@link MCRObjectID}. * Checks for a {@link MCRAccessKey} collision * * @param objectId the {@link MCRObjectID} * @param accessKey access key with hashed secret * @throws MCRException key is not valid */ private static synchronized void addAccessKey(final MCRObjectID objectId, final MCRAccessKey accessKey) throws MCRException { final String secret = accessKey.getSecret(); if (secret == null) { LOGGER.debug("Incorrect secret."); throw new MCRAccessKeyInvalidSecretException("Incorrect secret."); } final String type = accessKey.getType(); if (type == null || !isValidType(type)) { LOGGER.debug("Invalid permission type."); throw new MCRAccessKeyInvalidTypeException("Invalid permission type."); } if (getAccessKeyWithSecret(objectId, secret) == null) { accessKey.setId(0); //prevent collision accessKey.setObjectId(objectId); final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); em.persist(accessKey); em.detach(accessKey); } else { LOGGER.debug("Key collision."); throw new MCRAccessKeyCollisionException("Key collision."); } } /** * Adds {@link MCRAccessKey} list for given {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} * @param accessKeys the {@link MCRAccessKey} list * @throws MCRAccessKeyException key is not valid */ public static synchronized void addAccessKeys(final MCRObjectID objectId, final List<MCRAccessKey> accessKeys) throws MCRAccessKeyException { for (MCRAccessKey accessKey : accessKeys) { //Transaktion addAccessKey(objectId, accessKey); } } /** * Deletes all {@link MCRAccessKey}. */ public static void clearAccessKeys() { MCREntityManagerProvider.getCurrentEntityManager() .createNamedQuery("MCRAccessKey.clear") .executeUpdate(); } /** * Deletes the all {@link MCRAccessKey} for given {@link MCRObjectID}. * * @param objectId the {@link MCRObjectID} */ public static void clearAccessKeys(final MCRObjectID objectId) { MCREntityManagerProvider.getCurrentEntityManager() .createNamedQuery("MCRAccessKey.clearWithObjectId") .setParameter("objectId", objectId) .executeUpdate(); } /** * Removes {@link MCRAccessKey} for given {@link MCRObjectID} and secret. * * @param objectId the {@link MCRObjectID} * @param secret the secret */ public static synchronized void removeAccessKey(final MCRObjectID objectId, final String secret) throws MCRAccessKeyNotFoundException { final MCRAccessKey accessKey = getAccessKeyWithSecret(objectId, secret); if (accessKey == null) { LOGGER.debug("Key does not exist."); throw new MCRAccessKeyNotFoundException("Key does not exist."); } else { MCRAccessCacheHelper.clearAllPermissionCaches(objectId.toString()); final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); em.remove(em.contains(accessKey) ? accessKey : em.merge(accessKey)); } } /** * Updates {@link MCRAccessKey} * * @param objectId the {@link MCRObjectID} * @param secret the access key secret * @param updatedAccessKey access key * @throws MCRException if update fails */ public static synchronized void updateAccessKey(final MCRObjectID objectId, final String secret, final MCRAccessKey updatedAccessKey) throws MCRException { final MCRAccessKey accessKey = getAccessKeyWithSecret(objectId, secret); if (accessKey != null) { final String type = updatedAccessKey.getType(); if (type != null && !accessKey.getType().equals(type)) { if (isValidType(type)) { MCRAccessCacheHelper.clearAllPermissionCaches(objectId.toString()); accessKey.setType(type); } else { LOGGER.debug("Unkown Type."); throw new MCRAccessKeyInvalidTypeException("Unknown permission type."); } } final Boolean isActive = updatedAccessKey.getIsActive(); if (isActive != null) { MCRAccessCacheHelper.clearAllPermissionCaches(objectId.toString()); accessKey.setIsActive(isActive); } final Date expiration = updatedAccessKey.getExpiration(); if (expiration != null) { MCRAccessCacheHelper.clearAllPermissionCaches(objectId.toString()); accessKey.setExpiration(expiration); } final String comment = updatedAccessKey.getComment(); if (comment != null) { accessKey.setComment(comment); } accessKey.setLastModifiedBy(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID()); accessKey.setLastModified(new Date()); final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); em.merge(accessKey); } else { LOGGER.debug("Key does not exist."); throw new MCRAccessKeyNotFoundException("Key does not exist."); } } /** * Return the {@link MCRAccessKey} for given {@link MCRObjectID} and secret. * * @param objectId the {@link MCRObjectID} * @param secret the hashed secret * @return the {@link MCRAccessKey} */ public static synchronized MCRAccessKey getAccessKeyWithSecret(final MCRObjectID objectId, final String secret) { final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); final MCRAccessKey accessKey = em.createNamedQuery("MCRAccessKey.getWithSecret", MCRAccessKey.class) .setParameter("objectId", objectId) .setParameter("secret", secret) .getResultList() .stream() .findFirst() .orElse(null); if (accessKey != null) { em.detach(accessKey); } return accessKey; } /** * Return the access keys for given {@link MCRObjectID} and type. * * @param objectId the {@link MCRObjectID} * @param type the type * @return {@link MCRAccessKey} list */ public static synchronized List<MCRAccessKey> listAccessKeysWithType(final MCRObjectID objectId, final String type) { final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); final List<MCRAccessKey> accessKeys = em.createNamedQuery("MCRAccessKey.getWithType", MCRAccessKey.class) .setParameter("objectId", objectId) .setParameter("type", type) .getResultList(); for (MCRAccessKey accessKey : accessKeys) { em.detach(accessKey); } return accessKeys; } }
13,397
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyURIResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyURIResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import org.jdom2.transform.JDOMSource; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyTransformationException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; /** * Returns a JSON string with all {@link MCRAccessKey} for an given {@link MCRObjectID}. * <p>Syntax:</p> * <ul> * <li><code>accesskeys:{objectId}</code> to resolve a access keys as json string and count as attribute</li> * </ul> */ public class MCRAccessKeyURIResolver implements URIResolver { /* (non-Javadoc) * @see javax.xml.transform.URIResolver#resolve(java.lang.String, java.lang.String) */ @Override public Source resolve(String href, String base) throws MCRAccessKeyTransformationException { final MCRObjectID objectId = MCRObjectID.getInstance(href.substring(href.indexOf(":") + 1)); final List<MCRAccessKey> accessKeys = MCRAccessKeyManager.listAccessKeys(objectId); return new JDOMSource(MCRAccessKeyTransformer.elementFromAccessKeys(accessKeys)); } }
1,919
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAccessKeyTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/MCRAccessKeyTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jdom2.Element; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyTransformationException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Methods for transforming {@link MCRAccessKey} between JSON. */ public class MCRAccessKeyTransformer { /** * Name of service element. */ private static final String ROOT_SERVICE = "service"; /** * Name of servflags element. */ private static final String ROOT_SERV_FLAGS = "servflags"; /** * Name of servflag element. */ private static final String SERV_FLAG = "servflag"; /** * Name of accesskeys element. */ public static final String ACCESS_KEY_TYPE = "accesskeys"; /** * Transforms JSON to a {@link MCRAccessKey}. * * @param json the json * @return the {@link MCRAccessKey} * @throws MCRAccessKeyTransformationException if the transformation fails */ public static MCRAccessKey accessKeyFromJson(final String json) throws MCRAccessKeyTransformationException { final ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.readValue(json, MCRAccessKey.class); } catch (JsonProcessingException e) { throw new MCRAccessKeyTransformationException("Cannot transform JSON."); } } /** * Transforms JSON to {@link MCRAccessKey} list. * * @param json the json * @return the {@link MCRAccessKey} list * @throws MCRAccessKeyTransformationException if the transformation fails */ public static List<MCRAccessKey> accessKeysFromJson(final String json) throws MCRAccessKeyTransformationException { final ObjectMapper objectMapper = new ObjectMapper(); try { return Arrays.asList(objectMapper.readValue(json, MCRAccessKey[].class)); } catch (JsonProcessingException e) { throw new MCRAccessKeyTransformationException("Invalid JSON."); } } /** * Transforms a {@link MCRAccessKey} to JSON. * * @param accessKey the {@link MCRAccessKey} * @return access key as json string * @throws MCRAccessKeyTransformationException if the transformation fails */ public static String jsonFromAccessKey(final MCRAccessKey accessKey) throws MCRAccessKeyTransformationException { final ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(accessKey); } catch (JsonProcessingException e) { throw new MCRAccessKeyTransformationException("Access key could not be converted to JSON."); } } /** * Transforms a {@link MCRAccessKey} list to JSON. * * @param accessKeys the {@link MCRAccessKey} list * @return access keys as json array string * @throws MCRAccessKeyTransformationException if the transformation fails */ public static String jsonFromAccessKeys(final List<MCRAccessKey> accessKeys) throws MCRAccessKeyTransformationException { final ObjectMapper objectMapper = new ObjectMapper(); try { return objectMapper.writeValueAsString(accessKeys); } catch (JsonProcessingException e) { throw new MCRAccessKeyTransformationException("Access keys could not be converted to JSON."); } } /** * Transforms service element to {@link MCRAccessKey} list * * @param objectId the linked {@link MCRObjectID} * @param element the service element * @return the {@link MCRAccessKey} list * @throws MCRAccessKeyTransformationException if the transformation fails */ public static List<MCRAccessKey> accessKeysFromElement(MCRObjectID objectId, Element element) throws MCRAccessKeyTransformationException { if (ROOT_SERVICE.equals(element.getName())) { Element servFlagsRoot = element.getChild(ROOT_SERV_FLAGS); if (servFlagsRoot != null) { final List<Element> servFlags = servFlagsRoot.getChildren(SERV_FLAG); for (Element servFlag : servFlags) { if (ACCESS_KEY_TYPE.equals(servFlag.getAttributeValue("type"))) { return accessKeysFromAccessKeyElement(objectId, servFlag); } } } } else if (SERV_FLAG.equals(element.getName()) && ACCESS_KEY_TYPE.equals(element.getAttributeValue("type"))) { return accessKeysFromAccessKeyElement(objectId, element); } else if (ACCESS_KEY_TYPE.equals(element.getName())) { return accessKeysFromAccessKeyElement(objectId, element); } return new ArrayList<>(); } /** * Transforms servflag element to {@link MCRAccessKey} list * * @param objectId the linked {@link MCRObjectID} * @param element servflag element {@link org.mycore.datamodel.metadata.MCRObjectService} * @return the {@link MCRAccessKey} list * @throws MCRAccessKeyTransformationException if the transformation fails */ private static List<MCRAccessKey> accessKeysFromAccessKeyElement(MCRObjectID objectId, Element element) throws MCRAccessKeyTransformationException { final String json = element.getText(); final List<MCRAccessKey> accessKeyList = accessKeysFromJson(json); for (MCRAccessKey accessKey : accessKeyList) { accessKey.setObjectId(objectId); } return accessKeyList; } /** * Transforms {@link MCRAccessKey} list to a element * * @param accessKeys the {@link MCRAccessKey} list * @return the accesskeys element with access key list as json string as content * @throws MCRAccessKeyTransformationException if the transformation fails */ public static Element elementFromAccessKeys(final List<MCRAccessKey> accessKeys) throws MCRAccessKeyTransformationException { final String jsonString = jsonFromAccessKeys(accessKeys); final Element element = elementFromAccessKeysJson(jsonString); element.setAttribute("count", Integer.toString(accessKeys.size())); return element; } /** * Transforms JSON of {@link MCRAccessKey} list to a element * * @param json the JSON * @return element with accesskeys name */ private static Element elementFromAccessKeysJson(final String json) { final Element element = new Element(ACCESS_KEY_TYPE); element.setText(json); return element; } }
7,581
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestDerivateAccessKeys.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/restapi/v2/MCRRestDerivateAccessKeys.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey.restapi.v2; import static org.mycore.mcr.acl.accesskey.restapi.v2.MCRRestAccessKeyHelper.PARAM_SECRET; import static org.mycore.mcr.acl.accesskey.restapi.v2.MCRRestAccessKeyHelper.QUERY_PARAM_SECRET_ENCODING; import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_DERID; import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_MCRID; import static org.mycore.restapi.v2.MCRRestUtils.TAG_MYCORE_DERIVATE; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; import org.mycore.restapi.annotations.MCRApiDraft; import org.mycore.restapi.annotations.MCRRequireTransaction; import org.mycore.restapi.converter.MCRObjectIDParamConverterProvider; import org.mycore.restapi.v2.MCRRestDerivates; import org.mycore.restapi.v2.access.MCRRestAPIACLPermission; import org.mycore.restapi.v2.annotation.MCRRestRequiredPermission; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.headers.Header; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; @MCRApiDraft("MCRAccessKey") @Path("/objects/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}/accesskeys") @Tag(name = TAG_MYCORE_DERIVATE) public class MCRRestDerivateAccessKeys { @Context UriInfo uriInfo; @Parameter(example = "mir_mods_00004711") @PathParam(PARAM_MCRID) MCRObjectID mcrId; @GET @Operation( summary = "Lists all access keys for a derivate", responses = { @ApiResponse(responseCode = "200", description = "List of access keys attached to this derivate", content = { @Content(mediaType = MediaType.APPLICATION_JSON, array = @ArraySchema(schema = @Schema(implementation = MCRAccessKey.class))) }), @ApiResponse(responseCode = "" + MCRObjectIDParamConverterProvider.CODE_INVALID, // 400 description = MCRObjectIDParamConverterProvider.MSG_INVALID, content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "401", description = "You do not have create permission and need to authenticate first", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "404", description = "Derivate or access key does not exist", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), }) @Produces(MediaType.APPLICATION_JSON) @MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE) public Response listAccessKeysForDerivate(@PathParam(PARAM_DERID) final MCRObjectID derivateId, @DefaultValue("0") @QueryParam("offset") final int offset, @DefaultValue("128") @QueryParam("limit") final int limit) { MCRRestDerivates.validateDerivateRelation(mcrId, derivateId); return MCRRestAccessKeyHelper.doListAccessKeys(derivateId, offset, limit); } @GET @Path("/{" + PARAM_SECRET + "}") @Operation( summary = "Gets access key for a derivate", responses = { @ApiResponse(responseCode = "200", description = "Information about a specific access key", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = MCRAccessKey.class))), @ApiResponse(responseCode = "" + MCRObjectIDParamConverterProvider.CODE_INVALID, // 400 description = MCRObjectIDParamConverterProvider.MSG_INVALID, content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "401", description = "You do not have create permission and need to authenticate first", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "404", description = "Derivate or access key does not exist", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), }) @Produces(MediaType.APPLICATION_JSON) @MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE) public Response getAccessKeyFromDerivate(@PathParam(PARAM_DERID) final MCRObjectID derivateId, @PathParam(PARAM_SECRET) final String secret, @QueryParam(QUERY_PARAM_SECRET_ENCODING) final String secretEncoding) { MCRRestDerivates.validateDerivateRelation(mcrId, derivateId); return MCRRestAccessKeyHelper.doGetAccessKey(derivateId, secret, secretEncoding); } @POST @Operation( summary = "Creates an access key for a derivate", responses = { @ApiResponse(responseCode = "201", description = "Access key was successfully created", headers = @Header(name = HttpHeaders.LOCATION, schema = @Schema(type = "string", format = "uri"), description = "Location of the new access keyD")), @ApiResponse(responseCode = "400", description = "Invalid ID or invalid access key", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "401", description = "You do not have create permission and need to authenticate first", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "404", description = "Derivate does not exist", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), }) @RequestBody(required = true, content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = MCRAccessKey.class))) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE) @MCRRequireTransaction public Response createAccessKeyForDerivate(@PathParam(PARAM_DERID) final MCRObjectID derivateId, final String accessKeyJson) { MCRRestDerivates.validateDerivateRelation(mcrId, derivateId); return MCRRestAccessKeyHelper.doCreateAccessKey(derivateId, accessKeyJson, uriInfo); } @PUT @Path("/{" + PARAM_SECRET + "}") @Operation( summary = "Updates an access key for a derivate", responses = { @ApiResponse(responseCode = "204", description = "Access key was successfully updated"), @ApiResponse(responseCode = "400", description = "Invalid ID or invalid access key", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "401", description = "You do not have create permission and need to authenticate first", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "404", description = "Derivate or access key does not exist", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), }) @RequestBody(required = true, content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(implementation = MCRAccessKey.class))) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE) @MCRRequireTransaction public Response updateAccessKeyFromDerivate(@PathParam(PARAM_DERID) final MCRObjectID derivateId, @PathParam(PARAM_SECRET) final String encodedSecret, final String accessKeyJson, @QueryParam(QUERY_PARAM_SECRET_ENCODING) final String secretEncoding) { MCRRestDerivates.validateDerivateRelation(mcrId, derivateId); return MCRRestAccessKeyHelper.doUpdateAccessKey(derivateId, encodedSecret, accessKeyJson, secretEncoding); } @DELETE @Path("/{" + PARAM_SECRET + "}") @Operation( summary = "Deletes an access key from a derivate", responses = { @ApiResponse(responseCode = "204", description = "Access key was successfully deleted"), @ApiResponse(responseCode = "" + MCRObjectIDParamConverterProvider.CODE_INVALID, // 400 description = MCRObjectIDParamConverterProvider.MSG_INVALID, content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "401", description = "You do not have create permission and need to authenticate first", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), @ApiResponse(responseCode = "404", description = "Derivate or access key does not exist", content = { @Content(mediaType = MediaType.APPLICATION_JSON) }), }) @Produces(MediaType.APPLICATION_JSON) @MCRRestRequiredPermission(MCRRestAPIACLPermission.WRITE) @MCRRequireTransaction public Response removeAccessKeyFromDerivate(@PathParam(PARAM_DERID) final MCRObjectID derivateId, @PathParam(PARAM_SECRET) final String secret, @QueryParam(QUERY_PARAM_SECRET_ENCODING) final String secretEncoding) { MCRRestDerivates.validateDerivateRelation(mcrId, derivateId); return MCRRestAccessKeyHelper.doRemoveAccessKey(derivateId, secret, secretEncoding); } }
10,998
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRestAccessKeyHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl/src/main/java/org/mycore/mcr/acl/accesskey/restapi/v2/MCRRestAccessKeyHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mcr.acl.accesskey.restapi.v2; import static java.nio.charset.StandardCharsets.UTF_8; import java.net.URLEncoder; import java.util.Base64; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.acl.accesskey.MCRAccessKeyManager; import org.mycore.mcr.acl.accesskey.MCRAccessKeyTransformer; import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyNotFoundException; import org.mycore.mcr.acl.accesskey.model.MCRAccessKey; import org.mycore.mcr.acl.accesskey.restapi.v2.model.MCRAccessKeyInformation; import org.mycore.restapi.v2.MCRErrorResponse; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; public class MCRRestAccessKeyHelper { /** * Placeholder for the path param secret */ protected static final String PARAM_SECRET = "secret"; /** * Placeholder for the query param secret_format */ protected static final String QUERY_PARAM_SECRET_ENCODING = "secret_encoding"; private static WebApplicationException getUnknownObjectException(final MCRObjectID objectId) { return MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode()) .withMessage(objectId + " does not exist!") .withErrorCode("objectNotFound") .toException(); } protected static Response doCreateAccessKey(final MCRObjectID objectId, final String accessKeyJson, final UriInfo uriInfo) { final MCRAccessKey accessKey = MCRAccessKeyTransformer.accessKeyFromJson(accessKeyJson); if (!MCRMetadataManager.exists(objectId)) { throw getUnknownObjectException(objectId); } MCRAccessKeyManager.createAccessKey(objectId, accessKey); final String encodedSecret = URLEncoder.encode(accessKey.getSecret(), UTF_8); return Response.created(uriInfo.getAbsolutePathBuilder().path(encodedSecret).build()).build(); } protected static Response doGetAccessKey(final MCRObjectID objectId, final String secret, final String secretEncoding) { if (!MCRMetadataManager.exists(objectId)) { throw getUnknownObjectException(objectId); } MCRAccessKey accessKey = null; if (secretEncoding != null) { accessKey = MCRAccessKeyManager.getAccessKeyWithSecret(objectId, decode(secret, secretEncoding)); } else { accessKey = MCRAccessKeyManager.getAccessKeyWithSecret(objectId, secret); } if (accessKey != null) { return Response.ok(accessKey).build(); } throw new MCRAccessKeyNotFoundException("Key does not exist."); } protected static Response doListAccessKeys(final MCRObjectID objectId, final int offset, final int limit) { if (!MCRMetadataManager.exists(objectId)) { throw getUnknownObjectException(objectId); } final List<MCRAccessKey> accessKeys = MCRAccessKeyManager.listAccessKeys(objectId); final List<MCRAccessKey> accessKeysResult = accessKeys.stream() .skip(offset) .limit(limit) .collect(Collectors.toList()); return Response.ok(new MCRAccessKeyInformation(accessKeysResult, accessKeys.size())).build(); } protected static Response doRemoveAccessKey(final MCRObjectID objectId, final String secret, final String secretEncoding) { if (!MCRMetadataManager.exists(objectId)) { throw getUnknownObjectException(objectId); } if (secretEncoding != null) { MCRAccessKeyManager.removeAccessKey(objectId, decode(secret, secretEncoding)); } else { MCRAccessKeyManager.removeAccessKey(objectId, secret); } return Response.noContent().build(); } protected static Response doUpdateAccessKey(final MCRObjectID objectId, final String secret, final String accessKeyJson, final String secretEncoding) { if (!MCRMetadataManager.exists(objectId)) { throw getUnknownObjectException(objectId); } final MCRAccessKey accessKey = MCRAccessKeyTransformer.accessKeyFromJson(accessKeyJson); if (secretEncoding != null) { MCRAccessKeyManager.updateAccessKey(objectId, decode(secret, secretEncoding), accessKey); } else { MCRAccessKeyManager.updateAccessKey(objectId, secret, accessKey); } return Response.noContent().build(); } private static String decode(final String text, final String encoding) { if (Objects.equals(encoding, "base64url")) { return new String(Base64.getUrlDecoder().decode(text.getBytes(UTF_8)), UTF_8); } return text; } }
5,604
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z