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
MCRMinDecimalValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMinDecimalValidator.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.frontend.xeditor.validation; /** * Validates input to be a decimal number and not less than a given minimum value. * The number format is specified by a given locale ID. * Example: &lt;xed:validate type="decimal" locale="en" min="1,000.00"... /&gt; * * * @author Frank Lützenkirchen */ public class MCRMinDecimalValidator extends MCRDecimalValidator { private static final String ATTR_MIN = "min"; private double min; @Override public boolean hasRequiredAttributes() { return super.hasRequiredAttributes() && hasAttributeValue(ATTR_MIN); } @Override public void configure() { super.configure(); min = converter.string2double(getAttributeValue(ATTR_MIN)); } @Override protected boolean isValid(String value) { Double d = converter.string2double(value); if (d == null) { return false; } else { return min <= d; } } }
1,701
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMinLengthValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMinLengthValidator.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.frontend.xeditor.validation; /** * Validates text values to have a given minimum length * Example: &lt;xed:validate minLength="10" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRMinLengthValidator extends MCRValidator { private static final String ATTR_MIN_LENGTH = "minLength"; private int minLength; @Override public boolean hasRequiredAttributes() { return hasAttributeValue(ATTR_MIN_LENGTH); } @Override public void configure() { minLength = Integer.parseInt(getAttributeValue(ATTR_MIN_LENGTH)); } @Override protected boolean isValid(String value) { return minLength <= value.length(); } }
1,437
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDateValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRDateValidator.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.frontend.xeditor.validation; /** * Validates date values specified by one or more SimpleDateFormat patterns separated by ";". * Example: &lt;xed:validate type="date" format="yyyy-MM-dd;dd.MM.yyyy" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRDateValidator extends MCRValidator { private static final String TYPE_DATE = "date"; private static final String ATTR_TYPE = "type"; private static final String ATTR_FORMAT = "format"; /** The converter used to convert strings to dates */ protected MCRDateConverter converter; @Override public boolean hasRequiredAttributes() { return TYPE_DATE.equals(getAttributeValue(ATTR_TYPE)) && hasAttributeValue(ATTR_FORMAT); } @Override public void configure() { String format = getAttributeValue(ATTR_FORMAT); converter = new MCRDateConverter(format); } @Override protected boolean isValid(String value) { return (converter.string2date(value) != null); } }
1,760
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDecimalConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRDecimalConverter.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.frontend.xeditor.validation; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; /** * Helper for decimal validators to convert string input into a decimal value for a given locale. * * @author Frank Lützenkirchen */ public class MCRDecimalConverter { private Locale locale = Locale.getDefault(); public MCRDecimalConverter(String localeID) { this.locale = Locale.forLanguageTag(localeID); } /** * Converts a given text string to a decimal number, using the given locale. * * @param value the text string * @return null, if the text contains illegal chars or can not be parsed */ public Double string2double(String value) { if (hasIllegalCharacters(value)) { return null; } NumberFormat nf = NumberFormat.getNumberInstance(locale); if (nf instanceof DecimalFormat decimalFormat && hasMultipleDecimalSeparators(value, decimalFormat)) { return null; } try { return nf.parse(value).doubleValue(); } catch (ParseException e) { return null; } } private boolean hasMultipleDecimalSeparators(String string, DecimalFormat df) { DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); String patternNonDecimalSeparators = "[^" + dfs.getDecimalSeparator() + "]"; String decimalSeparatorsLeftOver = string.replaceAll(patternNonDecimalSeparators, ""); return (decimalSeparatorsLeftOver.length() > 1); } private boolean hasIllegalCharacters(String string) { return !string.matches("[0-9,.]+"); } }
2,482
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRExternalValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRExternalValidator.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.frontend.xeditor.validation; import java.lang.reflect.Method; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.xml.MCRXPathBuilder; import org.mycore.frontend.xeditor.MCRBinding; /** * Validates edited xml using an external method. * The method must be "public static boolean ..." * and should accept a String, Element, Attribute or Object as argument. * * Example: &lt;xed:validate class="foo.bar.MyValidator" method="validateISBN" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRExternalValidator extends MCRValidator { private static final String ATTR_METHOD = "method"; private static final String ATTR_CLASS = "class"; private String className; private String methodName; @Override public boolean hasRequiredAttributes() { return hasAttributeValue(ATTR_CLASS) && hasAttributeValue(ATTR_METHOD); } @Override public void configure() { className = getAttributeValue(ATTR_CLASS); methodName = getAttributeValue(ATTR_METHOD); } @Override public boolean validateBinding(MCRValidationResults results, MCRBinding binding) { boolean isValid = true; // all nodes must validate for (Object node : binding.getBoundNodes()) { String absPath = MCRXPathBuilder.buildXPath(node); if (results.hasError(absPath)) { continue; } Boolean result = isValid(node); if (result == null) { continue; } results.mark(absPath, result, this); isValid = isValid && result; } return isValid; } protected Boolean isValid(Object node) { Method method = findMethod(node.getClass()); if (method != null) { return invokeMethod(method, node); } else { method = findMethod(String.class); if (method != null) { String value = MCRBinding.getValue(node); return value.isEmpty() ? null : invokeMethod(method, value); } else { throw new MCRConfigurationException( "Method configured for external validation not found: " + className + "#" + methodName); } } } private Method findMethod(Class<?> argType) { try { Class<?> clazz = ClassUtils.getClass(className); Class<?>[] argTypes = { argType }; return MethodUtils.getMatchingAccessibleMethod(clazz, methodName, argTypes); } catch (ClassNotFoundException ex) { throw new MCRConfigurationException("class configured for external validation not found: " + className); } } private Boolean invokeMethod(Method method, Object param) { try { Object[] params = { param }; Object result = method.invoke(null, params); return (Boolean) result; } catch (Exception ex) { throw new MCRException(ex); } } }
3,927
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMaxLengthValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMaxLengthValidator.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.frontend.xeditor.validation; /** * Validates text values to have a given maximum length * Example: &lt;xed:validate maxLength="250" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRMaxLengthValidator extends MCRValidator { private static final String ATTR_MAX_LENGTH = "maxLength"; private int maxLength; @Override public boolean hasRequiredAttributes() { return hasAttributeValue(ATTR_MAX_LENGTH); } @Override public void configure() { maxLength = Integer.parseInt(getAttributeValue(ATTR_MAX_LENGTH)); } @Override protected boolean isValid(String value) { return value.length() <= maxLength; } }
1,438
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMaxStringValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMaxStringValidator.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.frontend.xeditor.validation; /** * Validates text values to be "below" (in java.lang.String#compare order) a given maximum. * Example: &lt;xed:validate type="string" max="ZZZ" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRMaxStringValidator extends MCRValidator { private static final String ATTR_MAX = "max"; private static final String ATTR_TYPE = "type"; private static final String TYPE_STRING = "string"; private String max; @Override public boolean hasRequiredAttributes() { return TYPE_STRING.equals(getAttributeValue(ATTR_TYPE)) && hasAttributeValue(ATTR_MAX); } @Override public void configure() { max = getAttributeValue(ATTR_MAX); } @Override protected boolean isValid(String value) { return max.compareTo(value) >= 0; } }
1,590
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDecimalValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRDecimalValidator.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.frontend.xeditor.validation; /** * Validates input to be a decimal number. The number format is specified by a given locale ID. * Example: &lt;xed:validate type="decimal" locale="de" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRDecimalValidator extends MCRValidator { private static final String ATTR_LOCALE = "locale"; private static final String ATTR_TYPE = "type"; private static final String TYPE_DECIMAL = "decimal"; protected MCRDecimalConverter converter; @Override public boolean hasRequiredAttributes() { return TYPE_DECIMAL.equals(getAttributeValue(ATTR_TYPE)) && hasAttributeValue(ATTR_LOCALE); } @Override public void configure() { String locale = getAttributeValue(ATTR_LOCALE); converter = new MCRDecimalConverter(locale); } @Override protected boolean isValid(String value) { return converter.string2double(value) != null; } }
1,706
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRValidationResults.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRValidationResults.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.frontend.xeditor.validation; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.mycore.common.config.MCRConfiguration2; public class MCRValidationResults { static final String MARKER_DEFAULT; static final String MARKER_SUCCESS; static final String MARKER_ERROR; static { String prefix = "MCR.XEditor.Validation.Marker."; MARKER_DEFAULT = MCRConfiguration2.getString(prefix + "default").orElse(""); MARKER_SUCCESS = MCRConfiguration2.getString(prefix + "success").orElse("mcr-valid"); MARKER_ERROR = MCRConfiguration2.getString(prefix + "error").orElse("mcr-invalid"); } private Map<String, String> xPath2Marker = new HashMap<>(); private LinkedHashMap<String, MCRValidator> xPath2FailedRule = new LinkedHashMap<>(); private boolean isValid = true; public boolean hasError(String xPath) { return MARKER_ERROR.equals(xPath2Marker.get(xPath)); } public void mark(String xPath, boolean isValid, MCRValidator failedRule) { if (hasError(xPath)) { return; } if (isValid) { xPath2Marker.put(xPath, MARKER_SUCCESS); } else { xPath2Marker.put(xPath, MARKER_ERROR); xPath2FailedRule.put(xPath, failedRule); this.isValid = false; } } public String getValidationMarker(String xPath) { return xPath2Marker.getOrDefault(xPath, MARKER_DEFAULT); } public MCRValidator getFailedRule(String xPath) { return xPath2FailedRule.get(xPath); } public Collection<MCRValidator> getFailedRules() { return xPath2FailedRule.values(); } public boolean isValid() { return isValid; } }
2,537
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMaxDateValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMaxDateValidator.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.frontend.xeditor.validation; import java.util.Date; /** * Validates date values against a maximum date. * Date values are specified by one or more SimpleDateFormat patterns separated by ";". * Example: &lt;xed:validate type="date" format="yyyy-MM" max="2017-12" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRMaxDateValidator extends MCRDateValidator { private static final String ATTR_MAX = "max"; private Date maxDate; @Override public boolean hasRequiredAttributes() { return super.hasRequiredAttributes() && hasAttributeValue(ATTR_MAX); } @Override public void configure() { super.configure(); String max = getAttributeValue(ATTR_MAX); this.maxDate = converter.string2date(max); } @Override protected boolean isValid(String value) { Date date = converter.string2date(value); if (date == null) { return false; } else { return maxDate.after(date) || maxDate.equals(date); } } }
1,791
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMatchesNotValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMatchesNotValidator.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.frontend.xeditor.validation; /** * Validates input to not match a specified java.util.regex pattern. * Example: &lt;xed:validate xpath="/user/@name" matches-not="ldap[0-9]+" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRMatchesNotValidator extends MCRValidator { private static final String ATTR_MATCHES_NOT = "matches-not"; private String pattern; @Override public boolean hasRequiredAttributes() { return hasAttributeValue(ATTR_MATCHES_NOT); } @Override public void configure() { this.pattern = getAttributeValue(ATTR_MATCHES_NOT); } @Override protected boolean isValid(String value) { return !value.matches(pattern); } }
1,465
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXEditorValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRXEditorValidator.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.frontend.xeditor.validation; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jaxen.JaxenException; import org.mycore.frontend.xeditor.MCRBinding; import org.mycore.frontend.xeditor.MCREditorSession; import org.w3c.dom.Attr; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * @author Frank Lützenkirchen */ public class MCRXEditorValidator { public static final String XED_VALIDATION_FAILED = "xed-validation-failed"; public static final String XED_VALIDATION_MARKER = "xed-validation-marker"; private List<MCRValidator> validationRules = new ArrayList<>(); private MCRValidationResults results = new MCRValidationResults(); private MCREditorSession session; public MCRXEditorValidator(MCREditorSession session) { this.session = session; } public void addRule(String baseXPath, Node ruleElement) { NamedNodeMap attributes = ruleElement.getAttributes(); Attr enableReplacementNode = (Attr) attributes.getNamedItem("enable-replacements"); if (enableReplacementNode != null && enableReplacementNode.getValue().equals("true")) { for (int i = 0, n = attributes.getLength(); i < n; i++) { Attr attribute = (Attr) attributes.item(i); String oldValue = attribute.getNodeValue(); String newValue = session.replaceParameters(oldValue); attribute.setValue(newValue); } } addIfConfigured(new MCRRequiredValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMinLengthValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMaxLengthValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMatchesValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMatchesNotValidator(), baseXPath, ruleElement); addIfConfigured(new MCRXPathTestValidator(), baseXPath, ruleElement); addIfConfigured(new MCRDateValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMinDateValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMaxDateValidator(), baseXPath, ruleElement); addIfConfigured(new MCRIntegerValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMinIntegerValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMaxIntegerValidator(), baseXPath, ruleElement); addIfConfigured(new MCRDecimalValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMinDecimalValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMaxDecimalValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMinStringValidator(), baseXPath, ruleElement); addIfConfigured(new MCRMaxStringValidator(), baseXPath, ruleElement); addIfConfigured(new MCRExternalValidator(), baseXPath, ruleElement); } private void addIfConfigured(MCRValidator validator, String baseXPath, Node ruleElement) { validator.init(baseXPath, ruleElement); if (validator.hasRequiredAttributes()) { validationRules.add(validator); } } public void clearRules() { validationRules.clear(); } public boolean isValid() throws JaxenException { MCRBinding root = session.getRootBinding(); for (MCRValidator rule : validationRules) { rule.validate(results, root); } session.getVariables().put(XED_VALIDATION_FAILED, String.valueOf(!results.isValid())); return results.isValid(); } public boolean hasError(MCRBinding binding) { return results.hasError(binding.getAbsoluteXPath()); } public MCRValidator getFailedRule(MCRBinding binding) { return results.getFailedRule(binding.getAbsoluteXPath()); } public void setValidationMarker(MCRBinding binding) { String xPath = binding.getAbsoluteXPath(); String marker = results.getValidationMarker(xPath); session.getVariables().put(XED_VALIDATION_MARKER, marker); } public Collection<MCRValidator> getFailedRules() { return results.getFailedRules(); } public void clearValidationResults() { results = new MCRValidationResults(); session.getVariables().remove(XED_VALIDATION_FAILED); } }
5,061
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIntegerValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRIntegerValidator.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.frontend.xeditor.validation; /** * Validates values to be integer numbers. * Example: &lt;xed:validate type="integer" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRIntegerValidator extends MCRValidator { private static final String ATTR_TYPE = "type"; private static final String TYPE_INTEGER = "integer"; @Override public boolean hasRequiredAttributes() { return TYPE_INTEGER.equals(getAttributeValue(ATTR_TYPE)); } @Override protected boolean isValid(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException ex) { return false; } } }
1,446
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRequiredValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRRequiredValidator.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.frontend.xeditor.validation; import org.mycore.common.MCRException; import org.mycore.frontend.xeditor.MCRBinding; /** * Validates input to be required. XML is valid if at least one value exists at the given XPath. * Example: &lt;xed:validate required="true" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRRequiredValidator extends MCRValidator { private static final String VALUE_TRUE = "true"; private static final String ATTR_REQUIRED = "required"; @Override public boolean hasRequiredAttributes() { return VALUE_TRUE.equals(getAttributeValue(ATTR_REQUIRED)); } @Override public boolean validateBinding(MCRValidationResults results, MCRBinding binding) { if (binding.getBoundNodes().size() == 0) { String msg = "Condition for " + this.xPath + " can not be validated, no such XML source node"; throw new MCRException(msg); } String absPath = binding.getAbsoluteXPath(); if (results.hasError(absPath)) { return true; } if (!isRelevant(binding)) { return true; } boolean isValid = false; // at least one value must exist for (Object node : binding.getBoundNodes()) { if (!MCRBinding.getValue(node).isEmpty()) { isValid = true; } } results.mark(absPath, isValid, this); return isValid; } }
2,198
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDebugTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRDebugTarget.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.frontend.xeditor.target; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCREditorSession; import org.mycore.frontend.xeditor.tracker.MCRChangeTracker; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen */ public class MCRDebugTarget implements MCREditorTarget { private static final String USE_DEBUG_PERMISSION = "use-xeditor-debug"; @Override public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String parameter) throws Exception { if (!MCRAccessManager.checkPermission(USE_DEBUG_PERMISSION)) { throw MCRAccessException.missingPrivilege("use xeditor debug target", USE_DEBUG_PERMISSION); } job.getResponse().setContentType("text/html; charset=UTF-8"); PrintWriter out = job.getResponse().getWriter(); out.println("<html><body>"); Map<String, String[]> parameters = job.getRequest().getParameterMap(); session.getSubmission().setSubmittedValues(parameters); Document result = session.getEditedXML().clone(); MCRChangeTracker tracker = session.getChangeTracker().clone(); List<Step> steps = new ArrayList<>(); for (String label = tracker.undoLastBreakpoint(result); label != null; label = tracker .undoLastBreakpoint(result)) { steps.add(0, new Step(label, result.clone())); } result = session.getEditedXML().clone(); result = MCRChangeTracker.removeChangeTracking(result); result = session.getXMLCleaner().clean(result); steps.add(new Step("After cleaning", result)); result = session.getPostProcessor().process(result); steps.add(new Step("After postprocessing", result)); for (int i = 0; i < steps.size(); i++) { if (i == steps.size() - 3) { outputParameters(parameters, out); } steps.get(i).output(out); } out.println("</body></html>"); out.close(); } private void outputParameters(Map<String, String[]> values, PrintWriter out) { out.println("<h3>Submitted parameters:</h3>"); out.println("<p><pre>"); List<String> names = new ArrayList<>(values.keySet()); Collections.sort(names); for (String name : names) { for (String value : values.get(name)) { out.println(name + " = " + value); } } out.println("</pre></p>"); } static class Step { private String label; private Document xml; private Format format = Format.getPrettyFormat().setLineSeparator("\n").setOmitDeclaration(true); Step(String label, Document xml) { this.label = label; this.xml = xml; } public void output(PrintWriter out) throws IOException { out.println("<h3>" + label + ":</h3>"); XMLOutputter outputter = new XMLOutputter(format); out.println("<p>"); Element pre = new Element("pre"); pre.addContent(outputter.outputString(xml)); outputter.output(pre, out); out.println("</p>"); } } }
4,374
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREditorTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCREditorTarget.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.frontend.xeditor.target; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCREditorSession; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen */ public interface MCREditorTarget { void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String parameter) throws Exception; }
1,134
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRemoveTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRRemoveTarget.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.frontend.xeditor.target; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCRBinding; import org.mycore.frontend.xeditor.MCREditorSession; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen */ public class MCRRemoveTarget extends MCRRepeaterControl { protected void handleRepeaterControl(ServletContext context, MCRServletJob job, MCREditorSession session, String xPath) throws Exception { MCRBinding binding = new MCRBinding(xPath, false, session.getRootBinding()); binding.removeBoundNode(0); binding.detach(); session.setBreakpoint("After handling target remove " + xPath); } }
1,442
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTargetUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRTargetUtils.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.frontend.xeditor.target; import java.util.HashMap; import java.util.Map; import org.mycore.frontend.servlets.MCRServletJob; public class MCRTargetUtils { static Map<String, String[]> getSubmittedValues(MCRServletJob job, String baseXPath) { Map<String, String[]> valuesToSet = new HashMap<>(); for (String paramName : job.getRequest().getParameterMap().keySet()) { if (!paramName.startsWith("_xed_")) { String xPath = baseXPath + "/" + paramName; String[] values = job.getRequest().getParameterValues(paramName); valuesToSet.put(xPath, values); } } return valuesToSet; } }
1,435
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSwapInsertTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRSwapInsertTarget.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.frontend.xeditor.target; import org.jaxen.JaxenException; import org.mycore.common.xml.MCRXPathBuilder; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCRBinding; import org.mycore.frontend.xeditor.MCREditorSession; import org.mycore.frontend.xeditor.MCRRepeatBinding; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen */ public abstract class MCRSwapInsertTarget extends MCRRepeaterControl { protected void handleRepeaterControl(ServletContext context, MCRServletJob job, MCREditorSession session, String param) throws Exception { handle(param, session.getRootBinding()); session.setBreakpoint("After handling target " + getClass().getName() + " " + param); } public void handle(String swapParameter, MCRBinding root) throws JaxenException { String[] tokens = swapParameter.split("\\|"); String parentXPath = tokens[0]; String posString = tokens[1]; int pos = Integer.parseInt(posString); String method = tokens[2]; String elementNameWithPredicates = swapParameter .substring(parentXPath.length() + posString.length() + method.length() + 3); MCRBinding parentBinding = new MCRBinding(parentXPath, false, root); MCRRepeatBinding repeatBinding = new MCRRepeatBinding(elementNameWithPredicates, parentBinding, method); handle(pos, repeatBinding); repeatBinding.detach(); parentBinding.detach(); } protected abstract void handle(int pos, MCRRepeatBinding repeatBinding) throws JaxenException; protected static String buildParameter(MCRRepeatBinding repeatBinding, int pos) throws JaxenException { String parentXPath = MCRXPathBuilder.buildXPath(repeatBinding.getParentElement()); String nameWithPredicates = repeatBinding.getElementNameWithPredicates(); String method = repeatBinding.getMethod(); return parentXPath + "|" + pos + "|" + method + "|" + nameWithPredicates; } }
2,783
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSubselectTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRSubselectTarget.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.frontend.xeditor.target; import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRUtils; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCRBinding; import org.mycore.frontend.xeditor.MCREditorSession; import jakarta.servlet.ServletContext; import jakarta.xml.bind.DatatypeConverter; /** * @author Frank Lützenkirchen */ public class MCRSubselectTarget implements MCREditorTarget { public static final String PARAM_SUBSELECT_SESSION = "_xed_subselect_session"; private static final Logger LOGGER = LogManager.getLogger(MCRSubselectTarget.class); public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String parameter) throws Exception { session.getSubmission().setSubmittedValues(job.getRequest().getParameterMap()); int pos = parameter.lastIndexOf(":"); String xPath = parameter.substring(0, pos); String href = decode(parameter.substring(pos + 1)); LOGGER.info("New subselect for {} using pattern {}", xPath, href); MCRBinding binding = new MCRBinding(xPath, false, session.getRootBinding()); href = binding.getXPathEvaluator().replaceXPaths(href, true); binding.detach(); session.setBreakpoint("After starting subselect at " + href + " for " + xPath); href += (href.contains("?") ? "&" : "?") + PARAM_SUBSELECT_SESSION + "=" + session.getCombinedSessionStepID(); LOGGER.info("Redirecting to subselect {}", href); job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(href)); } public static String encode(String href) { return MCRUtils.toHexString(href.getBytes(StandardCharsets.UTF_8)); } public static String decode(String href) { return new String(DatatypeConverter.parseHexBinary(href), StandardCharsets.UTF_8); } }
2,731
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSubselectReturnTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRSubselectReturnTarget.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.frontend.xeditor.target; import java.util.Map; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCRBinding; import org.mycore.frontend.xeditor.MCREditorSession; import org.mycore.frontend.xeditor.tracker.MCRChangeData; import jakarta.servlet.ServletContext; public class MCRSubselectReturnTarget implements MCREditorTarget { private static final Logger LOGGER = LogManager.getLogger(MCRSubselectReturnTarget.class); @Override public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String parameter) throws Exception { String baseXPath = getBaseXPathForSubselect(session); LOGGER.info("Returning from subselect for {}", baseXPath); if (Objects.equals(parameter, "cancel")) { session.setBreakpoint("After canceling subselect for " + baseXPath); } else { Map<String, String[]> submittedValues = MCRTargetUtils.getSubmittedValues(job, baseXPath); session.getSubmission().setSubmittedValues(submittedValues); session.setBreakpoint("After returning from subselect for " + baseXPath); } job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(session.getRedirectURL(null))); } private String getBaseXPathForSubselect(MCREditorSession session) throws JaxenException, JDOMException { Document doc = session.getEditedXML(); MCRChangeData change = session.getChangeTracker().findLastChange(doc); String text = change.getText(); String xPath = text.substring(text.lastIndexOf(" ") + 1).trim(); return bindsFirstOrMoreThanOneElement(xPath, session) ? xPath + "[1]" : xPath; } private boolean bindsFirstOrMoreThanOneElement(String xPath, MCREditorSession session) throws JaxenException { MCRBinding binding = new MCRBinding(xPath, false, session.getRootBinding()); boolean result = (binding.getBoundNode() instanceof Element) && !xPath.endsWith("]"); binding.detach(); return result; } }
3,065
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLayoutServiceTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRLayoutServiceTarget.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.frontend.xeditor.target; import org.jdom2.Document; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.xml.MCRLayoutService; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCREditorSession; import org.mycore.frontend.xeditor.tracker.MCRChangeTracker; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen */ public class MCRLayoutServiceTarget implements MCREditorTarget { @Override public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String style) throws Exception { session.getSubmission().setSubmittedValues(job.getRequest().getParameterMap()); Document result = session.getEditedXML(); if (session.getValidator().isValid()) { result = MCRChangeTracker.removeChangeTracking(result); result = session.getXMLCleaner().clean(result); result = session.getPostProcessor().process(result); if ((style != null) && (!style.isEmpty())) { job.getRequest().setAttribute("XSL.Style", style); } MCRContent editedXML = new MCRJDOMContent(result); MCRLayoutService.instance().doLayout(job.getRequest(), job.getResponse(), editedXML); session.setBreakpoint("After handling target layout " + style); } else { session.setBreakpoint("After validation failed, target layout " + style); job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(session.getRedirectURL(null))); } } }
2,398
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAjaxSubselectTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRAjaxSubselectTarget.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.frontend.xeditor.target; import java.util.Map; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCREditorSession; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletResponse; public class MCRAjaxSubselectTarget implements MCREditorTarget { @Override public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String parameter) throws Exception { int pos = parameter.lastIndexOf(":"); String xPath = parameter.substring(0, pos); Map<String, String[]> submittedValues = MCRTargetUtils.getSubmittedValues(job, xPath); session.getSubmission().setSubmittedValues(submittedValues); job.getResponse().setStatus(HttpServletResponse.SC_OK); job.getResponse().getOutputStream().print(session.getCombinedSessionStepID()); job.getResponse().getOutputStream().flush(); job.getResponse().getOutputStream().close(); } }
1,744
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCancelTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRCancelTarget.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.frontend.xeditor.target; import java.io.IOException; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCREditorSession; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen * * Implements the "cancel" target to redirect when cancel button is clicked. * The target URL is set by <code>&lt;xed:cancel url="..." /&gt;</code> * * When no URL is set, the web application base URL is used. * When a complete URL is given, it is used as is. * When a relative path is given, the URL is calculated relative to the page containing the editor form. * When an absolute path is given, the web application base URL is prepended. */ public class MCRCancelTarget implements MCREditorTarget { @Override public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String parameter) throws IOException { String cancelURL = session.getCancelURL(); if (cancelURL == null) { cancelURL = MCRFrontendUtil.getBaseURL(); } else if (cancelURL.startsWith("/")) { cancelURL = MCRFrontendUtil.getBaseURL() + cancelURL.substring(1); } else if (!(cancelURL.startsWith("http:") || cancelURL.startsWith("https:"))) { String pageURL = session.getPageURL(); cancelURL = pageURL.substring(0, pageURL.lastIndexOf('/') + 1) + cancelURL; } job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(cancelURL)); } }
2,307
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSwapTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRSwapTarget.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.frontend.xeditor.target; import org.jaxen.JaxenException; import org.mycore.frontend.xeditor.MCRRepeatBinding; /** * @author Frank Lützenkirchen */ public class MCRSwapTarget extends MCRSwapInsertTarget { public static final boolean MOVE_DOWN = true; public static final boolean MOVE_UP = false; @Override protected void handle(int pos, MCRRepeatBinding repeatBinding) { repeatBinding.swap(pos); } public static String getSwapParameter(MCRRepeatBinding repeatBinding, boolean direction) throws JaxenException { int pos = repeatBinding.getRepeatPosition() + (direction == MOVE_UP ? -1 : 0); return buildParameter(repeatBinding, pos); } }
1,444
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRInsertTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRInsertTarget.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.frontend.xeditor.target; import org.jaxen.JaxenException; import org.mycore.frontend.xeditor.MCRRepeatBinding; /** * @author Frank Lützenkirchen */ public class MCRInsertTarget extends MCRSwapInsertTarget { @Override protected void handle(int pos, MCRRepeatBinding repeatBinding) throws JaxenException { repeatBinding.insert(pos); } public static String getInsertParameter(MCRRepeatBinding repeatBinding) throws JaxenException { return buildParameter(repeatBinding, repeatBinding.getRepeatPosition()); } }
1,294
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRepeaterControl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRRepeaterControl.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.frontend.xeditor.target; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCREditorSession; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen */ public abstract class MCRRepeaterControl implements MCREditorTarget { public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String buttonName) throws Exception { session.getSubmission().setSubmittedValues(job.getRequest().getParameterMap()); int posOfAnchor = buttonName.lastIndexOf('|'); String param = buttonName.substring(0, posOfAnchor); String anchor = buttonName.substring(posOfAnchor + 1); handleRepeaterControl(context, job, session, param); job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(session.getRedirectURL(anchor))); } protected abstract void handleRepeaterControl(ServletContext context, MCRServletJob job, MCREditorSession session, String param) throws Exception; }
1,789
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRServletTarget.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/target/MCRServletTarget.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.frontend.xeditor.target; import org.jdom2.Document; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.MCREditorSession; import org.mycore.frontend.xeditor.tracker.MCRChangeTracker; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletContext; /** * @author Frank Lützenkirchen */ public class MCRServletTarget implements MCREditorTarget { @Override public void handleSubmission(ServletContext context, MCRServletJob job, MCREditorSession session, String servletNameOrPath) throws Exception { session.getSubmission().setSubmittedValues(job.getRequest().getParameterMap()); Document result = session.getEditedXML(); if (session.getValidator().isValid()) { result = MCRChangeTracker.removeChangeTracking(result); result = session.getXMLCleaner().clean(result); result = session.getPostProcessor().process(result); RequestDispatcher dispatcher = context.getNamedDispatcher(servletNameOrPath); if (dispatcher == null) { dispatcher = context.getRequestDispatcher(servletNameOrPath); } job.getRequest().setAttribute("MCRXEditorSubmission", result); session.setBreakpoint("After handling target servlet " + servletNameOrPath); dispatcher.forward(job.getRequest(), job.getResponse()); } else { session.setBreakpoint("After validation failed, target servlet " + servletNameOrPath); job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(session.getRedirectURL(null))); } } }
2,406
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJaxenXPathFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/jaxen/MCRJaxenXPathFactory.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.frontend.xeditor.jaxen; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jaxen.Function; import org.jaxen.XPath; import org.jaxen.XPathFunctionContext; import org.jdom2.Namespace; import org.jdom2.filter.Filter; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.jaxen.JaxenXPathFactory; import org.mycore.common.MCRConstants; /** * @author Frank Lützenkirchen */ public class MCRJaxenXPathFactory extends JaxenXPathFactory { private static final Logger LOGGER = LogManager.getLogger(MCRJaxenXPathFactory.class); private List<ExtensionFunction> functions = new ArrayList<>(); public MCRJaxenXPathFactory() { super(); functions.add(new ExtensionFunction("xed", "generate-id", new MCRFunctionGenerateID())); functions.add(new ExtensionFunction("xed", "call-java", new MCRFunctionCallJava())); functions.add(new ExtensionFunction("i18n", "translate", new MCRFunctionTranslate())); } @Override public <T> XPathExpression<T> compile(String expression, Filter<T> filter, Map<String, Object> variables, Namespace... namespaces) { XPathExpression<T> jaxenCompiled = super.compile(expression, filter, variables, namespaces); if (functions.stream().anyMatch(function -> function.isCalledIn(expression))) { addExtensionFunctions(jaxenCompiled); } return jaxenCompiled; } private <T> void addExtensionFunctions(XPathExpression<T> jaxenCompiled) { try { XPath xPath = getXPath(jaxenCompiled); addExtensionFunctions(xPath); } catch (Exception ex) { LOGGER.warn(ex); } } private void addExtensionFunctions(XPath xPath) { XPathFunctionContext xfc = (XPathFunctionContext) (xPath.getFunctionContext()); for (ExtensionFunction function : functions) { function.register(xfc); } xPath.setFunctionContext(xfc); } private <T> XPath getXPath(XPathExpression<T> jaxenCompiled) throws NoSuchFieldException, IllegalAccessException { Field xPathField = jaxenCompiled.getClass().getDeclaredField("xPath"); xPathField.setAccessible(true); XPath xPath = (XPath) (xPathField.get(jaxenCompiled)); xPathField.setAccessible(false); return xPath; } static class ExtensionFunction { String prefix; String localName; Function function; ExtensionFunction(String prefix, String localName, Function function) { this.prefix = prefix; this.localName = localName; this.function = function; } public void register(XPathFunctionContext context) { context.registerFunction(MCRConstants.getStandardNamespace(prefix).getURI(), localName, function); } public boolean isCalledIn(String xPathExpression) { return xPathExpression.contains(prefix + ":" + localName + "("); } } }
3,876
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFunctionCallJava.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/jaxen/MCRFunctionCallJava.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.frontend.xeditor.jaxen; import java.lang.reflect.Method; import java.util.List; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jaxen.Context; class MCRFunctionCallJava implements org.jaxen.Function { private static final Logger LOGGER = LogManager.getLogger(MCRFunctionCallJava.class); @Override public Object call(Context context, List args) { try { String clazzName = (String) (args.get(0)); String methodName = (String) (args.get(1)); LOGGER.debug("XEditor extension function calling {} {}", clazzName, methodName); Class[] argTypes = new Class[args.size() - 2]; Object[] params = new Object[args.size() - 2]; for (int i = 0; i < argTypes.length; i++) { argTypes[i] = args.get(i + 2).getClass(); params[i] = args.get(i + 2); } Class clazz = ClassUtils.getClass(clazzName); Method method = MethodUtils.getMatchingAccessibleMethod(clazz, methodName, argTypes); return method.invoke(null, params); } catch (Exception ex) { LOGGER.warn("Exception in call to external java method", ex); return ex.getMessage(); } } }
2,129
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFunctionGenerateID.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/jaxen/MCRFunctionGenerateID.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.frontend.xeditor.jaxen; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jaxen.Context; class MCRFunctionGenerateID implements org.jaxen.Function { private static final Logger LOGGER = LogManager.getLogger(MCRFunctionGenerateID.class); @Override public Object call(Context context, List args) { try { Object targetNode = args.isEmpty() ? context.getNodeSet().get(0) : ((List) args.get(0)).get(0); return "n" + System.identityHashCode(targetNode); } catch (Exception ex) { LOGGER.warn("Exception in call to generate-id", ex); return ex.getMessage(); } } }
1,463
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFunctionTranslate.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/jaxen/MCRFunctionTranslate.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.frontend.xeditor.jaxen; import java.util.List; import org.jaxen.Context; import org.mycore.services.i18n.MCRTranslation; /** * * @author Frank Lützenkirchen */ class MCRFunctionTranslate implements org.jaxen.Function { @Override public Object call(Context context, List args) { String i18nkey = (String) (args.get(0)); if (args.size() == 1) { return MCRTranslation.translate(i18nkey); } else { return MCRTranslation.translate(i18nkey, args.subList(1, args.size())); } } }
1,295
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAclEditorResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl-editor2/src/main/java/org/mycore/frontend/acl2/resources/MCRAclEditorResource.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.frontend.acl2.resources; import java.io.InputStream; import java.util.Collection; import java.util.Date; import java.util.Objects; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.access.mcrimpl.MCRAccessRule; import org.mycore.access.mcrimpl.MCRAccessStore; import org.mycore.access.mcrimpl.MCRRuleMapping; import org.mycore.access.mcrimpl.MCRRuleStore; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.jersey.MCRJerseyUtil; import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; 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; @Path("ACLE") public class MCRAclEditorResource { private static final MCRRuleStore RULE_STORE = MCRRuleStore.getInstance(); private static final MCRAccessStore ACCESS_STORE = MCRAccessStore.getInstance(); private static final String JSON_ACCESSID = "accessID"; private static final String JSON_ACCESSPOOL = "accessPool"; private static final String JSON_RULE = "rule"; private static final String JSON_SUCCESS = "success"; @Context HttpServletRequest request; @Context HttpServletResponse response; @Context ServletContext context; @GET @Path("start") @MCRRestrictedAccess(MCRAclEditorPermission.class) @Produces(MediaType.TEXT_HTML) public InputStream start() throws Exception { return transform("/META-INF/resources/modules/acl-editor2/gui/xml/webpage.xml"); } protected InputStream transform(String xmlFile) throws Exception { InputStream guiXML = getClass().getResourceAsStream(xmlFile); if (guiXML == null) { throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).build()); } SAXBuilder saxBuilder = new SAXBuilder(); Document webPage = saxBuilder.build(guiXML); XPathExpression<Object> xpath = XPathFactory.instance().compile( "/MyCoReWebPage/section/div[@id='mycore-acl-editor2']"); Object node = xpath.evaluateFirst(webPage); MCRSession mcrSession = MCRSessionMgr.getCurrentSession(); String lang = mcrSession.getCurrentLanguage(); if (node != null) { Element mainDiv = (Element) node; mainDiv.setAttribute("lang", lang); String bsPath = MCRConfiguration2.getString("MCR.bootstrap.path").orElse(""); if (!Objects.equals(bsPath, "")) { bsPath = MCRFrontendUtil.getBaseURL() + bsPath; Element item = new Element("link").setAttribute("href", bsPath).setAttribute("rel", "stylesheet") .setAttribute("type", "text/css"); mainDiv.addContent(0, item); } } MCRContent content = MCRJerseyUtil.transform(webPage, request); return content.getInputStream(); } @GET @MCRRestrictedAccess(MCRAclEditorPermission.class) public String list() { Collection<String> ruleIDs = RULE_STORE.retrieveAllIDs(); JsonArray jsonARules = new JsonArray(); JsonObject jsonObj = new JsonObject(); for (String id : ruleIDs) { MCRAccessRule rule = RULE_STORE.getRule(id); JsonObject jsonO = new JsonObject(); jsonO.addProperty("ruleID", id); jsonO.addProperty("desc", rule.getDescription()); jsonO.addProperty("ruleSt", rule.getRuleString()); jsonARules.add(jsonO); } jsonObj.add("rules", jsonARules); JsonArray jsonAAccess = new JsonArray(); Collection<String> ids = ACCESS_STORE.getDistinctStringIDs(); for (String id : ids) { Collection<String> pools = ACCESS_STORE.getPoolsForObject(id); for (String pool : pools) { JsonObject jsonO = new JsonObject(); jsonO.addProperty(JSON_ACCESSID, id); jsonO.addProperty(JSON_ACCESSPOOL, pool); jsonO.addProperty(JSON_RULE, ACCESS_STORE.getRuleID(id, pool)); jsonAAccess.add(jsonO); } } jsonObj.add("access", jsonAAccess); return jsonObj.toString(); } @POST @Consumes(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRAclEditorPermission.class) public Response add(String data) { JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); String accessID = jsonObject.get(JSON_ACCESSID).getAsString(); String accessPool = jsonObject.get(JSON_ACCESSPOOL).getAsString(); String rule = jsonObject.get(JSON_RULE).getAsString(); if (RULE_STORE.existsRule(rule) && !Objects.equals(accessID, "") && !Objects.equals(accessPool, "")) { MCRRuleMapping accessRule = createRuleMap(accessID, accessPool, rule); if (!ACCESS_STORE.existsRule(accessID, accessPool)) { ACCESS_STORE.createAccessDefinition(accessRule); return Response.ok().build(); } else { return Response.status(Status.CONFLICT).build(); } } else { return Response.status(Status.CONFLICT).build(); } } @DELETE @Consumes(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRAclEditorPermission.class) public String remove(String data) { JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); JsonArray jsonArray = jsonObject.getAsJsonArray("access"); for (int i = 0; i < jsonArray.size(); i++) { JsonObject accessAsJsonObject = jsonArray.get(i).getAsJsonObject(); String accessID = accessAsJsonObject.get(JSON_ACCESSID).getAsString(); String accessPool = accessAsJsonObject.get(JSON_ACCESSPOOL).getAsString(); if (ACCESS_STORE.existsRule(accessID, accessPool)) { MCRRuleMapping accessRule = ACCESS_STORE.getAccessDefinition(accessPool, accessID); if (!"".equals(accessRule.getObjId())) { ACCESS_STORE.deleteAccessDefinition(accessRule); accessAsJsonObject.addProperty(JSON_SUCCESS, "1"); } else { accessAsJsonObject.addProperty(JSON_SUCCESS, "0"); } } else { accessAsJsonObject.addProperty(JSON_SUCCESS, "0"); } } return jsonObject.toString(); } @PUT @Consumes(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRAclEditorPermission.class) public Response edit(String data) { JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); String accessIDOld = jsonObject.get("accessIDOld").getAsString(); String accessPoolOld = jsonObject.get("accessPoolOld").getAsString(); String mode = jsonObject.get("mode").getAsString(); String accessIDNew = jsonObject.get("accessIDNew").getAsString(); String accessPoolNew = jsonObject.get("accessPoolNew").getAsString(); String accessRuleNew = jsonObject.get("accessRuleNew").getAsString(); if (!ACCESS_STORE.existsRule(accessIDNew, accessPoolNew) || JSON_RULE.equals(mode)) { if (ACCESS_STORE.existsRule(accessIDOld, accessPoolOld) && RULE_STORE.existsRule(accessRuleNew) && !Objects.equals(accessIDNew, "") && !Objects.equals(accessPoolNew, "")) { MCRRuleMapping accessRule = createRuleMap(accessIDNew, accessPoolNew, accessRuleNew); MCRRuleMapping oldAccessRule = ACCESS_STORE.getAccessDefinition(accessPoolOld, accessIDOld); if (oldAccessRule != null && !oldAccessRule.getObjId().equals("")) { if (JSON_RULE.equals(mode)) { ACCESS_STORE.updateAccessDefinition(accessRule); } else { ACCESS_STORE.deleteAccessDefinition(oldAccessRule); ACCESS_STORE.createAccessDefinition(accessRule); } } else { ACCESS_STORE.createAccessDefinition(accessRule); } return Response.ok().build(); } else { return Response.status(Status.CONFLICT).build(); } } else { return Response.status(Status.CONFLICT).build(); } } @POST @Path(JSON_RULE) @MCRRestrictedAccess(MCRAclEditorPermission.class) @Consumes(MediaType.APPLICATION_JSON) public String addRule(String data) { JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); String ruleDesc = jsonObject.get("ruleDesc").getAsString(); String ruleText = jsonObject.get("ruleText").getAsString(); MCRAccessRule accessRule; try { accessRule = createAccessRule(ruleDesc, ruleText); } catch (Exception e) { return ""; } RULE_STORE.createRule(accessRule); return accessRule.getId(); } @DELETE @Path(JSON_RULE) @MCRRestrictedAccess(MCRAclEditorPermission.class) @Consumes(MediaType.APPLICATION_JSON) public Response removeRule(String data) { JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); String ruleID = jsonObject.get("ruleID").getAsString(); if (!ACCESS_STORE.isRuleInUse(ruleID)) { RULE_STORE.deleteRule(ruleID); return Response.ok().build(); } else { return Response.status(Status.CONFLICT).build(); } } @PUT @Path(JSON_RULE) @MCRRestrictedAccess(MCRAclEditorPermission.class) @Consumes(MediaType.APPLICATION_JSON) public Response editRule(String data) { JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); String ruleID = jsonObject.get("ruleID").getAsString(); String ruleDesc = jsonObject.get("ruleDesc").getAsString(); String ruleText = jsonObject.get("ruleText").getAsString(); String uid = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(); if (RULE_STORE.existsRule(ruleID)) { try { MCRAccessRule accessRule = new MCRAccessRule(ruleID, uid, new Date(), ruleText, ruleDesc); RULE_STORE.updateRule(accessRule); return Response.ok().build(); } catch (Exception e) { return Response.status(Status.CONFLICT).build(); } } else { return Response.status(Status.CONFLICT).build(); } } @PUT @Path("multi") @MCRRestrictedAccess(MCRAclEditorPermission.class) @Consumes(MediaType.APPLICATION_JSON) public String editMulti(String data) { JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject(); JsonArray jsonArray = jsonObject.getAsJsonArray("access"); for (int i = 0; i < jsonArray.size(); i++) { JsonObject accessAsJsonObject = jsonArray.get(i).getAsJsonObject(); String accessID = accessAsJsonObject.get(JSON_ACCESSID).getAsString(); String accessPool = accessAsJsonObject.get(JSON_ACCESSPOOL).getAsString(); String accessRule = accessAsJsonObject.get("accessRule").getAsString(); if (ACCESS_STORE.existsRule(accessID, accessPool) && RULE_STORE.existsRule(accessRule)) { MCRRuleMapping newAccessRule = createRuleMap(accessID, accessPool, accessRule); MCRRuleMapping oldAccessRule = ACCESS_STORE.getAccessDefinition(accessPool, accessID); if (oldAccessRule != null && !oldAccessRule.getObjId().equals("")) { ACCESS_STORE.updateAccessDefinition(newAccessRule); accessAsJsonObject.addProperty(JSON_SUCCESS, "1"); } else { ACCESS_STORE.createAccessDefinition(newAccessRule); accessAsJsonObject.addProperty(JSON_SUCCESS, "1"); } } else { accessAsJsonObject.addProperty(JSON_SUCCESS, "0"); } } return jsonObject.toString(); } private MCRRuleMapping createRuleMap(String accessID, String accessPool, String rule) { String uid = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(); MCRRuleMapping accessRule = new MCRRuleMapping(); accessRule.setObjId(accessID); accessRule.setPool(accessPool); accessRule.setRuleId(rule); accessRule.setCreationdate(new Date()); accessRule.setCreator(uid); return accessRule; } private MCRAccessRule createAccessRule(String ruleDesc, String ruleText) { int freeRuleID = RULE_STORE.getNextFreeRuleID("SYSTEMRULE"); String ruleID = "0000000000" + freeRuleID; ruleID = ruleID.substring(ruleID.length() - "0000000000".length()); String newRuleID = "SYSTEMRULE" + ruleID; String uid = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(); return new MCRAccessRule(newRuleID, uid, new Date(), ruleText, ruleDesc); } }
14,701
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAclEditorGuiResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl-editor2/src/main/java/org/mycore/frontend/acl2/resources/MCRAclEditorGuiResource.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.frontend.acl2.resources; import org.mycore.frontend.jersey.MCRStaticContent; import jakarta.servlet.http.HttpServletResponse; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.Response; @Path("ACLE/gui") @MCRStaticContent public class MCRAclEditorGuiResource { @Context HttpServletResponse response; @GET @Path("{filename:.*}") public Response getResources(@PathParam("filename") String filename) { if (filename.endsWith(".js")) { return Response.ok(getClass() .getResourceAsStream("/META-INF/resources/modules/acl-editor2/gui/" + filename)) .header("Content-Type", "application/javascript") .build(); } if (filename.endsWith(".css")) { return Response.ok(getClass() .getResourceAsStream("/META-INF/resources/modules/acl-editor2/gui/" + filename)) .header("Content-Type", "text/css") .build(); } return Response.ok(getClass() .getResourceAsStream("/META-INF/resources/modules/acl-editor2/gui/" + filename)) .build(); } }
1,977
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAclEditorPermission.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-acl-editor2/src/main/java/org/mycore/frontend/acl2/resources/MCRAclEditorPermission.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.frontend.acl2.resources; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessManager; import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker; import jakarta.ws.rs.container.ContainerRequestContext; public class MCRAclEditorPermission implements MCRResourceAccessChecker { private static Logger LOGGER = LogManager.getLogger(MCRAclEditorPermission.class); @Override public boolean isPermitted(ContainerRequestContext request) { if (!MCRAccessManager.getAccessImpl().checkPermission("use-aclEditor")) { LOGGER.info("Permission denied on MCRAclEditor"); return false; } return true; } }
1,483
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFAValidatorTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-validation/src/test/java/org/mycore/validation/pdfa/MCRPDFAValidatorTest.java
package org.mycore.validation.pdfa; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class MCRPDFAValidatorTest { @Test public void isCompliant() throws Exception { MCRPDFAValidator validator = new MCRPDFAValidator(); Assert.assertFalse("shouldn't be a valid pdf/a document", isCompliant(validator, "/noPdfA.pdf")); Assert.assertTrue("should be a valid pdf/a document", isCompliant(validator, "/pdfA-1b.pdf")); Assert.assertTrue("should be a valid pdf/a document", isCompliant(validator, "/pdfA-2b.pdf")); Assert.assertTrue("should be a valid pdf/a document", isCompliant(validator, "/pdfA-3b.pdf")); } private static boolean isCompliant(MCRPDFAValidator validator, String resourceName) throws IOException, MCRPDFAValidationException { return validator.validate(MCRPDFAValidatorTest.class.getResourceAsStream(resourceName)).isCompliant(); } }
959
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFAValidatorResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-validation/src/main/java/org/mycore/validation/pdfa/MCRPDFAValidatorResolver.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.validation.pdfa; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMSource; import org.mycore.common.MCRException; import org.mycore.datamodel.niofs.MCRPath; import org.w3c.dom.Document; /** * MCRPdfAValidatorResolver is a custom URIResolver implementation used for resolving XML document URIs during * transformations. It resolves a specific URI, gathers validation results using MCRPdfAFunctions, and returns the * resulting XML document as a Source object. *<p><br> * When an XML transformation is performed, and an external resource URI is encountered in the document, the * 'resolve' method of this class is called to handle the resolution of the URI. In this case, the URI format is assumed * to be 'mcrpdfa:{derivateId}', where 'derivateId' is the ID of the object for which validation results are required. *<p><br> * The 'resolve' method takes the 'href' and 'base' parameters, but only the 'href' is used. The 'href' is split to * extract the 'derivateId', and then the MCRPdfAFunctions class is used to generate the XML document containing the * validation results. The resulting XML document is returned as a DOMSource object, which can be used in the XML * transformation process. *<p><br> * Note: This implementation assumes that the 'href' parameter follows the 'mcrpdfa:{derivateId}' format, and the 'base' * parameter is not used in the resolution process. */ public class MCRPDFAValidatorResolver implements URIResolver { @Override public Source resolve(String href, String base) throws TransformerException { String[] hrefParts = href.split(":"); String derivateId = hrefParts[1]; MCRPath rootPath = MCRPath.getRootPath(derivateId); try { Document document = MCRPDFAFunctions.getResults(rootPath, derivateId); return new DOMSource(document); } catch (ParserConfigurationException | IOException e) { throw new MCRException(e); } } }
2,903
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFAValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-validation/src/main/java/org/mycore/validation/pdfa/MCRPDFAValidator.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.validation.pdfa; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import org.verapdf.core.EncryptedPdfException; import org.verapdf.core.ModelParsingException; import org.verapdf.core.ValidationException; import org.verapdf.gf.foundry.VeraGreenfieldFoundryProvider; import org.verapdf.pdfa.Foundries; import org.verapdf.pdfa.PDFAParser; import org.verapdf.pdfa.PDFAValidator; import org.verapdf.pdfa.results.ValidationResult; /** * Pdf/A Validator. * * @author Matthias Eichner */ public class MCRPDFAValidator { private static volatile Boolean INITIALIZED = false; private static final Object MUTEX = new Object(); private static void initialise() { if (!INITIALIZED) { synchronized (MUTEX) { if (INITIALIZED) { return; } INITIALIZED = true; VeraGreenfieldFoundryProvider.initialise(); } } } /** * Checks if the given input stream is a valid pdf/a document. * * @param inputStream the input stream * @return result of the validation * @throws MCRPDFAValidationException something went wrong while parsing or validating * @throws IOException i/o exception */ public ValidationResult validate(InputStream inputStream) throws MCRPDFAValidationException, IOException { initialise(); try (PDFAParser parser = Foundries.defaultInstance().createParser(inputStream); PDFAValidator validator = Foundries.defaultInstance().createValidator(parser.getFlavour(), false)) { return validator.validate(parser); } catch (ValidationException | ModelParsingException | EncryptedPdfException e) { throw new MCRPDFAValidationException("unable to validate pdf", e); } } /** * Checks if the given path is a valid pdf/a document. * * @param path path to the pdf document * @return result of the validation * @throws MCRPDFAValidationException something went wrong while parsing or validating * @throws IOException i/o exception */ public ValidationResult validate(Path path) throws MCRPDFAValidationException, IOException { try (InputStream inputStream = Files.newInputStream(path)) { return validate(inputStream); } } }
3,178
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFAFunctions.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-validation/src/main/java/org/mycore/validation/pdfa/MCRPDFAFunctions.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.validation.pdfa; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.mycore.common.MCRException; import org.verapdf.pdfa.flavours.PDFAFlavour; import org.verapdf.pdfa.results.ValidationResult; import org.verapdf.pdfa.validation.profiles.RuleId; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * MCRPdfAFunctions is a utility class that uses MCRPdfAValidator to validate multiple PDF files and generates an XML * document with detailed information about the validation results for each file.<br> * The class provides a method, 'getResults', which takes a directory path and an object ID as input. It iterates * through all PDF files in the specified directory, validates them using MCRPdfAValidator, and records the * validation results in an XML format. The resulting XML document has a hierarchical structure as follows: * <p> * <ul> * * <li> &lt;derivate&gt;: Root element representing the object with the given ID. * <li> &lt;file&gt;: Element representing each PDF file, containing its name and PDF/A flavor. * <li> &lt;failed&gt;: Element representing each failed check in the validation, containing the test number, clause, * specification, and a link to the official VeraPDF error documentation (depending on the error). * </ul> * <p> * The XML document presents detailed information about each PDF file's validation, including the number of failed * checks and links to the official VeraPDF error documentation for further reference. The structure allows users to * easily analyze and address validation issues in the PDF files. * * @author Antonia Friedrich */ public class MCRPDFAFunctions { private static final MCRPDFAValidator PDF_A_VALIDATOR = new MCRPDFAValidator(); /** * Retrieves PDF validation results for files in a given directory and generates an XML document * containing the validation outcomes. * * @param dir The path to the directory containing the PDF files to validate. * @param objectId An identifier for the validation process or target. * @return A Document object representing an XML structure containing validation results. * @throws ParserConfigurationException If a DocumentBuilder cannot be created. * @throws IOException If an I/O error occurs while processing the files. * @throws MCRException If there is an issue with PDF validation or file processing. */ public static Document getResults(Path dir, String objectId) throws ParserConfigurationException, IOException { Map<String, ValidationResult> results = new HashMap<>(); Files.walkFileTree(dir, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().endsWith(".pdf")) { try { results.put(dir.relativize(file).toString(), PDF_A_VALIDATOR.validate(file)); } catch (MCRPDFAValidationException e) { throw new MCRException(e); } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } }); return createXML(objectId, results); } /** * Creates an XML Document representing the validation results for the PDF files. * * @param objectId The ID of the object for which the validation results are generated. * @param results A map containing the validation results for each PDF file. * @return An XML Document representing the validation results. * @throws ParserConfigurationException If there is a configuration issue with the XML document builder. */ private static Document createXML(String objectId, Map<String, ValidationResult> results) throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element derivateElement = createDerivateElement(document, objectId); document.appendChild(derivateElement); for (Map.Entry<String, ValidationResult> resultEntry : results.entrySet()) { createXMLTag(derivateElement, document, resultEntry); } return document; } /** * Creates an XML tag for a PDF file with its validation results. * * @param derivateElement The parent element to which the file element is added. * @param document The XML document being constructed. * @param resultEntry A map entry containing the file name and its validation result. */ private static void createXMLTag(Element derivateElement, Document document, Map.Entry<String, ValidationResult> resultEntry) { String fileName = resultEntry.getKey(); ValidationResult result = resultEntry.getValue(); Element fileElement = createFileElement(document, fileName, result); derivateElement.appendChild(fileElement); } /** * Creates an XML element representing the "derivate" with an ID attribute. * * @param document The XML document being constructed. * @param objectId The ID of the object for which the validation results are generated. * @return The "derivate" XML element. */ private static Element createDerivateElement(Document document, String objectId) { Element derivateElement = document.createElement("derivate"); derivateElement.setAttribute("id", objectId); return derivateElement; } /** * Creates an XML element representing a "file" with its attributes and "failed" tags for each failed check. * * @param document The XML document being constructed. * @param fileName The name of the PDF file. * @param result The validation result for the PDF file. * @return The "file" XML element. */ private static Element createFileElement(Document document, String fileName, ValidationResult result) { Element fileElement = document.createElement("file"); fileElement.setAttribute("name", fileName); fileElement.setAttribute("flavour", result.getPDFAFlavour().toString()); result.getFailedChecks().keySet().stream() .map(rid -> createFailedElement(document, rid)) .forEach(fileElement::appendChild); return fileElement; } /** * Creates an XML element representing a "failed" check with its attributes. * * @param document The XML document being constructed. * @param ruleId The RuleId containing information about the failed check. * @return The "failed" XML element. */ private static Element createFailedElement(Document document, RuleId ruleId) { Element failedElement = document.createElement("failed"); failedElement.setAttribute("testNumber", String.valueOf(ruleId.getTestNumber())); failedElement.setAttribute("clause", ruleId.getClause()); failedElement.setAttribute("specification", ruleId.getSpecification().toString()); failedElement.setAttribute("Link", getLink(ruleId)); return failedElement; } /** * Generates a link to an external veraPDF wiki page for a failed check based on the given RuleId. * The link is constructed using the specification, clause, and test number of the failed check. * * @param ruleId The RuleId object representing the failed check. * @return The link to the external veraPDF wiki page for the failed check, or an empty string if no link * should be returned. */ private static String getLink(RuleId ruleId) { PDFAFlavour.Specification specification = ruleId.getSpecification(); String firstPart = switch (specification) { case ISO_14289_1 -> "PDFUA-Part-1-rules"; case ISO_19005_4 -> "PDFA-Part-4-rules"; case ISO_19005_2, ISO_19005_3 -> "PDFA-Parts-2-and-3-rules"; case ISO_19005_1 -> "PDFA-Part-1-rules"; default -> ""; }; if (firstPart.isEmpty()) { return ""; } String secondPart = ruleId.getClause().replaceAll("\\.", ""); return "https://github.com/veraPDF/veraPDF-validation-profiles/wiki/" + firstPart + "#rule-" + secondPart + "-" + ruleId.getTestNumber(); } }
9,753
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPDFAValidationException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-validation/src/main/java/org/mycore/validation/pdfa/MCRPDFAValidationException.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.validation.pdfa; import org.mycore.common.MCRCatchException; /** * * * @author Matthias Eichner */ public class MCRPDFAValidationException extends MCRCatchException { private static final long serialVersionUID = 1L; public MCRPDFAValidationException(String message, Throwable cause) { super(message, cause); } }
1,085
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMockIdentifierGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRMockIdentifierGenerator.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.pi; import org.junit.Assert; import org.mycore.datamodel.metadata.MCRBase; public class MCRMockIdentifierGenerator extends MCRPIGenerator<MCRMockIdentifier> { public static final String TEST_PROPERTY = "mockProperty"; public static final String TEST_PROPERTY_VALUE = "mockPropertyValue"; @Override public MCRMockIdentifier generate(MCRBase mcrBase, String additional) { Assert.assertEquals("Test propterties should be set!", getProperties().get(TEST_PROPERTY), TEST_PROPERTY_VALUE); return (MCRMockIdentifier) new MCRMockIdentifierParser() .parse(MCRMockIdentifier.MOCK_SCHEME + mcrBase.getId() + ":" + additional).get(); } }
1,426
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRPIUtils.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.pi; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; import org.mycore.pi.urn.MCRDNBURN; import org.mycore.pi.urn.MCRUUIDURNGenerator; import org.mycore.pi.urn.rest.MCRDNBURNRestClient; import org.mycore.pi.urn.rest.MCRURNJsonBundle; /** * Created by chi on 23.02.17. * * @author Huu Chi Vu */ public class MCRPIUtils { final private static Logger LOGGER = LogManager.getLogger(); public static MCRPI generateMCRPI(String fileName, String serviceID) throws MCRPersistentIdentifierException { MCRObjectID mycoreID = getNextFreeID(); return new MCRPI(generateURNFor(mycoreID).asString(), MCRDNBURN.TYPE, mycoreID.toString(), fileName, serviceID, null); } public static MCRObjectID getNextFreeID() { return MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("MyCoRe_test"); } private static MCRDNBURN generateURNFor(MCRObjectID mycoreID) throws MCRPersistentIdentifierException { String testGenerator = "testGenerator"; MCRUUIDURNGenerator mcruuidurnGenerator = new MCRUUIDURNGenerator(); mcruuidurnGenerator.init(MCRPIService.GENERATOR_CONFIG_PREFIX + testGenerator); MCRObject mcrObject1 = new MCRObject(); mcrObject1.setId(mycoreID); return mcruuidurnGenerator.generate(mcrObject1, ""); } public static String randomFilename() { return UUID.randomUUID() .toString() .concat(".tif"); } public static URL getUrl(MCRPIRegistrationInfo info) { String url = "http://localhost:8291/deriv_0001/" + info.getAdditional(); try { return new URI(url).toURL(); } catch (MalformedURLException | URISyntaxException e) { e.printStackTrace(); LOGGER.error("Malformed URL: {}", url); } return null; } public static MCRDNBURNRestClient getMCRURNClient() { return new MCRDNBURNRestClient(MCRPIUtils::getBundle); } public static MCRURNJsonBundle getBundle(MCRPIRegistrationInfo urnInfo) { return MCRURNJsonBundle.instance(urnInfo, MCRPIUtils.getUrl(urnInfo)); } }
3,312
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMockMetadataService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRMockMetadataService.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.pi; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.Assert; import org.mycore.datamodel.metadata.MCRBase; public class MCRMockMetadataService extends MCRPIMetadataService<MCRMockIdentifier> { public static final String TEST_PROPERTY = "mockProperty"; public static final String TEST_PROPERTY_VALUE = "mockPropertyValue"; private Map<String, MCRMockIdentifier> map = new HashMap<>(); @Override public void insertIdentifier(MCRMockIdentifier identifier, MCRBase obj, String additional) { Assert.assertEquals("Test propterties should be set!", getProperties().get(TEST_PROPERTY), TEST_PROPERTY_VALUE); map.put(obj + additional, identifier); } @Override public void removeIdentifier(MCRMockIdentifier identifier, MCRBase obj, String additional) { Assert.assertEquals("Test properties should be set!", getProperties().get(TEST_PROPERTY), TEST_PROPERTY_VALUE); map.remove(obj + additional); } @Override public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase obj, String additional) { return Optional.ofNullable(map.get(obj + additional)); } }
1,933
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMockIdentifierService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRMockIdentifierService.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.pi; import java.util.Date; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.metadata.MCRBase; public class MCRMockIdentifierService extends MCRPIService<MCRMockIdentifier> { protected static final String TYPE = "mock"; public static final Logger LOGGER = LogManager.getLogger(); public MCRMockIdentifierService() { super(TYPE); } private boolean registerCalled = false; private boolean deleteCalled = false; private boolean updatedCalled = false; @Override protected MCRPIServiceDates registerIdentifier(MCRBase obj, String additional, MCRMockIdentifier mi) { registerCalled = true; return new MCRPIServiceDates(new Date(), null); } @Override public void delete(MCRMockIdentifier identifier, MCRBase obj, String additional) { deleteCalled = true; } @Override public void update(MCRMockIdentifier identifier, MCRBase obj, String additional) { updatedCalled = true; } public boolean isRegisterCalled() { return registerCalled; } public boolean isDeleteCalled() { return deleteCalled; } public boolean isUpdatedCalled() { return updatedCalled; } protected void reset() { this.registerCalled = this.deleteCalled = this.updatedCalled = false; } }
2,134
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIManagerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRPIManagerTest.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.pi; import java.lang.reflect.Field; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mycore.access.MCRAccessBaseImpl; import org.mycore.access.MCRAccessException; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRStoreTestCase; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.processing.impl.MCRCentralProcessableRegistry; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public class MCRPIManagerTest extends MCRStoreTestCase { private static final String MOCK_SERVICE = "MockService"; private static final String MOCK_METADATA_SERVICE = "MockInscriber"; private static final String MOCK_PID_GENERATOR = "MockIDGenerator"; @Rule public TemporaryFolder baseDir = new TemporaryFolder(); @Before public void setUp() throws Exception { super.setUp(); } @Test public void testGet() throws Exception { String mockString = MCRMockIdentifier.MOCK_SCHEME + "http://google.de/"; Optional<? extends MCRPersistentIdentifier> mockIdentifierOptional = MCRPIManager .getInstance() .get(mockString) .findFirst(); Assert.assertTrue(mockIdentifierOptional.isPresent()); Assert.assertEquals(mockIdentifierOptional.get().asString(), mockString); // test get(service, id, additional) MCRPIService<MCRMockIdentifier> registrationService = MCRPIServiceManager .getInstance() .getRegistrationService(MOCK_SERVICE); ((MCRMockIdentifierService) registrationService).reset(); MCRObject mcrObject = buildMockObject(); registrationService.register(mcrObject, null); MCRPI mcrpi = MCRPIManager.getInstance().get(MOCK_SERVICE, mcrObject.getId().toString(), null); Assert.assertNotNull(mcrpi); } @Test public void testParseIdentifier() { String mockString = MCRMockIdentifier.MOCK_SCHEME + "http://google.de/"; Stream<MCRPersistentIdentifier> mcrPersistentIdentifierStream = MCRPIManager .getInstance() .get(mockString); Optional<? extends MCRPersistentIdentifier> mcrMockIdentifier = mcrPersistentIdentifierStream .findFirst(); Assert.assertEquals(mcrMockIdentifier.get().asString(), mockString); } @Test public void testRegistrationService() throws MCRAccessException, MCRPersistentIdentifierException, ExecutionException, InterruptedException { MCRPIService<MCRMockIdentifier> registrationService = MCRPIServiceManager .getInstance() .getRegistrationService(MOCK_SERVICE); MCRMockIdentifierService casted = (MCRMockIdentifierService) registrationService; casted.reset(); Assert.assertFalse("Delete should not have been called!", casted.isDeleteCalled()); Assert.assertFalse("Register should not have been called!", casted.isRegisterCalled()); Assert.assertFalse("Update should not have been called!", casted.isUpdatedCalled()); MCRObject mcrObject = buildMockObject(); MCRMockIdentifier identifier = registrationService.register(mcrObject, "", true); Assert.assertFalse("Delete should not have been called!", casted.isDeleteCalled()); Assert.assertTrue("The identifier " + identifier.asString() + " should be registered now!", registrationService.isCreated(mcrObject.getId(), "")); registrationService.onUpdate(identifier, mcrObject, ""); Assert.assertFalse("Delete should not have been called!", casted.isDeleteCalled()); Assert.assertTrue("The identifier " + identifier.asString() + " should have been updated!", casted.isUpdatedCalled()); registrationService.onDelete(identifier, mcrObject, ""); Assert.assertFalse("The identifier " + identifier.asString() + " should not be registered now!", registrationService.isCreated(mcrObject.getId(), "")); Assert.assertTrue("There should be one resolver", MCRPIManager.getInstance() .getResolvers().stream().anyMatch(r -> r.getName().equals(MCRMockResolver.NAME))); } @Test public void testGetUnregisteredIdenifiers() throws Exception { MCREntityManagerProvider.getCurrentEntityManager().persist(generateMCRPI()); MCREntityManagerProvider.getCurrentEntityManager().persist(generateMCRPI()); long numOfUnregisteredPI = MCRPIManager.getInstance() .getUnregisteredIdentifiers("Unregistered") .size(); Assert.assertEquals("Wrong number of unregistered PI: ", 2, numOfUnregisteredPI); } private MCRPI generateMCRPI() throws MCRPersistentIdentifierException { MCRObjectID mycoreID = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("test_unregisterd"); return new MCRPI(generatePIFor(mycoreID).asString(), "Unregistered", mycoreID.toString(), null, MOCK_SERVICE, new MCRPIServiceDates(null, null)); } private MCRMockIdentifier generatePIFor(MCRObjectID mycoreID) { MCRMockIdentifierGenerator mcruuidurnGenerator = (MCRMockIdentifierGenerator) MCRConfiguration2 .getInstanceOf("MCR.PI.Generator." + MOCK_PID_GENERATOR).get(); MCRObject mcrObject = new MCRObject(); mcrObject.setId(mycoreID); return mcruuidurnGenerator.generate(mcrObject, ""); } @Before public void resetManagerInstance() { try { Field instance = MCRPIManager.class.getDeclaredField("instance"); instance.setAccessible(true); instance.set(null, null); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } @Override protected Map<String, String> getTestProperties() { Map<String, String> configuration = super.getTestProperties(); configuration.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName()); configuration.put("MCR.Metadata.Type.mock", "true"); configuration.put("MCR.Metadata.Type.unregisterd", "true"); configuration.put("MCR.PI.Resolvers", MCRMockResolver.class.getName()); configuration.put("MCR.PI.Service." + MOCK_SERVICE, MCRMockIdentifierService.class.getName()); configuration.put("MCR.PI.Service." + MOCK_SERVICE + ".Generator", MOCK_PID_GENERATOR); configuration.put("MCR.PI.Service." + MOCK_SERVICE + ".MetadataService", MOCK_METADATA_SERVICE); configuration.put("MCR.PI.MetadataService." + MOCK_METADATA_SERVICE, MCRMockMetadataService.class.getName()); configuration.put( "MCR.PI.MetadataService." + MOCK_METADATA_SERVICE + "." + MCRMockMetadataService.TEST_PROPERTY, MCRMockMetadataService.TEST_PROPERTY_VALUE); configuration.put("MCR.PI.Generator." + MOCK_PID_GENERATOR, MCRMockIdentifierGenerator.class.getName()); configuration.put("MCR.PI.Generator." + MOCK_PID_GENERATOR + "." + MCRMockIdentifierGenerator.TEST_PROPERTY, MCRMockIdentifierGenerator.TEST_PROPERTY_VALUE); configuration.put("MCR.PI.Generator." + MOCK_PID_GENERATOR + ".Namespace", "frontend-"); configuration.put("MCR.PI.Parsers." + MCRMockIdentifierService.TYPE, MCRMockIdentifierParser.class.getName()); configuration.put("MCR.QueuedJob.activated", "true"); configuration.put("MCR.QueuedJob.JobThreads", "2"); configuration.put("MCR.QueuedJob.TimeTillReset", "10"); configuration.put("MCR.Processable.Registry.Class", MCRCentralProcessableRegistry.class.getName()); configuration.put("MCR.Access.Cache.Size", "1000"); return configuration; } private MCRObject buildMockObject() { MCRObject mcrObject = new MCRObject(); MCRObjectID id = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("test", "mock"); mcrObject.setId(id); mcrObject.setSchema("http://www.w3.org/2001/XMLSchema"); return mcrObject; } @After public void tearDown() throws Exception { super.tearDown(); } }
9,344
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMockIdentifier.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRMockIdentifier.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.pi; public class MCRMockIdentifier implements MCRPersistentIdentifier { private String text; protected MCRMockIdentifier(String text) { this.text = text; } @Override public String asString() { return this.text; } public static final String MOCK_SCHEME = "MOCK:"; }
1,060
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMockResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRMockResolver.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.pi; import java.util.stream.Stream; public class MCRMockResolver extends MCRPIResolver<MCRMockIdentifier> { public static final String NAME = "MOCK-Resolver"; public MCRMockResolver() { super(NAME); } @Override public Stream<String> resolve(MCRMockIdentifier identifier) { return Stream.of(identifier.asString()); } }
1,109
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRGenericPIGeneratorTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRGenericPIGeneratorTest.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.pi; import static org.junit.Assert.assertEquals; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.Map; import org.jdom2.Element; import org.junit.Test; import org.mycore.common.MCRStoreTestCase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public class MCRGenericPIGeneratorTest extends MCRStoreTestCase { public static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); @Test public void testGenerate() throws MCRPersistentIdentifierException { final MCRGenericPIGenerator generator = new MCRGenericPIGenerator( "urn:nbn:de:gbv:$CurrentDate-$1-$2-$ObjectType-$ObjectProject-$ObjectNumber-$Count-", new SimpleDateFormat("yyyy", Locale.ROOT), null, null, 3, "dnbUrn", "/mycoreobject/metadata/test1/test2/text()", "/mycoreobject/metadata/test1/test3/text()"); //generator.init(MCRPIService.GENERATOR_CONFIG_PREFIX + "test1"); MCRObjectID testID = MCRObjectID.getInstance("my_test_00000001"); MCRObject mcrObject = new MCRObject(); mcrObject.setSchema("test"); mcrObject.setId(testID); final Element metadata = new Element("metadata"); final Element testElement = new Element("test1"); metadata.addContent(testElement); testElement.setAttribute("class", "MCRMetaXML"); testElement.addContent(new Element("test2").setText("result1")); testElement.addContent(new Element("test3").setText("result2")); mcrObject.getMetadata().setFromDOM(metadata); final String pi1 = generator.generate(mcrObject, "").asString(); final String pi2 = generator.generate(mcrObject, "").asString(); assertEquals("urn:nbn:de:gbv:" + CURRENT_YEAR + "-result1-result2-test-my-00000001-000-", pi1.substring(0, pi1.length() - 1)); assertEquals("urn:nbn:de:gbv:" + CURRENT_YEAR + "-result1-result2-test-my-00000001-001-", pi2.substring(0, pi2.length() - 1)); } @Override protected Map<String, String> getTestProperties() { final Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString()); return testProperties; } }
3,155
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMockIdentifierParser.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/MCRMockIdentifierParser.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.pi; import java.util.Optional; public class MCRMockIdentifierParser implements MCRPIParser<MCRPersistentIdentifier> { @Override public Optional<MCRPersistentIdentifier> parse(String identifier) { if (!identifier.startsWith(MCRMockIdentifier.MOCK_SCHEME)) { return Optional.empty(); } return Optional.of(new MCRMockIdentifier(identifier)); } }
1,141
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDNBURNGeneratorTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/urn/MCRDNBURNGeneratorTest.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.pi.urn; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mycore.access.MCRAccessBaseImpl; import org.mycore.common.MCRStoreTestCase; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; public class MCRDNBURNGeneratorTest extends MCRStoreTestCase { private static final String GENERATOR_ID = "TESTDNBURN1"; private static final Logger LOGGER = LogManager.getLogger(); @Rule public TemporaryFolder baseDir = new TemporaryFolder(); @Test public void generate() throws Exception { MCRObjectID getID = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("test", "mock"); MCRObject mcrObject1 = new MCRObject(); mcrObject1.setId(getID); MCRFLURNGenerator flGenerator = (MCRFLURNGenerator) MCRConfiguration2 .getInstanceOf("MCR.PI.Generator." + GENERATOR_ID).get(); MCRDNBURN generated = flGenerator.generate(mcrObject1, ""); String urn = generated.asString(); LOGGER.info("THE URN IS: {}", urn); Assert.assertFalse(urn.startsWith("urn:nbn:de:urn:nbn:de")); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName()); testProperties.put("MCR.Metadata.Type.mock", "true"); testProperties.put("MCR.Metadata.Type.unregisterd", "true"); testProperties.put("MCR.PI.Generator." + GENERATOR_ID, MCRFLURNGenerator.class.getName()); testProperties.put("MCR.PI.Generator." + GENERATOR_ID + ".Namespace", "urn:nbn:de:gbv"); return testProperties; } }
2,747
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURNGranularRESTServiceTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/urn/rest/MCRURNGranularRESTServiceTest.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.pi.urn.rest; import java.nio.file.Files; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.function.Function; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.mycore.access.MCRAccessBaseImpl; import org.mycore.access.strategies.MCRAccessCheckStrategy; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRStoreTestCase; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventManager; import org.mycore.datamodel.common.MCRXMLMetadataEventHandler; 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; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.pi.MCRPIRegistrationInfo; import org.mycore.pi.urn.MCRDNBURN; import org.mycore.pi.urn.MCRUUIDURNGenerator; /** * Created by chi on 09.03.17. * @author Huu Chi Vu */ public class MCRURNGranularRESTServiceTest extends MCRStoreTestCase { private static Logger LOGGER = LogManager.getLogger(); private int numOfDerivFiles = 15; private MCRObject object; private MCRDerivate derivate; @Override public void setUp() throws Exception { super.setUp(); MCREventManager.instance().clear().addEventHandler(MCREvent.ObjectType.OBJECT, new MCRXMLMetadataEventHandler()); } @Test public void fullRegister() throws Exception { LOGGER.info("Store BaseDir {}", getStoreBaseDir()); LOGGER.info("Store SVN Base {}", getSvnBaseDir()); object = createObject(); derivate = createDerivate(object.getId()); MCRMetadataManager.create(object); MCRMetadataManager.create(derivate); List<MCRPath> fileList = new ArrayList<>(); for (int j = 0; j < numOfDerivFiles; j++) { String fileName = UUID.randomUUID() + "_" + String.format(Locale.getDefault(), "%02d", j); MCRPath path = MCRPath.getPath(derivate.getId().toString(), fileName); fileList.add(path); if (!Files.exists(path)) { Files.createFile(path); derivate.getDerivate().getOrCreateFileMetadata(path); } } Function<MCRDerivate, Stream<MCRPath>> foo = deriv -> fileList.stream(); String serviceID = "TestService"; MCRURNGranularRESTService testService = new MCRURNGranularRESTService(foo); testService.init("MCR.PI.Service.TestService"); testService.setProperties(getTestServiceProperties()); testService.register(derivate, "", true); timerTask(); List<MCRPIRegistrationInfo> registeredURNs = MCREntityManagerProvider .getEntityManagerFactory() .createEntityManager() .createNamedQuery("Get.PI.Created", MCRPIRegistrationInfo.class) .setParameter("mcrId", derivate.getId().toString()) .setParameter("type", MCRDNBURN.TYPE) .setParameter("service", serviceID) .getResultList(); registeredURNs.stream() .forEach(pi -> LOGGER.info("URN: {}", pi)); Assert.assertEquals("Wrong number of registered URNs: ", numOfDerivFiles + 1, registeredURNs.size()); } public void timerTask() throws Exception { System.out.println("Start: " + new Date()); new MCRURNGranularRESTRegistrationCronjob().runJob(); System.out.println("End: " + new Date()); } protected Map<String, String> getTestServiceProperties() { HashMap<String, String> serviceProps = new HashMap<>(); serviceProps.put("Generator", "UUID"); serviceProps.put("supportDfgViewerURN", Boolean.TRUE.toString()); return serviceProps; } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.datadir", "%MCR.basedir%/data"); testProperties .put("MCR.Persistence.LinkTable.Store.Class", "org.mycore.backend.hibernate.MCRHIBLinkTableStore"); testProperties.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName()); testProperties.put("MCR.Access.Strategy.Class", AlwaysTrueStrategy.class.getName()); testProperties.put("MCR.Metadata.Type.object", "true"); testProperties.put("MCR.Metadata.Type.derivate", "true"); testProperties.put("MCR.IFS2.Store.mycore_derivate.Class", "org.mycore.datamodel.ifs2.MCRMetadataStore"); //testProperties.put("MCR.IFS2.Store.mycore_derivate.BaseDir","/foo"); testProperties.put("MCR.IFS2.Store.mycore_derivate.SlotLayout", "4-2-2"); testProperties.put("MCR.EventHandler.MCRDerivate.020.Class", "org.mycore.datamodel.common.MCRXMLMetadataEventHandler"); testProperties.put("MCR.EventHandler.MCRDerivate.030.Class", "org.mycore.datamodel.common.MCRLinkTableEventHandler"); testProperties.put("MCR.IFS.ContentStore.IFS2.BaseDir", getStoreBaseDir().toString()); testProperties.put("MCR.PI.Generator.UUID", MCRUUIDURNGenerator.class.getName()); testProperties.put("MCR.PI.Generator.UUID.Namespace", "frontend-"); testProperties.put("MCR.PI.DNB.Credentials.Login", "test"); testProperties.put("MCR.PI.DNB.Credentials.Password", "test"); return testProperties; } public static MCRDerivate createDerivate(MCRObjectID objectHrefId) { MCRDerivate derivate = new MCRDerivate(); derivate.setId(MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("mycore_derivate")); derivate.setSchema("datamodel-derivate.xsd"); MCRMetaIFS ifs = new MCRMetaIFS(); ifs.setSubTag("internal"); ifs.setSourcePath(MCRPath.getPath(derivate.getId().toString(), "/").toAbsolutePath().toString()); derivate.getDerivate().setInternals(ifs); MCRMetaLinkID mcrMetaLinkID = new MCRMetaLinkID(); mcrMetaLinkID.setReference(objectHrefId.toString(), null, null); derivate.getDerivate().setLinkMeta(mcrMetaLinkID); return derivate; } public static MCRObject createObject() { MCRObject object = new MCRObject(); object.setId(MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("mycore_object")); object.setSchema("noSchema"); return object; } @After public void tearDown() throws Exception { MCRMetadataManager.delete(derivate); MCRMetadataManager.delete(object); super.tearDown(); } public static class AlwaysTrueStrategy implements MCRAccessCheckStrategy { @Override public boolean checkPermission(String id, String permission) { return true; } } }
7,940
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURNGranularRESTRegistrationTaskTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/urn/rest/MCRURNGranularRESTRegistrationTaskTest.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.pi.urn.rest; import static org.mycore.pi.MCRPIUtils.generateMCRPI; import static org.mycore.pi.MCRPIUtils.randomFilename; import java.util.Date; import java.util.Map; import java.util.Optional; import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRStoreTestCase; import org.mycore.pi.MCRPIManager; import org.mycore.pi.MCRPIRegistrationInfo; import org.mycore.pi.MCRPIUtils; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.urn.MCRDNBURN; /** * Created by chi on 23.02.17. * * @author Huu Chi Vu */ public class MCRURNGranularRESTRegistrationTaskTest extends MCRStoreTestCase { private static final String countRegistered = "select count(u) from MCRPI u " + "where u.type = :type " + "and u.registered is not null"; public static final int BATCH_SIZE = 20; private static final Logger LOGGER = LogManager.getLogger(); @Override public void setUp() throws Exception { super.setUp(); } @Ignore @Test public void run() throws Exception { MCRPI urn1 = generateMCRPI(randomFilename(), countRegistered); MCREntityManagerProvider.getCurrentEntityManager() .persist(urn1); Assert.assertNull("Registered date should be null.", urn1.getRegistered()); MCRPIManager.getInstance() .getUnregisteredIdentifiers(urn1.getType()) .stream() .map(MCRPIRegistrationInfo::getIdentifier) .map("URN: "::concat) .forEach(LOGGER::info); Integer progressedIdentifiersFromDatabase; Function<MCRPIRegistrationInfo, Optional<Date>> registerFn = MCRPIUtils.getMCRURNClient()::register; do { progressedIdentifiersFromDatabase = MCRPIManager.getInstance() .setRegisteredDateForUnregisteredIdentifiers(MCRDNBURN.TYPE, registerFn, BATCH_SIZE); } while (progressedIdentifiersFromDatabase > 0); boolean registered = MCRPIManager.getInstance().isRegistered(urn1); LOGGER.info("Registered: {}", registered); MCRPI mcrpi = MCREntityManagerProvider.getCurrentEntityManager().find(MCRPI.class, urn1.getId()); Optional.ofNullable(mcrpi) .filter(pi -> pi.getRegistered() != null) .map(MCRPI::getRegistered) .map(Date::toString) .map("URN registered: "::concat) .ifPresent(LOGGER::info); MCRPIManager.getInstance().getUnregisteredIdentifiers(urn1.getType()) .stream() .map(MCRPIRegistrationInfo::getIdentifier) .map("URN update: "::concat) .forEach(LOGGER::info); LOGGER.info("end."); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString()); testProperties.put("MCR.PI.Generator.testGenerator.Namespace", "frontend-"); return testProperties; } @After public void tearDown() throws Exception { super.tearDown(); } }
4,082
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDOIParserTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/doi/MCRDOIParserTest.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.pi.doi; import java.util.Optional; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRDOIParserTest extends MCRTestCase { public static final String EXAMPLE_DOI2_PREFIX = "10.22032.0"; public static final String EXAMPLE_DOI2_SUFFIX = "hj34"; private static final String EXAMPLE_DOI1_PREFIX = "10.1000"; private static final String EXAMPLE_DOI1_SUFFIX = "123456"; private static final String EXAMPLE_DOI1 = EXAMPLE_DOI1_PREFIX + "/" + EXAMPLE_DOI1_SUFFIX; private static final String EXAMPLE_DOI2 = EXAMPLE_DOI2_PREFIX + "/" + EXAMPLE_DOI2_SUFFIX; private static MCRDOIParser parser; private static void testDOI(String doi, String expectedPrefix, String expectedSuffix) { Optional<MCRDigitalObjectIdentifier> parsedDOIOptional = parser.parse(doi); Assert.assertTrue("DOI should be parsable!", parsedDOIOptional.isPresent()); MCRDigitalObjectIdentifier parsedDOI = parsedDOIOptional.get(); Assert.assertEquals("DOI Prefix should match!", expectedPrefix, parsedDOI.getPrefix()); Assert.assertEquals("DOI Suffix should match", expectedSuffix, parsedDOI.getSuffix()); } @Before public void setUp() throws Exception { super.setUp(); parser = new MCRDOIParser(); } @Test public void parseRegularDOITest() { testDOI(EXAMPLE_DOI1, EXAMPLE_DOI1_PREFIX, EXAMPLE_DOI1_SUFFIX); } @Test public void parseRegistrantCodeDOI() { testDOI(EXAMPLE_DOI2, EXAMPLE_DOI2_PREFIX, EXAMPLE_DOI2_SUFFIX); } @After public void tearDown() throws Exception { super.tearDown(); } }
2,504
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDOIServiceTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/doi/MCRDOIServiceTest.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.pi.doi; import javax.xml.validation.Schema; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRTestCase; public class MCRDOIServiceTest extends MCRTestCase { @Test public void testSchemaV3() { Assert.assertNotNull(loadSchema("xsd/datacite/v3/metadata.xsd")); Assert.assertNotNull(loadSchema(MCRDOIService.DATACITE_SCHEMA_V3)); } @Test public void testSchemaV4() { Assert.assertNotNull(loadSchema("xsd/datacite/v4/metadata.xsd")); Assert.assertNotNull(loadSchema(MCRDOIService.DATACITE_SCHEMA_V4)); } @Test public void testSchemaV41() { Assert.assertNotNull(loadSchema("xsd/datacite/v4.1/metadata.xsd")); Assert.assertNotNull(loadSchema(MCRDOIService.DATACITE_SCHEMA_V41)); } @Test public void testSchemaV43() { Assert.assertNotNull(loadSchema("xsd/datacite/v4.3/metadata.xsd")); Assert.assertNotNull(loadSchema(MCRDOIService.DATACITE_SCHEMA_V43)); } @Test public void testCrossrefSchema() { Assert.assertNotNull(loadSchema("xsd/crossref/4.4.1/crossref4.4.1.xsd")); Assert.assertNotNull(loadSchema(MCRCrossrefService.DEFAULT_SCHEMA)); } private Schema loadSchema(String schemaURL) { return MCRDOIBaseService.resolveSchema(schemaURL); } }
2,074
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMapObjectIDDOIGeneratorTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/doi/MCRMapObjectIDDOIGeneratorTest.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.pi.doi; import static org.junit.Assert.assertEquals; import static org.mycore.pi.doi.MCRDigitalObjectIdentifier.TEST_DOI_PREFIX; import java.util.Map; import org.junit.After; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; /** * @author Thomas Scheffler (yagee) */ public class MCRMapObjectIDDOIGeneratorTest extends MCRTestCase { MCRMapObjectIDDOIGenerator doiGenerator; @Override public void setUp() throws Exception { super.setUp(); doiGenerator = (MCRMapObjectIDDOIGenerator) MCRConfiguration2.getInstanceOf("MCR.PI.Generator.MapObjectIDDOI") .get(); } @Test public void generate() throws Exception { MCRObjectID testID1 = MCRObjectID.getInstance("junit_test_00004711"); MCRObject mcrObject1 = new MCRObject(); mcrObject1.setId(testID1); MCRObjectID testID2 = MCRObjectID.getInstance("my_test_00000815"); MCRObject mcrObject2 = new MCRObject(); mcrObject2.setId(testID2); assertEquals(TEST_DOI_PREFIX + "/4711", doiGenerator.generate(mcrObject1, null).asString()); assertEquals(TEST_DOI_PREFIX + "/my.815", doiGenerator.generate(mcrObject2, null).asString()); } @Test(expected = MCRPersistentIdentifierException.class) public void missingMappingTest() throws Exception { MCRObjectID testID = MCRObjectID.getInstance("brandNew_test_00000001"); MCRObject mcrObject = new MCRObject(); mcrObject.setId(testID); doiGenerator.generate(mcrObject, null); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString()); testProperties.put("MCR.PI.Generator.MapObjectIDDOI", MCRMapObjectIDDOIGenerator.class.getName()); testProperties.put("MCR.PI.Generator.MapObjectIDDOI.Prefix.junit_test", TEST_DOI_PREFIX); testProperties.put("MCR.PI.Generator.MapObjectIDDOI.Prefix.my_test", TEST_DOI_PREFIX + "/my."); return testProperties; } @After public void tearDown() throws Exception { super.tearDown(); } }
3,160
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIDPURLGeneratorTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/purl/MCRIDPURLGeneratorTest.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.pi.purl; import static org.mycore.pi.MCRPIService.GENERATOR_CONFIG_PREFIX; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public class MCRIDPURLGeneratorTest extends MCRTestCase { private static final String TEST_BASE_1 = "http://purl.myurl.de/$ID"; private static final String TEST_BASE_2 = "http://purl.myurl.de/$ID/$ID/$ID"; private static final String GENERATOR_1 = "IDPURLGenerator"; private static final String GENERATOR_2 = GENERATOR_1 + "2"; @Test public void generate() throws MCRPersistentIdentifierException { MCRObjectID testID = MCRObjectID.getInstance("my_test_00000001"); MCRObject mcrObject = new MCRObject(); mcrObject.setId(testID); MCRIDPURLGenerator generator1 = (MCRIDPURLGenerator) MCRConfiguration2 .getInstanceOf(GENERATOR_CONFIG_PREFIX + GENERATOR_1).get(); Assert.assertEquals("", generator1.generate(mcrObject, "").asString(), "http://purl.myurl.de/my_test_00000001"); MCRIDPURLGenerator generator2 = (MCRIDPURLGenerator) MCRConfiguration2 .getInstanceOf(GENERATOR_CONFIG_PREFIX + GENERATOR_2).get(); Assert.assertEquals("", generator2.generate(mcrObject, "").asString(), "http://purl.myurl.de/my_test_00000001/my_test_00000001/my_test_00000001"); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString()); testProperties.put(GENERATOR_CONFIG_PREFIX + GENERATOR_1, MCRIDPURLGenerator.class.getName()); testProperties.put(GENERATOR_CONFIG_PREFIX + GENERATOR_1 + ".BaseURLTemplate", TEST_BASE_1); testProperties.put(GENERATOR_CONFIG_PREFIX + GENERATOR_2, MCRIDPURLGenerator.class.getName()); testProperties.put(GENERATOR_CONFIG_PREFIX + GENERATOR_2 + ".BaseURLTemplate", TEST_BASE_2); return testProperties; } }
3,003
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIAndPredicateTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/condition/MCRPIAndPredicateTest.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.pi.condition; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.MCRTestConfiguration; import org.mycore.common.MCRTestProperty; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.MCRPIJobService; @MCRTestConfiguration(properties = { @MCRTestProperty(key = "MCR.Metadata.Type.test", string = "true") }) public class MCRPIAndPredicateTest extends MCRTestCase { private static final String KEY_CREATION_PREDICATE = "MCR.PI.Service.Mock.CreationPredicate"; private static final String KEY_CREATION_PREDICATE_1 = KEY_CREATION_PREDICATE + ".1"; private static final String KEY_CREATION_PREDICATE_1_1 = KEY_CREATION_PREDICATE + ".1.1"; private static final String KEY_CREATION_PREDICATE_1_2 = KEY_CREATION_PREDICATE + ".1.2"; private static final String KEY_CREATION_PREDICATE_2 = KEY_CREATION_PREDICATE + ".2"; @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIAndPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRTruePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRTruePredicate.class) }) public void testTrueAndTrue() { Assert.assertTrue(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIAndPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRTruePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRFalsePredicate.class) }) public void testTrueAndFalse() { Assert.assertFalse(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIAndPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRPIAndPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_1, classNameOf = MCRTruePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_2, classNameOf = MCRTruePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRTruePredicate.class) }) public void testNestedTrueAndTrue() { Assert.assertTrue(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIAndPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRPIAndPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_1, classNameOf = MCRTruePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_2, classNameOf = MCRFalsePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRFalsePredicate.class) }) public void testNestedTrueAndFalse() { Assert.assertFalse(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } private static MCRObject getTestObject() { MCRObject mcrObject = new MCRObject(); mcrObject.setSchema("test"); mcrObject.setId(MCRObjectID.getInstance("mcr_test_00000001")); return mcrObject; } }
4,357
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIXPathPredicateTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/condition/MCRPIXPathPredicateTest.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.pi.condition; import org.jdom2.Element; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.MCRTestConfiguration; import org.mycore.common.MCRTestProperty; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.MCRPIJobService; @MCRTestConfiguration(properties = { @MCRTestProperty(key = "MCR.Metadata.Type.test", string = "true") }) public class MCRPIXPathPredicateTest extends MCRTestCase { private static final String KEY_CREATION_PREDICATE = "MCR.PI.Service.Mock.CreationPredicate"; private static final String KEY_CREATION_PREDICATE_XPATH = KEY_CREATION_PREDICATE + ".XPath"; @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIXPathPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_XPATH, string = "/mycoreobject/metadata/test") }) public void testMetadataRootElement() { Assert.assertTrue(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIXPathPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_XPATH, string = "/mycoreobject/metadata/foo") }) public void testMetadataWrongRootElement() { Assert.assertFalse(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIXPathPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_XPATH, string = "/mycoreobject/metadata/test/foo") }) public void testMetadataNestedElement() { Assert.assertTrue(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIXPathPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_XPATH, string = "false()") }) public void testFasle() { Assert.assertFalse(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIXPathPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_XPATH, string = "true()") }) public void testTrue() { Assert.assertTrue(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } private static MCRObject getTestObject() { Element testElement = new Element("test"); testElement.setAttribute("class", "MCRMetaXML"); testElement.addContent(new Element("foo").setText("result1")); testElement.addContent(new Element("bar").setText("result2")); Element metadataElement = new Element("metadata"); metadataElement.addContent(testElement); MCRObject mcrObject = new MCRObject(); mcrObject.setSchema("test"); mcrObject.setId(MCRObjectID.getInstance("mcr_test_00000001")); mcrObject.getMetadata().setFromDOM(metadataElement); return mcrObject; } }
4,160
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFalsePredicate.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/condition/MCRFalsePredicate.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.pi.condition; import org.mycore.datamodel.metadata.MCRBase; public class MCRFalsePredicate extends MCRPIPredicateBase { @Override public boolean test(MCRBase mcrBase) { return false; } }
957
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTruePredicate.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/condition/MCRTruePredicate.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.pi.condition; import org.mycore.datamodel.metadata.MCRBase; public class MCRTruePredicate extends MCRPIPredicateBase { @Override public boolean test(MCRBase mcrBase) { return true; } }
955
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIOrPredicateTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/test/java/org/mycore/pi/condition/MCRPIOrPredicateTest.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.pi.condition; import org.junit.Assert; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.MCRTestConfiguration; import org.mycore.common.MCRTestProperty; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.MCRPIJobService; @MCRTestConfiguration(properties = { @MCRTestProperty(key = "MCR.Metadata.Type.test", string = "true") }) public class MCRPIOrPredicateTest extends MCRTestCase { private static final String KEY_CREATION_PREDICATE = "MCR.PI.Service.Mock.CreationPredicate"; private static final String KEY_CREATION_PREDICATE_1 = KEY_CREATION_PREDICATE + ".1"; private static final String KEY_CREATION_PREDICATE_1_1 = KEY_CREATION_PREDICATE + ".1.1"; private static final String KEY_CREATION_PREDICATE_1_2 = KEY_CREATION_PREDICATE + ".1.2"; private static final String KEY_CREATION_PREDICATE_2 = KEY_CREATION_PREDICATE + ".2"; @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIOrPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRFalsePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRFalsePredicate.class) }) public void testFalseOrFalse() { Assert.assertFalse(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIOrPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRFalsePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRTruePredicate.class) }) public void testFalseOrTrue() { Assert.assertTrue(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIOrPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRPIOrPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_1, classNameOf = MCRFalsePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_2, classNameOf = MCRFalsePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRFalsePredicate.class) }) public void testNestedFalseOrFalse() { Assert.assertFalse(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = KEY_CREATION_PREDICATE, classNameOf = MCRPIOrPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1, classNameOf = MCRPIOrPredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_1, classNameOf = MCRFalsePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_1_2, classNameOf = MCRTruePredicate.class), @MCRTestProperty(key = KEY_CREATION_PREDICATE_2, classNameOf = MCRFalsePredicate.class) }) public void testNestedFalseOrTrue() { Assert.assertTrue(MCRPIJobService.getPredicateInstance(KEY_CREATION_PREDICATE).test(getTestObject())); } private static MCRObject getTestObject() { MCRObject mcrObject = new MCRObject(); mcrObject.setSchema("test"); mcrObject.setId(MCRObjectID.getInstance("mcr_test_00000001")); return mcrObject; } }
4,355
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIConfigurationChecker.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIConfigurationChecker.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.pi; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; 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.common.events.MCRStartupHandler; import jakarta.servlet.ServletContext; /** * Checks deprecated properties and the configuration of {@link MCRPIService}s on startup */ public class MCRPIConfigurationChecker implements MCRStartupHandler.AutoExecutable { protected static final List<String> DEPRECATED_PROPERTY_PREFIXES = Stream.of("MCR.PI.MetadataManager.", "MCR.PI.Inscriber.", "MCR.PI.Registration.").collect(Collectors.toList()); private static final Logger LOGGER = LogManager.getLogger(); @Override public String getName() { return "ConfigurationChecker"; } @Override public int getPriority() { return 0; } @Override public void startUp(ServletContext servletContext) { LOGGER.info("Check persistent identifier configuration!"); final List<String> deprecatedPropertyList = DEPRECATED_PROPERTY_PREFIXES .stream() .flatMap(propPrefix -> MCRConfiguration2.getPropertiesMap() .entrySet() .stream() .filter(p -> p.getKey().startsWith(propPrefix)) .map(Map.Entry::getKey)) .collect(Collectors.toList()); if (deprecatedPropertyList.size() > 0) { throw new MCRConfigurationException("Deprecated properties found: " + deprecatedPropertyList .stream() .collect(Collectors.joining(System.lineSeparator()))); } // check service configuration final MCRPIServiceManager serviceManager = MCRPIServiceManager.getInstance(); serviceManager.getServiceList().forEach(service -> { LOGGER.info("Check service: " + service.getServiceID()); service.checkConfiguration(); }); } }
2,849
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIService.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.pi; import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRCoreVersion; import org.mycore.common.MCRException; import org.mycore.common.MCRGsonUTCDateAdapter; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.config.annotation.MCRPostConstruction; import org.mycore.common.config.annotation.MCRProperty; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.MCRObjectService; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.doi.MCRDOIService; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; import org.mycore.services.i18n.MCRTranslation; import org.mycore.util.concurrent.MCRFixedUserCallable; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public abstract class MCRPIService<T extends MCRPersistentIdentifier> { public static final String REGISTRATION_CONFIG_PREFIX = "MCR.PI.Service."; public static final String GENERATOR_CONFIG_PREFIX = "MCR.PI.Generator."; public static final String METADATA_SERVICE_CONFIG_PREFIX = "MCR.PI.MetadataService."; public static final String PI_FLAG = "MyCoRe-PI"; public static final String GENERATOR_PROPERTY_KEY = "Generator"; protected static final String METADATA_SERVICE_PROPERTY_KEY = "MetadataService"; protected static final String TRANSLATE_PREFIX = "component.pi.register.error."; private String registrationServiceID; private final String type; private static final ExecutorService REGISTER_POOL; static { ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("MCRPIRegister-#%d") .build(); REGISTER_POOL = Executors.newFixedThreadPool(1, threadFactory); } private Map<String, String> properties; public MCRPIService(String identifierType) { this.type = identifierType; } @MCRPostConstruction public void init(String prop) { registrationServiceID = prop.substring(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX.length()); } // generated identifier is already present in database private static final int ERR_CODE_0_1 = 0x0001; @SuppressWarnings("unused") private static Logger LOGGER = LogManager.getLogger(); protected static Gson getGson() { return new GsonBuilder().registerTypeAdapter(Date.class, new MCRGsonUTCDateAdapter()) .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { String name = fieldAttributes.getName(); return Stream.of("mcrRevision", "mycoreID", "id", "mcrVersion") .anyMatch(field -> field.equals(name)); } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }).create(); } public final String getServiceID() { return registrationServiceID; } /** * Checks the service parameters. * * @throws MCRConfigurationException if parameter is missing or wrong! */ protected void checkConfiguration() throws MCRConfigurationException { if (getProperties().containsKey("MetadataManager")) { throw new MCRConfigurationException("The MCRPIService " + getServiceID() + " uses old property key MetadataManager"); } getGenerator(); getMetadataService(); } public MCRPIMetadataService<T> getMetadataService() { Map<String, String> properties = getProperties(); final String metadataService; if (properties.containsKey(METADATA_SERVICE_PROPERTY_KEY)) { metadataService = properties.get(METADATA_SERVICE_PROPERTY_KEY); } else { throw new MCRConfigurationException( getServiceID() + " has no " + METADATA_SERVICE_PROPERTY_KEY + "!"); } String msProperty = METADATA_SERVICE_CONFIG_PREFIX + metadataService; MCRPIMetadataService<T> mdService = MCRConfiguration2.<MCRPIMetadataService<T>>getInstanceOf(msProperty) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(msProperty)); return mdService; } protected MCRPIGenerator<T> getGenerator() { Supplier<? extends RuntimeException> generatorPropertiesNotSetError = () -> new MCRConfigurationException( "Configuration property " + REGISTRATION_CONFIG_PREFIX + registrationServiceID + "." + GENERATOR_PROPERTY_KEY + " is not set"); String generatorName = Optional.ofNullable(getProperties().get(GENERATOR_PROPERTY_KEY)) .orElseThrow(generatorPropertiesNotSetError); String generatorPropertyKey = GENERATOR_CONFIG_PREFIX + generatorName; MCRPIGenerator<T> generator = MCRConfiguration2.<MCRPIGenerator<T>>getInstanceOf(generatorPropertyKey) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(generatorPropertyKey)); return generator; } public static void addFlagToObject(MCRBase obj, MCRPI databaseEntry) { String json = getGson().toJson(databaseEntry); obj.getService().addFlag(PI_FLAG, json); } /** * Removes a flag from a {@link MCRObject} * * @param obj the object * @param databaseEntry the database entry * @return the remove entry parsed from json or null */ public static MCRPI removeFlagFromObject(MCRBase obj, MCRPI databaseEntry) { MCRObjectService service = obj.getService(); ArrayList<String> flags = service.getFlags(MCRPIService.PI_FLAG); int flagCount = flags.size(); for (int flagIndex = 0; flagIndex < flagCount; flagIndex++) { String flag = flags.get(flagIndex); MCRPI pi = getGson().fromJson(flag, MCRPI.class); if (pi.getIdentifier().equals(databaseEntry.getIdentifier()) && pi.getAdditional().equals(databaseEntry.getAdditional()) && pi.getService().equals(databaseEntry.getService()) && pi.getType().equals(databaseEntry.getType())) { service.removeFlag(flagIndex); return databaseEntry; } } return null; } public static boolean hasFlag(MCRObjectID id, String additional, MCRPIRegistrationInfo mcrpi) { MCRBase obj = MCRMetadataManager.retrieve(id); return hasFlag(obj, additional, mcrpi); } public static boolean hasFlag(MCRBase obj, String additional, MCRPIRegistrationInfo mcrpi) { MCRObjectService service = obj.getService(); ArrayList<String> flags = service.getFlags(MCRPIService.PI_FLAG); Gson gson = getGson(); return flags.stream().anyMatch(_stringFlag -> { MCRPI flag = gson.fromJson(_stringFlag, MCRPI.class); return flag.getAdditional().equals(additional) && flag.getIdentifier().equals(mcrpi.getIdentifier()); }); } public static boolean hasFlag(MCRBase obj, String additional, MCRPIService<?> piService) { MCRObjectService service = obj.getService(); ArrayList<String> flags = service.getFlags(MCRPIService.PI_FLAG); Gson gson = getGson(); return flags.stream().anyMatch(_stringFlag -> { MCRPI flag = gson.fromJson(_stringFlag, MCRPI.class); return flag.getAdditional().equals(additional) && Objects.equals(flag.getService(), piService.getServiceID()); }); } protected void validatePermission(MCRBase obj, boolean writePermission) throws MCRAccessException { List<String> requiredPermissions = new ArrayList<>(writePermission ? 2 : 1); requiredPermissions.add("register-" + getServiceID()); if (writePermission) { requiredPermissions.add(PERMISSION_WRITE); } Optional<String> missingPermission = requiredPermissions.stream() .filter(permission -> !MCRAccessManager.checkPermission(obj.getId(), permission)) .findFirst(); if (missingPermission.isPresent()) { throw MCRAccessException .missingPermission("Register a " + type + " & Update object.", obj.getId().toString(), missingPermission.get()); } } protected void validateAlreadyCreated(MCRObjectID id, String additional) throws MCRPersistentIdentifierException { if (isCreated(id, additional)) { throw new MCRPersistentIdentifierException("There is already a registered " + getType() + " for Object " + id + " and additional " + additional); } } /** * Validates if an object can get an Identifier assigned from this service! <b>Better call super when overwrite!</b> * * @throws MCRPersistentIdentifierException * see {@link org.mycore.pi.exceptions} * @throws MCRAccessException * if the user does not have the rights to assign a pi to the specific object */ public void validateRegistration(MCRBase obj, String additional) throws MCRPersistentIdentifierException, MCRAccessException { validateRegistration(obj, additional, true); } public void validateRegistration(MCRBase obj, String additional, boolean checkWritePermission) throws MCRPersistentIdentifierException, MCRAccessException { validateAlreadyCreated(obj.getId(), additional); validatePermission(obj, checkWritePermission); } /** * shorthand for {@link #register(MCRBase, String, boolean)} with update = true */ public T register(MCRBase obj, String additional) throws MCRAccessException, MCRPersistentIdentifierException, ExecutionException, InterruptedException { return register(obj, additional, true); } /** * Adds a identifier to the object. * Validates everything, registers a new Identifier, inserts the identifier to object metadata and writes a * information to the Database. * * @param obj the object which has to be identified * @return the assigned Identifier * @throws MCRAccessException * the current User doesn't have the rights to insert the Identifier to Metadata * @throws MCRPersistentIdentifierException see {@link org.mycore.pi.exceptions} */ public T register(MCRBase obj) throws MCRAccessException, MCRPersistentIdentifierException, ExecutionException, InterruptedException { return this.register(obj, null); } /** * Validates everything, registers a new Identifier, inserts the identifier to object metadata and writes a * information to the Database. * * @param obj the object which has to be identified * @param additional additional information for the persistent identifier * @param updateObject if true this method calls {@link MCRMetadataManager#update(MCRBase)} * @return the assigned Identifier * @throws MCRAccessException * the current User doesn't have the rights to insert the Identifier to Metadata * @throws MCRPersistentIdentifierException * see {@link org.mycore.pi.exceptions} */ public T register(MCRBase obj, String additional, boolean updateObject) throws MCRAccessException, MCRPersistentIdentifierException, ExecutionException, InterruptedException { // There are many querys that require the current database state. // So we start a new transaction within the synchronized block final MCRFixedUserCallable<T> createPICallable = new MCRFixedUserCallable<>(() -> { this.validateRegistration(obj, additional, updateObject); final T identifier = getNewIdentifier(obj, additional); MCRPIServiceDates dates = this.registerIdentifier(obj, additional, identifier); this.getMetadataService().insertIdentifier(identifier, obj, additional); MCRPI databaseEntry = insertIdentifierToDatabase(obj, additional, identifier, dates); addFlagToObject(obj, databaseEntry); if (updateObject) { if (obj instanceof MCRObject object) { MCRMetadataManager.update(object); } else if (obj instanceof MCRDerivate derivate) { MCRMetadataManager.update(derivate); } } return identifier; }, MCRSessionMgr.getCurrentSession().getUserInformation()); try { return REGISTER_POOL.submit(createPICallable).get(); } catch (ExecutionException e) { if (e.getCause() instanceof MCRPersistentIdentifierException pie) { throw pie; } throw e; } } public MCRPI insertIdentifierToDatabase(MCRBase obj, String additional, T identifier, MCRPIServiceDates registrationDates) { MCRPI databaseEntry = new MCRPI(identifier.asString(), getType(), obj.getId().toString(), additional, this.getServiceID(), registrationDates); MCREntityManagerProvider.getCurrentEntityManager().persist(databaseEntry); return databaseEntry; } public static void updateFlagsInDatabase(MCRBase obj) { Gson gson = MCRPIService.getGson(); obj.getService().getFlags(MCRPIService.PI_FLAG).stream() .map(piFlag -> gson.fromJson(piFlag, MCRPI.class)) .map(entry -> { // disabled: Git does not provide a revision number as integer (see MCR-1393) // entry.setMcrRevision(MCRCoreVersion.getRevision()); entry.setMcrVersion(MCRCoreVersion.getVersion()); entry.setMycoreID(obj.getId().toString()); return entry; }) .filter(entry -> !MCRPIManager.getInstance().exist(entry)) .forEach(entry -> { LOGGER.info("Add PI : {} with service {} to database!", entry.getIdentifier(), entry.getService()); MCREntityManagerProvider.getCurrentEntityManager().persist(entry); }); } public final String getType() { return this.type; } protected abstract MCRPIServiceDates registerIdentifier(MCRBase obj, String additional, T pi) throws MCRPersistentIdentifierException; protected final void onDelete(T identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException { delete(identifier, obj, additional); MCRPIManager.getInstance().delete(obj.getId().toString(), additional, getType(), this.getServiceID()); } protected final void onUpdate(T identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException { update(identifier, obj, additional); } /** * Should handle deletion of a Object with the PI. * E.g. The {@link MCRDOIService} sets the active flag in Datacite datacentre to false. * * @param identifier the Identifier * @param obj the deleted object * @throws MCRPersistentIdentifierException * to abort deletion of the object or if something went wrong, (e.g. {@link MCRDOIService} throws if not a superuser * tries to delete the object) */ protected abstract void delete(T identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException; /** * Should handle updates of a Object with the PI. * E.g. The {@link MCRDOIService} sends the updated metadata to the Datacite datacentre. * * @param identifier the Identifier * @param obj the deleted object * @throws MCRPersistentIdentifierException to abort update of the object or if something went wrong. */ protected abstract void update(T identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException; public boolean isCreated(MCRObjectID id, String additional) { return MCRPIManager.getInstance().isCreated(id, additional, type, registrationServiceID); } public boolean isRegistered(MCRObjectID id, String additional) { return MCRPIManager.getInstance().isRegistered(id, additional, type, registrationServiceID); } public boolean hasRegistrationStarted(MCRObjectID id, String additional) { return MCRPIManager.getInstance() .hasRegistrationStarted(id, additional, type, registrationServiceID); } protected final Map<String, String> getProperties() { return properties; } @MCRProperty(name = "*") public void setProperties(Map<String, String> properties) { this.properties = properties; } protected T getNewIdentifier(MCRBase id, String additional) throws MCRPersistentIdentifierException { MCRPIGenerator<T> persitentIdentifierGenerator = getGenerator(); final T generated = persitentIdentifierGenerator.generate(id, additional); final String generatedIdentifier = generated.asString(); final Optional<MCRPIRegistrationInfo> mayInfo = MCRPIManager.getInstance() .getInfo(generatedIdentifier, getType()); if (mayInfo.isPresent()) { final String presentObject = mayInfo.get().getMycoreID(); throw new MCRPersistentIdentifierException( "The Generated identifier " + generatedIdentifier + " is already present in database in object " + presentObject, MCRTranslation.translate(TRANSLATE_PREFIX + ERR_CODE_0_1), ERR_CODE_0_1); } return generated; } protected MCRPI getTableEntry(MCRObjectID id, String additional) { return MCRPIManager.getInstance().get(getServiceID(), id.toString(), additional); } public void updateFlag(MCRObjectID id, String additional, MCRPI mcrpi) { MCRBase obj = MCRMetadataManager.retrieve(id); MCRObjectService service = obj.getService(); ArrayList<String> flags = service.getFlags(MCRPIService.PI_FLAG); Gson gson = getGson(); String stringFlag = flags.stream().filter(_stringFlag -> { MCRPI flag = gson.fromJson(_stringFlag, MCRPI.class); return Objects.equals(flag.getAdditional(), additional) && Objects .equals(flag.getIdentifier(), mcrpi.getIdentifier()); }).findAny().orElseThrow(() -> new MCRException(new MCRPersistentIdentifierException( "Could find flag to update (" + id + "," + additional + "," + mcrpi.getIdentifier() + ")"))); int flagIndex = service.getFlagIndex(stringFlag); service.removeFlag(flagIndex); addFlagToObject(obj, mcrpi); try { MCRMetadataManager.update(obj); } catch (Exception e) { throw new MCRException("Could not update flags of object " + id, e); } } /** * Validates a property of this service * @param propertyName the property to check * @return the property * @throws MCRConfigurationException if property is not set or empty */ protected String requireNotEmptyProperty(String propertyName) throws MCRConfigurationException { final Map<String, String> properties = getProperties(); if (!properties.containsKey(propertyName) || properties.get(propertyName) == null || properties.get(propertyName).isEmpty()) { throw new MCRConfigurationException(String .format(Locale.ROOT, "The property %s%s.%s is empty or not set!", REGISTRATION_CONFIG_PREFIX, registrationServiceID, propertyName)); } return properties.get(propertyName); } protected Predicate<MCRBase> getCreationPredicate() { final String predicateProperty = MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + getServiceID() + "." + MCRPIJobService.CREATION_PREDICATE; if (MCRConfiguration2.getString(predicateProperty).isEmpty()) { return (o) -> false; } return getPredicateInstance(predicateProperty); } protected Predicate<MCRBase> getRegistrationPredicate() { final String predicateProperty = MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + getServiceID() + "." + MCRPIJobService.REGISTRATION_PREDICATE; if (MCRConfiguration2.getString(predicateProperty).isEmpty()) { return (o) -> true; } return getPredicateInstance(predicateProperty); } public static Predicate<MCRBase> getPredicateInstance(String predicateProperty) { return MCRConfiguration2.<Predicate<MCRBase>>getInstanceOf(predicateProperty) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(predicateProperty)); } }
22,822
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPICreationEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPICreationEventHandler.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.pi; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.function.Predicate; import java.util.stream.Collectors; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRException; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public class MCRPICreationEventHandler extends MCREventHandlerBase { @Override protected void handleObjectCreated(MCREvent evt, MCRObject obj) { processPIServices(obj); } @Override protected void handleObjectUpdated(MCREvent evt, MCRObject obj) { processPIServices(obj); } private void processPIServices(MCRObject obj) { List<MCRPIRegistrationInfo> registered = MCRPIManager.getInstance().getRegistered(obj); final List<String> services = registered.stream().map(MCRPIRegistrationInfo::getService) .collect(Collectors.toList()); List<MCRPIService<MCRPersistentIdentifier>> listOfServicesWithCreatablePIs = MCRPIServiceManager .getInstance().getAutoCreationList().stream() .filter(Predicate.not(s -> services.contains(s.getServiceID()))) .filter(Predicate.not(s -> MCRPIService.hasFlag(obj, "", s))) .filter(s -> s.getCreationPredicate().test(obj)) .collect(Collectors.toList()); listOfServicesWithCreatablePIs .forEach((serviceToRegister) -> { try { serviceToRegister.register(obj, "", false); } catch (MCRAccessException | MCRPersistentIdentifierException | ExecutionException | InterruptedException e) { throw new MCRException("Error while register pi for object " + obj.getId().toString(), e); } }); } }
2,687
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIJobService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIJobService.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.pi; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessManager; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.MCRUserInformation; import org.mycore.common.config.MCRConfigurationException; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; import org.mycore.services.queuedjob.MCRJob; import org.mycore.services.queuedjob.MCRJobAction; import org.mycore.services.queuedjob.MCRJobQueue; import org.mycore.services.queuedjob.MCRJobQueueManager; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; /** * Implementation of a {@link MCRPIService} which helps to outsource a registration task to a {@link MCRJob} * e.G. send a POST request to a REST api * * @param <T> */ public abstract class MCRPIJobService<T extends MCRPersistentIdentifier> extends MCRPIService<T> { public static final String JOB_API_USER_PROPERTY = "JobApiUser"; protected static final String REGISTRATION_PREDICATE = "RegistrationPredicate"; protected static final String CREATION_PREDICATE = "CreationPredicate"; private static final Logger LOGGER = LogManager.getLogger(); public MCRPIJobService(String identType) { super(identType); } private static MCRJobQueue getJobQueue() { return MCRJobQueueManager.getInstance().getJobQueue(MCRPIRegisterJobAction.class); } protected abstract void deleteJob(Map<String, String> parameters) throws MCRPersistentIdentifierException; protected abstract void updateJob(Map<String, String> parameters) throws MCRPersistentIdentifierException; protected abstract void registerJob(Map<String, String> parameters) throws MCRPersistentIdentifierException; /** * Hook in to rollback mechanism of {@link MCRJobAction#rollback()} by overwriting this method. * * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map<String, String>)} * with piJobAction = 'DELETE' * @throws MCRPersistentIdentifierException throw {@link MCRPersistentIdentifierException} if something goes * wrong during rollback */ @SuppressWarnings({ "WeakerAccess", "unused" }) protected void rollbackDeleteJob(Map<String, String> parameters) throws MCRPersistentIdentifierException { // can be used to rollback } /** * Hook in to rollback mechanism of {@link MCRJobAction#rollback()} by overwriting this method. * * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map<String, String>)} * with piJobAction = 'UPDATE' * @throws MCRPersistentIdentifierException throw {@link MCRPersistentIdentifierException} if something goes * wrong during rollback */ @SuppressWarnings({ "WeakerAccess", "unused" }) protected void rollbackUpdateJob(Map<String, String> parameters) throws MCRPersistentIdentifierException { // can be used to rollback } /** * Hook in to rollback mechanism of {@link MCRJobAction#rollback()} by overwriting this method. * * @param parameters the parameters which was passed to {@link #addJob(PiJobAction, Map<String, String>)} * with piJobAction = 'REGISTER' * @throws MCRPersistentIdentifierException throw {@link MCRPersistentIdentifierException} if something goes * wrong during rollback */ @SuppressWarnings({ "WeakerAccess", "unused" }) protected void rollbackRegisterJob(Map<String, String> parameters) throws MCRPersistentIdentifierException { // can be used to rollback } @Override public MCRPI insertIdentifierToDatabase(MCRBase obj, String additional, T identifier, MCRPIServiceDates dates) { MCRPI databaseEntry = new MCRPI(identifier.asString(), getType(), obj.getId().toString(), additional, this.getServiceID(), dates); MCREntityManagerProvider.getCurrentEntityManager().persist(databaseEntry); return databaseEntry; } @Override public MCRPIServiceDates registerIdentifier(MCRBase obj, String additional, T identifier) throws MCRPersistentIdentifierException { if (!additional.equals("")) { throw new MCRPersistentIdentifierException( getClass().getName() + " doesn't support additional information! (" + additional + ")"); } if (getRegistrationPredicate().test(obj)) { this.addJob(PiJobAction.REGISTER, createJobContextParams(PiJobAction.REGISTER, obj, identifier, additional)); return new MCRPIServiceDates(new Date(), null); } return new MCRPIServiceDates(null, null); } @Override protected void delete(T identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException { this.addJob(PiJobAction.DELETE, createJobContextParams(PiJobAction.DELETE, obj, identifier, additional)); } /** * Adds a job for a given PIAction, which will be called in the persistent {@link MCRJob} environment * in an extra thread. * * @param piJobAction the action that the job executes (REGISTER, UPDATE, DELETE) * * @param contextParameters pass parameters which are needed to register the PI. The parameter action and * registrationServiceID will be added, because they are necessary to reassign the job to * the right {@link MCRPIJobService} and method. */ protected void addJob(PiJobAction piJobAction, Map<String, String> contextParameters) { MCRJob job = createJob(contextParameters, piJobAction); getJobQueue().offer(job); } /** * If you use {@link #updateRegistrationDate(MCRObjectID, String, Date)} or * {@link #updateStartRegistrationDate(MCRObjectID, String, Date)} then you should validate if the user has the * rights for this. This methods validates this and throws a handsome exception. * * @param id of the object */ protected void validateJobUserRights(MCRObjectID id) throws MCRPersistentIdentifierException { if (!MCRAccessManager.checkPermission(id, MCRAccessManager.PERMISSION_WRITE)) { throw new MCRPersistentIdentifierException( String.format(Locale.ROOT, "The user %s does not have rights to %s the object %s. You should set the property %s to " + "a user which has the rights.", MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(), MCRAccessManager.PERMISSION_WRITE, id, JOB_API_USER_PROPERTY)); } } /** * Can be used to update the registration date in the database. The most {@link MCRPIJobService} * only add the pi to the object and then to the database, with registration date of null. Later the job will * register the pi and then change the registration date to the right value. * <b>If you use this methods from a job you should have called {@link #validateJobUserRights} before!</b> * * @param mycoreID the id of the {@link org.mycore.datamodel.metadata.MCRBase} which has the pi assigned * @param additional information like path to a file * @param date the new registration date */ protected void updateRegistrationDate(MCRObjectID mycoreID, String additional, Date date) { MCRPI pi = MCRPIManager.getInstance() .get(this.getServiceID(), mycoreID.toString(), additional); pi.setRegistered(date); updateFlag(mycoreID, additional, pi); } /** * Can be used to update the startRegistration date in the database. The most {@link MCRPIJobService} * only add the pi to the object and then to the database, with registration or startRegistration date of null. * After a job is created the Registration service should update the date. * <b>If you use this methods from a job you should have called {@link #validateJobUserRights} before!</b> * * @param mycoreID the id of the {@link org.mycore.datamodel.metadata.MCRBase} which has the pi assigned * @param additional information like path to a file * @param date the new registration date */ protected void updateStartRegistrationDate(MCRObjectID mycoreID, String additional, Date date) { MCRPI pi = MCRPIManager.getInstance() .get(this.getServiceID(), mycoreID.toString(), additional); pi.setRegistrationStarted(date); updateFlag(mycoreID, additional, pi); } /** * Tries to parse a identifier with a specific type. * * @param identifier the identifier to parse * @return parsed identifier or {@link Optional#empty()} if there is no parser for the type * or the parser can't parse the identifier * @throws ClassCastException when type does not match the type of T */ protected Optional<T> parseIdentifier(String identifier) { MCRPIParser<T> parserForType = MCRPIManager.getInstance() .getParserForType(getType()); if (parserForType == null) { return Optional.empty(); } return parserForType.parse(identifier); } private MCRJob createJob(Map<String, String> contextParameters, PiJobAction action) { MCRJob job = new MCRJob(MCRPIRegisterJobAction.class); HashMap<String, String> params = new HashMap<>(contextParameters); params.put("action", action.toString()); params.put("registrationServiceID", this.getServiceID()); job.setParameters(params); return job; } /** * Result of this will be passed to {@link MCRJobAction#name()} * * @param contextParameters the parameters of the job * @return Some Information what this job will do or just {@link Optional#empty()}, * then a default message is generated. */ protected abstract Optional<String> getJobInformation(Map<String, String> contextParameters); public void runAsJobUser(PIRunnable task) throws MCRPersistentIdentifierException { final boolean jobUserPresent = isJobUserPresent(); final String jobUser = getJobUser(); MCRSession session = null; MCRUserInformation savedUserInformation = null; session = MCRSessionMgr.getCurrentSession(); if (jobUserPresent) { savedUserInformation = session.getUserInformation(); MCRUser user = MCRUserManager.getUser(jobUser); /* workaround https://mycore.atlassian.net/browse/MCR-1400*/ session.setUserInformation(MCRSystemUserInformation.getGuestInstance()); session.setUserInformation(user); LOGGER.info("Continue as User {}", jobUser); } else { savedUserInformation = session.getUserInformation(); session.setUserInformation(MCRSystemUserInformation.getGuestInstance()); session.setUserInformation(MCRSystemUserInformation.getJanitorInstance()); } boolean transactionActive = !MCRTransactionHelper.isTransactionActive(); try { if (transactionActive) { MCRTransactionHelper.beginTransaction(); } task.run(); } finally { if (transactionActive && MCRTransactionHelper.isTransactionActive()) { MCRTransactionHelper.commitTransaction(); } if (jobUserPresent) { LOGGER.info("Continue as previous User {}", savedUserInformation.getUserID()); /* workaround https://mycore.atlassian.net/browse/MCR-1400*/ session.setUserInformation(MCRSystemUserInformation.getGuestInstance()); session.setUserInformation(savedUserInformation); } } } private String getJobUser() { return this.getProperties().get(JOB_API_USER_PROPERTY); } private boolean isJobUserPresent() { return this.getProperties().containsKey(JOB_API_USER_PROPERTY); } void delegateAction(final Map<String, String> contextParameters) throws MCRPersistentIdentifierException { runAsJobUser(() -> { switch (getAction(contextParameters)) { case REGISTER -> registerJob(contextParameters); case UPDATE -> updateJob(contextParameters); case DELETE -> deleteJob(contextParameters); default -> throw new MCRPersistentIdentifierException("Unhandled action type!"); } }); } void delegateRollback(final Map<String, String> contextParameters) throws MCRPersistentIdentifierException { runAsJobUser(() -> { switch (getAction(contextParameters)) { case REGISTER -> rollbackRegisterJob(contextParameters); case UPDATE -> rollbackUpdateJob(contextParameters); case DELETE -> rollbackDeleteJob(contextParameters); default -> throw new MCRPersistentIdentifierException("Unhandled action type!"); } }); } protected PiJobAction getAction(Map<String, String> contextParameters) { return PiJobAction.valueOf(contextParameters.get("action")); } @Override protected void checkConfiguration() throws MCRConfigurationException { super.checkConfiguration(); if (getProperties().containsKey("RegistrationConditionProvider")) { throw new MCRConfigurationException("The MCRPIService " + getServiceID() + " uses old property key RegistrationConditionProvider, use " + REGISTRATION_PREDICATE + " instead."); } } @Override protected void update(T identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException { if (this.isRegistered(obj.getId(), additional)) { this.addJob(PiJobAction.UPDATE, createJobContextParams(PiJobAction.UPDATE, obj, identifier, additional)); } else if (!this.hasRegistrationStarted(obj.getId(), additional) && this.getRegistrationPredicate().test(obj) && validateRegistrationDocument(obj, identifier, additional)) { this.updateStartRegistrationDate(obj.getId(), additional, new Date()); this.addJob(PiJobAction.REGISTER, createJobContextParams(PiJobAction.REGISTER, obj, identifier, additional)); } } protected abstract boolean validateRegistrationDocument(MCRBase obj, T identifier, String additional); protected abstract HashMap<String, String> createJobContextParams(PiJobAction action, MCRBase obj, T identifier, String additional); public enum PiJobAction { DELETE("delete"), REGISTER("register"), UPDATE("update"); private final String action; PiJobAction(String action) { this.action = action; } public String getAction() { return action; } } private interface PIRunnable { void run() throws MCRPersistentIdentifierException; } }
16,495
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLocalPIResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRLocalPIResolver.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.pi; import java.util.function.Function; import java.util.stream.Stream; import org.mycore.frontend.MCRFrontendUtil; public class MCRLocalPIResolver extends MCRPIResolver<MCRPersistentIdentifier> { private final Function<String, String> toReceiveObjectURL = mcrID -> MCRFrontendUtil.getBaseURL() + "receive/" + mcrID; public MCRLocalPIResolver() { super("Local-Resolver"); } @Override public Stream<String> resolve(MCRPersistentIdentifier identifier) { return MCRPIManager.getInstance() .getInfo(identifier) .stream() .map(MCRPIRegistrationInfo::getMycoreID) .map(toReceiveObjectURL); } }
1,435
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersistentIdentifier.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPersistentIdentifier.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.pi; public interface MCRPersistentIdentifier { String asString(); }
819
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIResolver.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.pi; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException; public abstract class MCRPIResolver<T extends MCRPersistentIdentifier> { private static final Logger LOGGER = LogManager.getLogger(); private final String name; public MCRPIResolver(String name) { this.name = name; } public abstract Stream<String> resolve(T identifier) throws MCRIdentifierUnresolvableException; public Stream<String> resolveSuppress(T identifier) { try { return resolve(identifier); } catch (MCRIdentifierUnresolvableException e) { LOGGER.info(e); return Stream.empty(); } } public String getName() { return name; } }
1,591
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIParser.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIParser.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.pi; import java.util.Optional; public interface MCRPIParser<T extends MCRPersistentIdentifier> { Optional<T> parse(String identifier); }
889
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIMetadataService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIMetadataService.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.pi; import java.util.Map; import java.util.Optional; import org.mycore.common.config.annotation.MCRProperty; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; /** * Should be able to insert/remove DOI, URN or other identifiers to metadata and check if they already have a * Identifier of type T * * @param <T> */ public abstract class MCRPIMetadataService<T extends MCRPersistentIdentifier> { private Map<String, String> properties; public final Map<String, String> getProperties() { return properties; } @MCRProperty(name = "*") public final void setProperties(Map<String, String> properties) { this.properties = properties; } public abstract void insertIdentifier(T identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException; public abstract void removeIdentifier(T identifier, MCRBase obj, String additional); public abstract Optional<MCRPersistentIdentifier> getIdentifier(MCRBase obj, String additional) throws MCRPersistentIdentifierException; }
1,867
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersistentIdentifierEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPersistentIdentifierEventHandler.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.pi; import java.util.List; import java.util.function.BiConsumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCRJanitorEventHandlerBase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public class MCRPersistentIdentifierEventHandler extends MCRJanitorEventHandlerBase { private static final Logger LOGGER = LogManager.getLogger(); @SuppressWarnings("unchecked") public static void updateObject(MCRObject obj) { detectServices(obj, (service, registrationInfo) -> { try { service.onUpdate(getIdentifier(registrationInfo), obj, registrationInfo.getAdditional()); } catch (MCRPersistentIdentifierException e) { throw new MCRException(e); } }); } private static void detectServices(MCRObject obj, BiConsumer<MCRPIService, MCRPIRegistrationInfo> r) { MCRPIServiceManager serviceManager = MCRPIServiceManager.getInstance(); List<MCRPIRegistrationInfo> registered = MCRPIManager.getInstance().getRegistered(obj); List<String> serviceList = serviceManager.getServiceIDList(); for (MCRPIRegistrationInfo pi : registered) { String serviceName = pi.getService(); if (serviceList.contains(serviceName)) { getIdentifier(pi); MCRPIService<MCRPersistentIdentifier> registrationService = serviceManager .getRegistrationService(serviceName); r.accept(registrationService, pi); } else { LOGGER .warn(() -> "The service " + serviceName + " was removed from properties, so the update function!"); } } } private static MCRPersistentIdentifier getIdentifier(MCRPIRegistrationInfo pi) { MCRPIManager identifierManager = MCRPIManager.getInstance(); MCRPIParser<?> parser = identifierManager.getParserForType(pi.getType()); return parser.parse(pi.getIdentifier()) .orElseThrow(() -> new MCRException("Cannot parse a previous inserted identifier")); } @Override protected void handleObjectRepaired(MCREvent evt, MCRObject obj) { /* Add PIs to DB if they are not there */ MCRPIManager.getInstance().getRegistered(obj) .forEach(pi -> MCRPIManager.getInstance().delete(pi.getMycoreID(), pi.getAdditional(), pi.getType(), pi.getService())); MCRPIService.updateFlagsInDatabase(obj); handleObjectUpdated(evt, obj); } @Override protected void handleObjectUpdated(MCREvent evt, MCRObject obj) { updateObject(obj); } @Override @SuppressWarnings("unchecked") protected void handleObjectDeleted(MCREvent evt, MCRObject obj) { detectServices(obj, (service, registrationInfo) -> { try { service.onDelete(getIdentifier(registrationInfo), obj, registrationInfo.getAdditional()); } catch (MCRPersistentIdentifierException e) { throw new MCRException(e); } }); } }
4,054
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRGenericPIGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRGenericPIGenerator.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.pi; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Attribute; import org.jdom2.Element; import org.jdom2.Text; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.config.annotation.MCRPostConstruction; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.MCRObjectService; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; /** * * MCR.PI.Generator.myGenerator=org.mycore.pi.urn.MCRGenericPIGenerator * * Set a generic pattern. * * MCR.PI.Generator.myGenerator.GeneralPattern=urn:nbn:de:gbv:$CurrentDate-$1-$2-$ObjectType-$ObjectProject-$ObjectNumber-$Count- * MCR.PI.Generator.myGenerator.GeneralPattern=urn:nbn:de:gbv:$ObjectDate-$ObjectType-$Count * MCR.PI.Generator.myGenerator.GeneralPattern=urn:nbn:de:gbv:$ObjectDate-$Count * MCR.PI.Generator.myGenerator.GeneralPattern=urn:nbn:de:gbv:$ObjectType-$Count * MCR.PI.Generator.myGenerator.GeneralPattern=urn:nbn:de:gbv:$0-$1-$Count * * Set a optional DateFormat, if not set the ddMMyyyy is just used as value. (SimpleDateFormat) * * MCR.PI.Generator.myGenerator.DateFormat=ddMMyyyy * * Set a optional ObjectType mapping, if not set the ObjectType is just used as value * * MCR.PI.Generator.myGenerator.TypeMapping=document:doc,disshab:diss,Thesis:Thesis,bundle:doc,mods:test * * You can also map the projectid * * Set a optional Count precision, if not set or set to -1 the pure number is used (1,2,.., 999). * Count always relativ to type and date. * * MCR.PI.Generator.myGenerator.CountPrecision=3 # will produce 001, 002, ... , 999 * * Set the Type of the generated pi. * * MCR.PI.Generator.myGenerator.Type=dnbURN * * * Set the Xpaths * * MCR.PI.Generator.myGenerator.XPath.1=/mycoreobject/metadata/def.shelf/shelf/ * MCR.PI.Generator.myGenerator.XPath.2=/mycoreobject/metadata/def.path2/path2/ * * @author Sebastian Hofmann */ public class MCRGenericPIGenerator extends MCRPIGenerator<MCRPersistentIdentifier> { static final String PLACE_HOLDER_CURRENT_DATE = "$CurrentDate"; static final String PLACE_HOLDER_OBJECT_DATE = "$ObjectDate"; static final String PLACE_HOLDER_OBJECT_TYPE = "$ObjectType"; static final String PLACE_HOLDER_OBJECT_PROJECT = "$ObjectProject"; static final String PLACE_HOLDER_COUNT = "$Count"; static final String PLACE_HOLDER_OBJECT_NUMBER = "$ObjectNumber"; private static final Logger LOGGER = LogManager.getLogger(); private static final String PROPERTY_KEY_GENERAL_PATTERN = "GeneralPattern"; private static final String PROPERTY_KEY_DATE_FORMAT = "DateFormat"; private static final String PROPERTY_KEY_OBJECT_TYPE_MAPPING = "ObjectTypeMapping"; private static final String PROPERTY_KEY_OBJECT_PROJECT_MAPPING = "ObjectProjectMapping"; private static final String PROPERTY_KEY_COUNT_PRECISION = "CountPrecision"; private static final String PROPERTY_KEY_XPATH = "XPath"; private static final String PROPERTY_KEY_TYPE = "Type"; private static final Map<String, AtomicInteger> PATTERN_COUNT_MAP = new HashMap<>(); private static final Pattern XPATH_PATTERN = Pattern.compile("\\$([0-9]+)", Pattern.DOTALL); private String generalPattern; private SimpleDateFormat dateFormat; private String objectTypeMapping; private String objectProjectMapping; private int countPrecision; private String type; private String[] xpath; public MCRGenericPIGenerator() { super(); } @MCRPostConstruction public void init(String property) { super.init(property); final Map<String, String> properties = getProperties(); setGeneralPattern(properties.get(PROPERTY_KEY_GENERAL_PATTERN)); setDateFormat(Optional.ofNullable(properties.get(PROPERTY_KEY_DATE_FORMAT)) .map(format -> new SimpleDateFormat(format, Locale.ROOT)) .orElse(new SimpleDateFormat("ddMMyyyy", Locale.ROOT))); setObjectTypeMapping(properties.get(PROPERTY_KEY_OBJECT_TYPE_MAPPING)); setObjectProjectMapping(properties.get(PROPERTY_KEY_OBJECT_PROJECT_MAPPING)); setCountPrecision(Optional.ofNullable(properties.get(PROPERTY_KEY_COUNT_PRECISION)) .map(Integer::parseInt) .orElse(-1)); setType(properties.get(PROPERTY_KEY_TYPE)); List<String> xpaths = new ArrayList<>(); int count = 1; while (properties.containsKey(PROPERTY_KEY_XPATH + "." + count)) { xpaths.add(properties.get(PROPERTY_KEY_XPATH + "." + count)); count++; } setXpath(xpaths.toArray(new String[0])); validateProperties(); } // for testing purposes MCRGenericPIGenerator(String generalPattern, SimpleDateFormat dateFormat, String objectTypeMapping, String objectProjectMapping, int countPrecision, String type, String... xpaths) { super(); setObjectProjectMapping(objectProjectMapping); setGeneralPattern(generalPattern); setDateFormat(dateFormat); setObjectTypeMapping(objectTypeMapping); setCountPrecision(countPrecision); setType(type); validateProperties(); setXpath(xpaths); } private void setXpath(String... xpaths) { this.xpath = xpaths; } private void validateProperties() { if (countPrecision == -1 && "dnbUrn".equals(getType())) { throw new MCRConfigurationException( PROPERTY_KEY_COUNT_PRECISION + "=-1 and " + PROPERTY_KEY_TYPE + "=urn is not supported!"); } } @Override public MCRPersistentIdentifier generate(MCRBase mcrBase, String additional) throws MCRPersistentIdentifierException { String resultingPI = getGeneralPattern(); if (resultingPI.contains(PLACE_HOLDER_CURRENT_DATE)) { resultingPI = resultingPI.replace(PLACE_HOLDER_CURRENT_DATE, getDateFormat().format(new Date())); } if (resultingPI.contains(PLACE_HOLDER_OBJECT_DATE)) { final Date objectCreateDate = mcrBase.getService().getDate(MCRObjectService.DATE_TYPE_CREATEDATE); resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_DATE, getDateFormat().format(objectCreateDate)); } if (resultingPI.contains(PLACE_HOLDER_OBJECT_TYPE)) { final String mappedObjectType = getMappedType(mcrBase.getId()); resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_TYPE, mappedObjectType); } if (resultingPI.contains(PLACE_HOLDER_OBJECT_PROJECT)) { final String mappedObjectProject = getMappedProject(mcrBase.getId()); resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_PROJECT, mappedObjectProject); } if (resultingPI.contains(PLACE_HOLDER_OBJECT_NUMBER)) { resultingPI = resultingPI.replace(PLACE_HOLDER_OBJECT_NUMBER, mcrBase.getId().getNumberAsString()); } if (XPATH_PATTERN.asPredicate().test(resultingPI)) { resultingPI = XPATH_PATTERN.matcher(resultingPI).replaceAll((mr) -> { final String xpathNumberString = mr.group(1); final int xpathNumber = Integer.parseInt(xpathNumberString, 10) - 1; if (this.xpath.length <= xpathNumber || xpathNumber < 0) { throw new MCRException( "The index of " + xpathNumber + " is out of bounds of xpath array (" + xpath.length + ")"); } final String xpathString = this.xpath[xpathNumber]; XPathFactory factory = XPathFactory.instance(); XPathExpression<Object> expr = factory.compile(xpathString, Filters.fpassthrough(), null, MCRConstants.getStandardNamespaces()); final Object content = expr.evaluateFirst(mcrBase.createXML()); if (content instanceof Text text) { return text.getTextNormalize(); } else if (content instanceof Attribute attribute) { return attribute.getValue(); } else if (content instanceof Element element) { return element.getTextNormalize(); } else { return content.toString(); } }); System.out.println(resultingPI); } final MCRPIParser<MCRPersistentIdentifier> parser = MCRPIManager.getInstance() .getParserForType(getType()); String result; result = applyCount(resultingPI); if (getType().equals("dnbUrn")) { result = result + "C"; // will be replaced by the URN-Parser } String finalResult = result; return parser.parse(finalResult) .orElseThrow(() -> new MCRPersistentIdentifierException("Could not parse " + finalResult)); } private String applyCount(String resultingPI) { String result; if (resultingPI.contains(PLACE_HOLDER_COUNT)) { final int countPrecision = getCountPrecision(); String regexpStr; if (countPrecision == -1) { regexpStr = "([0-9]+)"; } else { regexpStr = "(" + IntStream.range(0, countPrecision).mapToObj((i) -> "[0-9]").collect(Collectors.joining("")) + ")"; } String counterPattern = resultingPI.replace(PLACE_HOLDER_COUNT, regexpStr); if (getType().equals("dnbUrn")) { counterPattern = counterPattern + "[0-9]"; } LOGGER.info("Counter pattern is {}", counterPattern); final int count = getCount(counterPattern); LOGGER.info("Count is {}", count); final String pattern = IntStream.range(0, Math.abs(countPrecision)).mapToObj((i) -> "0") .collect(Collectors.joining("")); DecimalFormat decimalFormat = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.ROOT)); final String countAsString = countPrecision != -1 ? decimalFormat.format(count) : String.valueOf(count); result = resultingPI.replace(PLACE_HOLDER_COUNT, countAsString); } else { result = resultingPI; } return result; } private String getMappedType(MCRObjectID id) { String mapping = getObjectTypeMapping(); String typeID = id.getTypeId(); return Optional.ofNullable(mapping) .map(mappingStr -> mappingStr.split(",")) .map(Arrays::asList) .filter(o -> o.get(0).equals(typeID)) .map(o -> o.get(1)) .orElse(typeID); } private String getMappedProject(MCRObjectID id) { String mapping = getObjectProjectMapping(); String projectID = id.getProjectId(); return Optional.ofNullable(mapping) .map(mappingStr -> mappingStr.split(",")) .map(Arrays::asList) .filter(o -> o.get(0).equals(projectID)) .map(o -> o.get(1)) .orElse(projectID); } protected AtomicInteger readCountFromDatabase(String countPattern) { Pattern regExpPattern = Pattern.compile(countPattern); Predicate<String> matching = regExpPattern.asPredicate(); List<MCRPIRegistrationInfo> list = MCRPIManager.getInstance() .getList(getType(), -1, -1); // extract the number of the PI Optional<Integer> highestNumber = list.stream() .map(MCRPIRegistrationInfo::getIdentifier) .filter(matching) .map(pi -> { // extract the number of the PI Matcher matcher = regExpPattern.matcher(pi); if (matcher.find() && matcher.groupCount() == 1) { String group = matcher.group(1); return Integer.parseInt(group, 10); } else { return null; } }).filter(Objects::nonNull) .min(Comparator.reverseOrder()) .map(n -> n + 1); return new AtomicInteger(highestNumber.orElse(0)); } private String getType() { return type; } public void setType(String type) { this.type = type; } public String getGeneralPattern() { return generalPattern; } public void setGeneralPattern(String generalPattern) { this.generalPattern = generalPattern; } public SimpleDateFormat getDateFormat() { return dateFormat; } public void setDateFormat(SimpleDateFormat dateFormat) { this.dateFormat = dateFormat; } public String getObjectTypeMapping() { return objectTypeMapping; } public void setObjectTypeMapping(String typeMapping) { this.objectTypeMapping = typeMapping; } public int getCountPrecision() { return countPrecision; } public void setCountPrecision(int countPrecision) { this.countPrecision = countPrecision; } /** * Gets the count for a specific pattern and increase the internal counter. If there is no internal counter it will * look into the Database and detect the highest count with the pattern. * * @param pattern a reg exp pattern which will be used to detect the highest count. The first group is the count. * e.G. [0-9]+-mods-2017-([0-9][0-9][0-9][0-9])-[0-9] will match 31-mods-2017-0003-3 and the returned * count will be 4 (3+1). * @return the next count */ public final synchronized int getCount(String pattern) { AtomicInteger count = PATTERN_COUNT_MAP .computeIfAbsent(pattern, this::readCountFromDatabase); return count.getAndIncrement(); } public String getObjectProjectMapping() { return objectProjectMapping; } public void setObjectProjectMapping(String objectProjectMapping) { this.objectProjectMapping = objectProjectMapping; } }
15,686
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIRegisterJobAction.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIRegisterJobAction.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.pi; import java.util.concurrent.ExecutionException; import org.mycore.common.MCRException; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; import org.mycore.services.queuedjob.MCRJob; import org.mycore.services.queuedjob.MCRJobAction; public class MCRPIRegisterJobAction extends MCRJobAction { public MCRPIRegisterJobAction(MCRJob job) { super(job); } @Override public boolean isActivated() { return true; } @Override public String name() { MCRPIJobService<MCRPersistentIdentifier> registrationService = getRegistrationService(); return registrationService.getJobInformation(this.job.getParameters()).orElseGet(() -> { String action = getAction().toString(); String registrationServiceID = getRegistrationServiceID(); return registrationServiceID + " - " + action; }); } private MCRPIJobService<MCRPersistentIdentifier> getRegistrationService() { String registrationServiceID = getRegistrationServiceID(); return (MCRPIJobService<MCRPersistentIdentifier>) MCRPIServiceManager.getInstance() .getRegistrationService(registrationServiceID); } private MCRPIJobService.PiJobAction getAction() { return MCRPIJobService.PiJobAction.valueOf(this.job.getParameter("action")); } private String getRegistrationServiceID() { return this.job.getParameter("registrationServiceID"); } @Override public void execute() throws ExecutionException { try { getRegistrationService().delegateAction(this.job.getParameters()); } catch (MCRPersistentIdentifierException e) { throw new ExecutionException(e); } } @Override public void rollback() { try { getRegistrationService().delegateRollback(this.job.getParameters()); } catch (MCRPersistentIdentifierException e) { throw new MCRException(e); } } }
2,749
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIServiceDates.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIServiceDates.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.pi; import java.util.Date; /** * Record, that holds the dates, when the registration finished and was started * * @author Robert Stephan * */ public record MCRPIServiceDates(Date registered, Date registrationStarted) { }
975
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIXPathMetadataService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIXPathMetadataService.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.pi; import java.util.List; import java.util.Optional; import javax.naming.OperationNotSupportedException; import org.jdom2.Document; 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 org.mycore.common.MCRException; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public class MCRPIXPathMetadataService extends MCRPIMetadataService<MCRPersistentIdentifier> { @Override public void insertIdentifier(MCRPersistentIdentifier identifier, MCRBase obj, String additional) { String xpath = getProperties().get("Xpath"); Document xml = obj.createXML(); MCRNodeBuilder nb = new MCRNodeBuilder(); try { nb.buildElement(xpath, identifier.asString(), xml); if (obj instanceof MCRObject object) { final Element metadata = xml.getRootElement().getChild("metadata"); object.getMetadata().setFromDOM(metadata); } else { throw new MCRPersistentIdentifierException(obj.getId() + " is no MCRObject!", new OperationNotSupportedException(getClass().getName() + " only supports " + MCRObject.class.getName() + "!")); } } catch (Exception e) { throw new MCRException("Error while inscribing PI to " + obj.getId(), e); } } @Override public void removeIdentifier(MCRPersistentIdentifier identifier, MCRBase obj, String additional) { String xpath = getProperties().get("Xpath"); Document xml = obj.createXML(); XPathFactory xPathFactory = XPathFactory.instance(); XPathExpression<Element> xp = xPathFactory.compile(xpath, Filters.element()); List<Element> elements = xp.evaluate(xml); elements.stream() .filter(element -> element.getTextTrim().equals(identifier.asString())) .forEach(Element::detach); } @Override public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase obj, String additional) throws MCRPersistentIdentifierException { String xpath = getProperties().get("Xpath"); Document xml = obj.createXML(); XPathFactory xpfac = XPathFactory.instance(); XPathExpression<Element> xp = xpfac .compile(xpath, Filters.element(), null, MCRConstants.getStandardNamespaces()); List<Element> evaluate = xp.evaluate(xml); if (evaluate.size() > 1) { throw new MCRPersistentIdentifierException( "Got " + evaluate.size() + " matches for " + obj.getId() + " with xpath " + xpath + ""); } if (evaluate.size() == 0) { return Optional.empty(); } Element identifierElement = evaluate.listIterator().next(); String identifierString = identifierElement.getTextNormalize(); Optional<MCRPersistentIdentifier> parsedIdentifierOptional = MCRPIManager.getInstance() .getParserForType(getProperties().get("Type")).parse(identifierString); return parsedIdentifierOptional.map(MCRPersistentIdentifier.class::cast); } }
4,109
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIRegistrationInfo.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIRegistrationInfo.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.pi; import java.io.Serializable; import java.util.Date; public interface MCRPIRegistrationInfo extends Serializable { String getIdentifier(); String getType(); String getMycoreID(); String getAdditional(); String getMcrVersion(); int getMcrRevision(); Date getRegistrationStarted(); Date getRegistered(); Date getCreated(); String getService(); }
1,144
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIGenerator.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.pi; import static org.mycore.pi.MCRPIService.GENERATOR_CONFIG_PREFIX; import java.util.Map; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.config.annotation.MCRPostConstruction; import org.mycore.common.config.annotation.MCRProperty; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; public abstract class MCRPIGenerator<T extends MCRPersistentIdentifier> { private String generatorID; private Map<String, String> properties; public final Map<String, String> getProperties() { return properties; } @MCRPostConstruction public void init(String property) { generatorID = property.substring(GENERATOR_CONFIG_PREFIX.length()); } @MCRProperty(name = "*") public void setProperties(Map<String, String> properties) { this.properties = properties; } /** * generates a {@link MCRPersistentIdentifier} * * @param mcrBase the mycore object for which the identifier is generated * @param additional additional information dedicated to the object like a mcrpath * @return a unique persistence identifier * @throws MCRPersistentIdentifierException if something goes wrong while generating */ public abstract T generate(MCRBase mcrBase, String additional) throws MCRPersistentIdentifierException; /** * checks if the property exists and throws a exception if not. * @param propertyName to check * @throws MCRConfigurationException if property does not exist */ protected void checkPropertyExists(final String propertyName) throws MCRConfigurationException { if (!getProperties().containsKey(propertyName)) { throw new MCRConfigurationException( "Missing property " + GENERATOR_CONFIG_PREFIX + getGeneratorID() + "." + propertyName); } } public String getGeneratorID() { return generatorID; } }
2,738
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIManager.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.pi; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRClassTools; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.backend.MCRPI_; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; public class MCRPIManager { private static final String TYPE = "type"; private static final String MCRID = "mcrId"; private static final String SERVICE = "service"; private static final String ADDITIONAL = "additional"; private static final String PARSER_CONFIGURATION = "MCR.PI.Parsers."; private static final String RESOLVER_CONFIGURATION = "MCR.PI.Resolvers"; private static MCRPIManager instance; private List<MCRPIResolver<MCRPersistentIdentifier>> resolverList; private List<Class<? extends MCRPIParser<? extends MCRPersistentIdentifier>>> parserList; private Map<String, Class<? extends MCRPIParser>> typeParserMap; private MCRPIManager() { parserList = new ArrayList<>(); typeParserMap = new ConcurrentHashMap<>(); MCRConfiguration2.getSubPropertiesMap(PARSER_CONFIGURATION) .forEach((type, className) -> { try { Class<? extends MCRPIParser<?>> parserClass = MCRClassTools.forName(className); registerParser(type, parserClass); } catch (ClassNotFoundException e) { throw new MCRConfigurationException( "Could not load class " + className + " defined in " + PARSER_CONFIGURATION + type); } }); resolverList = MCRConfiguration2.getOrThrow(RESOLVER_CONFIGURATION, MCRConfiguration2::splitValue) .map(MCRConfiguration2::<MCRPIResolver<MCRPersistentIdentifier>>instantiateClass) .collect(Collectors.toList()); } public static synchronized MCRPIManager getInstance() { if (instance == null) { instance = new MCRPIManager(); } return instance; } @SuppressWarnings("unchecked") private static <T extends MCRPersistentIdentifier> MCRPIParser<T> getParserInstance( Class<? extends MCRPIParser> detectorClass) throws ClassCastException { try { return detectorClass.getDeclaredConstructor().newInstance(); } catch (ReflectiveOperationException e) { return null; } } public int getCount() { return getCount(null); } public boolean exist(MCRPIRegistrationInfo mcrpiRegistrationInfo) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Number> rowCountQuery = cb.createQuery(Number.class); Root<MCRPI> pi = rowCountQuery.from(MCRPI.class); return em.createQuery( rowCountQuery .select(cb.count(pi)) .where(cb.equal(pi.get(MCRPI_.type), mcrpiRegistrationInfo.getType()), cb.equal(pi.get(MCRPI_.additional), mcrpiRegistrationInfo.getAdditional()), cb.equal(pi.get(MCRPI_.identifier), mcrpiRegistrationInfo.getIdentifier()), cb.equal(pi.get(MCRPI_.service), mcrpiRegistrationInfo.getService()), cb.equal(pi.get(MCRPI_.mycoreID), mcrpiRegistrationInfo.getMycoreID()))) .getSingleResult() .intValue() > 0; } public MCRPI get(String service, String mycoreID, String additional) { return MCREntityManagerProvider .getCurrentEntityManager() .createNamedQuery("Get.PI.Additional", MCRPI.class) .setParameter(MCRID, mycoreID) .setParameter(ADDITIONAL, additional) .setParameter(SERVICE, service) .getSingleResult(); } public List<MCRPIRegistrationInfo> getCreatedIdentifiers(MCRObjectID id, String type, String registrationServiceID) { return MCREntityManagerProvider .getCurrentEntityManager() .createNamedQuery("Get.PI.Created", MCRPIRegistrationInfo.class) .setParameter(MCRID, id.toString()) .setParameter(TYPE, type) .setParameter(SERVICE, registrationServiceID) .getResultList(); } public boolean isCreated(MCRObjectID id, String additional, String type, String registrationServiceID) { return MCREntityManagerProvider .getCurrentEntityManager() .createNamedQuery("Count.PI.Created", Number.class) .setParameter(MCRID, id.toString()) .setParameter(TYPE, type) .setParameter(ADDITIONAL, additional) .setParameter(SERVICE, registrationServiceID) .getSingleResult() .shortValue() > 0; } public boolean isRegistered(MCRPI mcrPi) { return isRegistered(mcrPi.getMycoreID(), mcrPi.getAdditional(), mcrPi.getType(), mcrPi.getService()); } public boolean isRegistered(MCRObjectID mcrId, String additional, String type, String registrationServiceID) { return isRegistered(mcrId.toString(), additional, type, registrationServiceID); } public boolean isRegistered(String mcrId, String additional, String type, String registrationServiceID) { return MCREntityManagerProvider .getCurrentEntityManager() .createNamedQuery("Count.PI.Registered", Number.class) .setParameter(MCRID, mcrId) .setParameter(TYPE, type) .setParameter(ADDITIONAL, additional) .setParameter(SERVICE, registrationServiceID) .getSingleResult() .shortValue() > 0; } public boolean hasRegistrationStarted(MCRObjectID mcrId, String additional, String type, String registrationServiceID) { return hasRegistrationStarted(mcrId.toString(), additional, type, registrationServiceID); } public boolean hasRegistrationStarted(String mcrId, String additional, String type, String registrationServiceID) { return MCREntityManagerProvider .getCurrentEntityManager() .createNamedQuery("Count.PI.RegistrationStarted", Number.class) .setParameter(MCRID, mcrId) .setParameter(TYPE, type) .setParameter(ADDITIONAL, additional) .setParameter(SERVICE, registrationServiceID) .getSingleResult() .shortValue() > 0; } public int getCount(String type) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Number> rowCountQuery = cb.createQuery(Number.class); Root<MCRPI> pi = rowCountQuery.from(MCRPI.class); return em.createQuery( rowCountQuery .select(cb.count(pi)) .where(cb.equal(pi.get(MCRPI_.type), type))) .getSingleResult().intValue(); } public void delete(String objectID, String additional, String type, String service) { Objects.requireNonNull(objectID, "objectId may not be null"); Objects.requireNonNull(type, "type may not be null"); Objects.requireNonNull(service, "service may not be null"); EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRPI> getQuery = cb.createQuery(MCRPI.class); Root<MCRPI> pi = getQuery.from(MCRPI.class); Predicate additionalPredicate = additional == null ? cb.isNull(pi.get(MCRPI_.additional)) : cb.equal(pi.get(MCRPI_.additional), additional); em.remove( em.createQuery( getQuery .where( cb.equal(pi.get(MCRPI_.mycoreID), objectID), cb.equal(pi.get(MCRPI_.type), type), additionalPredicate, cb.equal(pi.get(MCRPI_.service), service))) .getSingleResult()); } public List<MCRPIRegistrationInfo> getList() { return getList(null, -1, -1); } public List<MCRPIRegistrationInfo> getList(int from, int count) { return getList(null, from, count); } public List<MCRPIRegistrationInfo> getList(String type, int from, int count) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRPIRegistrationInfo> getQuery = cb.createQuery(MCRPIRegistrationInfo.class); Root<MCRPI> pi = getQuery.from(MCRPI.class); CriteriaQuery<MCRPIRegistrationInfo> all = getQuery.select(pi); if (type != null) { all = all.where(cb.equal(pi.get(MCRPI_.type), type)); } TypedQuery<MCRPIRegistrationInfo> typedQuery = em.createQuery(all); if (from != -1) { typedQuery = typedQuery.setFirstResult(from); } if (count != -1) { typedQuery = typedQuery.setMaxResults(count); } return typedQuery.getResultList(); } public Integer setRegisteredDateForUnregisteredIdentifiers( String type, Function<MCRPIRegistrationInfo, Optional<Date>> dateProvider, Integer batchSize) { List<MCRPI> unregisteredIdentifiers = getUnregisteredIdentifiers(type, batchSize); unregisteredIdentifiers .forEach(ident -> dateProvider .apply(ident) .ifPresent(ident::setRegistered)); return unregisteredIdentifiers.size(); } public List<MCRPI> getUnregisteredIdentifiers(String type, int maxSize) { TypedQuery<MCRPI> getUnregisteredQuery = MCREntityManagerProvider .getCurrentEntityManager() .createNamedQuery("Get.PI.Unregistered", MCRPI.class) .setParameter("type", type); if (maxSize >= 0) { getUnregisteredQuery.setMaxResults(maxSize); } return getUnregisteredQuery.getResultList(); } public List<MCRPI> getUnregisteredIdentifiers(String type) { return getUnregisteredIdentifiers(type, -1); } public List<MCRPIRegistrationInfo> getRegistered(MCRBase object) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRPIRegistrationInfo> getQuery = cb.createQuery(MCRPIRegistrationInfo.class); Root<MCRPI> pi = getQuery.from(MCRPI.class); return em.createQuery( getQuery .select(pi) .where( cb.equal(pi.get(MCRPI_.mycoreID), object.getId().toString()))) .getResultList(); } public List<MCRPIRegistrationInfo> getInfo(MCRPersistentIdentifier identifier) { return getInfo(identifier.asString()); } public List<MCRPIRegistrationInfo> getInfo(String identifier) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRPIRegistrationInfo> getQuery = cb.createQuery(MCRPIRegistrationInfo.class); Root<MCRPI> pi = getQuery.from(MCRPI.class); return em.createQuery( getQuery .select(pi) .where(cb.equal(pi.get(MCRPI_.identifier), identifier))) .getResultList(); } public Optional<MCRPIRegistrationInfo> getInfo(MCRPersistentIdentifier identifier, String type) { return getInfo(identifier.asString(), type); } public Optional<MCRPIRegistrationInfo> getInfo(String identifier, String type) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRPIRegistrationInfo> getQuery = cb.createQuery(MCRPIRegistrationInfo.class); Root<MCRPI> pi = getQuery.from(MCRPI.class); final List<MCRPIRegistrationInfo> resultList = em.createQuery( getQuery .select(pi) .where(cb.equal(pi.get(MCRPI_.identifier), identifier), cb.equal(pi.get(MCRPI_.type), type))) .getResultList(); return resultList.size() == 0 ? Optional.empty() : Optional.of(resultList.get(0)); } /** * Returns a parser for a specific type of persistent identifier. * * @param type the type which should be parsed * @param <T> the type of {@link MCRPIParser} which should be returned. * @return a MCRPIParser * @throws ClassCastException when the wrong type is passed */ @SuppressWarnings("WeakerAccess") public <T extends MCRPersistentIdentifier> MCRPIParser<T> getParserForType(String type) throws ClassCastException { return getParserInstance(typeParserMap.get(type)); } /** * Registers a parser for a specific type of persistent identifier. * * @param type the type of the parser * @param parserClass the class of the parser */ @SuppressWarnings("WeakerAccess") public void registerParser( String type, Class<? extends MCRPIParser<? extends MCRPersistentIdentifier>> parserClass) { this.parserList.add(parserClass); this.typeParserMap.put(type, parserClass); } public List<MCRPIResolver<MCRPersistentIdentifier>> getResolvers() { return this.resolverList; } public Stream<MCRPersistentIdentifier> get(String pi) { return parserList .stream() .map(MCRPIManager::getParserInstance) .map(p -> p.parse(pi)) .filter(Optional::isPresent) .map(Optional::get) .map(MCRPersistentIdentifier.class::cast); } }
15,278
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPIServiceManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/MCRPIServiceManager.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.pi; import static org.mycore.pi.MCRPIJobService.CREATION_PREDICATE; import java.util.List; import java.util.stream.Collectors; import org.mycore.common.config.MCRConfiguration2; public class MCRPIServiceManager { public static final String REGISTRATION_SERVICE_CONFIG_PREFIX = "MCR.PI.Service."; public static MCRPIServiceManager getInstance() { return InstanceHolder.INSTANCE; } public List<String> getServiceIDList() { return MCRConfiguration2.getInstantiatablePropertyKeys(REGISTRATION_SERVICE_CONFIG_PREFIX) .map(s -> s.substring(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX.length())) .collect(Collectors.toList()); } public List<MCRPIService<MCRPersistentIdentifier>> getServiceList() { return getServiceIDList() .stream() .map(this::getRegistrationService) .collect(Collectors.toList()); } public List<MCRPIService<MCRPersistentIdentifier>> getAutoCreationList() { return getServiceList() .stream() .filter(service -> MCRConfiguration2 .getString(REGISTRATION_SERVICE_CONFIG_PREFIX + service.getServiceID() + "." + CREATION_PREDICATE) .isPresent()) .collect(Collectors.toList()); } public <T extends MCRPersistentIdentifier> MCRPIService<T> getRegistrationService(String id) { return MCRConfiguration2 .<MCRPIService<T>>getSingleInstanceOf(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + id).get(); } private static class InstanceHolder { private static final MCRPIServiceManager INSTANCE = new MCRPIServiceManager(); } }
2,466
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDatacenterException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/exceptions/MCRDatacenterException.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.pi.exceptions; public class MCRDatacenterException extends MCRPersistentIdentifierException { private static final long serialVersionUID = 1L; public MCRDatacenterException(String message) { super(message); } public MCRDatacenterException(String message, Throwable cause) { super(message, cause); } }
1,087
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIdentifierUnresolvableException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/exceptions/MCRIdentifierUnresolvableException.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.pi.exceptions; public class MCRIdentifierUnresolvableException extends MCRDatacenterException { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") private final String identifier; public MCRIdentifierUnresolvableException(String identifier, String message) { super(message); this.identifier = identifier; } public MCRIdentifierUnresolvableException(String identifier, String message, Throwable cause) { super(message, cause); this.identifier = identifier; } }
1,297
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersistentIdentifierException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/exceptions/MCRPersistentIdentifierException.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.pi.exceptions; import java.util.Optional; import org.mycore.common.MCRCatchException; public class MCRPersistentIdentifierException extends MCRCatchException { private static final long serialVersionUID = 1L; private final String translatedAdditionalInformation; private final Integer code; public MCRPersistentIdentifierException(String message) { super(message); translatedAdditionalInformation = null; code = null; } public MCRPersistentIdentifierException(String message, Throwable cause) { super(message, cause); translatedAdditionalInformation = null; code = null; } public MCRPersistentIdentifierException(String message, String translatedAdditionalInformation, int code) { this(message, translatedAdditionalInformation, code, null); } public MCRPersistentIdentifierException(String message, String translatedAdditionalInformation, int code, Exception cause) { super(message, cause); this.translatedAdditionalInformation = translatedAdditionalInformation; this.code = code; } public Optional<String> getTranslatedAdditionalInformation() { return Optional.ofNullable(translatedAdditionalInformation); } public Optional<Integer> getCode() { return Optional.ofNullable(code); } }
2,107
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDatacenterAuthenticationException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/exceptions/MCRDatacenterAuthenticationException.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.pi.exceptions; public class MCRDatacenterAuthenticationException extends MCRDatacenterException { private static final long serialVersionUID = 1L; public MCRDatacenterAuthenticationException() { super("Error with authentication!"); } }
1,006
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRInvalidIdentifierExeption.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/exceptions/MCRInvalidIdentifierExeption.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.pi.exceptions; import java.util.Locale; public class MCRInvalidIdentifierExeption extends MCRPersistentIdentifierException { private static final long serialVersionUID = 1L; public MCRInvalidIdentifierExeption(String idString, String type) { super(String.format(Locale.ENGLISH, "%s is not a valid %s!", idString, type)); } }
1,095
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUUIDURNGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRUUIDURNGenerator.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.pi.urn; import java.util.UUID; import org.mycore.datamodel.metadata.MCRObjectID; /** * Builds a new, unique NISS using Java implementation of the UUID * specification. java.util.UUID creates 'only' version 4 UUIDs. * Version 4 UUIDs are generated from a large random number and do * not include the MAC address. * <p> * UUID = 8*HEX "-" 4*HEX "-" 4*HEX "-" 4*HEX "-" 12*HEX * Example One: 067e6162-3b6f-4ae2-a171-2470b63dff00 * Example Two: 54947df8-0e9e-4471-a2f9-9af509fb5889 * * @author Kathleen Neumann (kkrebs) * @author Sebastian Hofmann */ public class MCRUUIDURNGenerator extends MCRDNBURNGenerator { @Override protected String buildNISS(MCRObjectID mcrID, String additional) { return UUID.randomUUID().toString(); } }
1,509
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDNBURN.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRDNBURN.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.pi.urn; /** * Base class for every DNBURN * * @author Sebastian Hofmann * @author shermann * @author Robert Stephan */ public class MCRDNBURN extends MCRUniformResourceName { public static final String TYPE = "dnbUrn"; public static final String URN_NID = "nbn:de:"; public MCRDNBURN(String subNamespace, String namespaceSpecificString) { super(subNamespace, namespaceSpecificString); } /** * Returns the integer value for a given String for checksum calculation * * @throws IllegalArgumentException when the given char is not allowed */ private static int getIntegerAlias(char c) throws IllegalArgumentException { return switch (c) { case '0' -> 1; case '1' -> 2; case '2' -> 3; case '3' -> 4; case '4' -> 5; case '5' -> 6; case '6' -> 7; case '7' -> 8; case '8' -> 9; case '9' -> 41; /* Letters */ case 'A', 'a' -> 18; case 'B', 'b' -> 14; case 'C', 'c' -> 19; case 'D', 'd' -> 15; case 'E', 'e' -> 16; case 'F', 'f' -> 21; case 'G', 'g' -> 22; case 'H', 'h' -> 23; case 'I', 'i' -> 24; case 'J', 'j' -> 25; case 'K', 'k' -> 42; case 'L', 'l' -> 26; case 'M', 'm' -> 27; case 'N', 'n' -> 13; case 'O', 'o' -> 28; case 'P', 'p' -> 29; case 'Q', 'q' -> 31; case 'R', 'r' -> 12; case 'S', 's' -> 32; case 'T', 't' -> 33; case 'U', 'u' -> 11; case 'V', 'v' -> 34; case 'W', 'w' -> 35; case 'X', 'x' -> 36; case 'Y', 'y' -> 37; case 'Z', 'z' -> 38; /* Special chars */ case '-' -> 39; case ':' -> 17; case '_' -> 43; case '.' -> 47; case '/' -> 45; case '+' -> 49; default -> throw new IllegalArgumentException("Invalid Character specified: " + c); }; } @Override public String getPREFIX() { return super.getPREFIX() + URN_NID; } /** * Method adds leading zeroes to the value parameter * * @param digits the amount of digits * @param value the value to which the zeroes to add */ protected String addLeadingZeroes(int digits, int value) { StringBuilder builder = new StringBuilder(); String maxS = String.valueOf(digits); String valueS = String.valueOf(value); int valueSLen = valueS.length(); int maxSLen = maxS.length(); /* in this case we must add zeroes */ if (valueSLen < maxSLen) { int zeroesToAdd = maxSLen - valueSLen; builder.append("0".repeat(zeroesToAdd)); return builder.append(valueS).toString(); } /* no need to add zeroes at all */ return valueS; } public MCRDNBURN toGranular(String setID, String index) { return new MCRDNBURN(getSubNamespace(), getGranularNamespaceSpecificString(setID, index)); } public MCRDNBURN withSuffix(String suffix) { return new MCRDNBURN(getSubNamespace(), getNamespaceSpecificString() + suffix); } public MCRDNBURN withNamespaceSuffix(String suffix) { return new MCRDNBURN(getSubNamespace() + suffix, getNamespaceSpecificString()); } public MCRDNBURN toGranular(String setID, int i, int max) { return toGranular(setID, addLeadingZeroes(max, i)); } private String getGranularNamespaceSpecificString(String setID, String index) { return getNamespaceSpecificString() + "-" + setID + "-" + index; } @Override public String getNamespaceSpecificString() { return super.getNamespaceSpecificString() + calculateChecksum(); } /** * Calculates the checksum of this urn. Checksum is calculated for urn with * the following structure <code>urn:nbn:de:&lt;your stuff here&gt;</code>. * For other schemas the calculated checksum may not be correct. * * @return the calculated checksum * @see <a href="http://www.persistent-identifier.de/?link=316" * >http://www.persistent-identifier.de/?link=316</a> */ public int calculateChecksum() { String urnbase = getPREFIX() + subNamespace + this.namespaceSpecificString; char[] urn = urnbase.toCharArray(); /* Convert the String into an integer representation */ StringBuilder sourceURNConverted = new StringBuilder(); for (int i = 1; i <= urn.length; i++) { sourceURNConverted.append(getIntegerAlias(urn[i - 1])); } /* Split the string again to calculate the product sum */ urn = sourceURNConverted.toString().toCharArray(); int productSum = 0; for (int i = 1; i <= urn.length; i++) { productSum += i * Character.getNumericValue(urn[i - 1]); } /* * calculation of the ratio, dividing the productSum by the last element * of the converted urn */ int q = productSum / Character.getNumericValue(urn[urn.length - 1]); return q % 10; } }
6,075
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDNBURNParser.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRDNBURNParser.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.pi.urn; import static org.mycore.pi.urn.MCRDNBURN.URN_NID; import static org.mycore.pi.urn.MCRUniformResourceName.PREFIX; import java.util.Optional; import org.mycore.pi.MCRPIParser; public class MCRDNBURNParser implements MCRPIParser<MCRDNBURN> { @Override public Optional<MCRDNBURN> parse(String identifier) { String prefix = PREFIX + URN_NID; if (identifier.startsWith(prefix)) { int lastColon = identifier.lastIndexOf(":") + 1; int checkSumStart = identifier.length() - 1; String namespace = identifier.substring(prefix.length(), lastColon); String nsss = identifier.substring(lastColon, checkSumStart); return Optional.of(new MCRDNBURN(namespace, nsss)); } return Optional.empty(); } }
1,549
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDNBURNGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRDNBURNGenerator.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.pi.urn; import java.util.Objects; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.pi.MCRPIGenerator; import jakarta.validation.constraints.NotNull; public abstract class MCRDNBURNGenerator extends MCRPIGenerator<MCRDNBURN> { private static final String URN_NBN_DE = "urn:nbn:de:"; protected abstract String buildNISS(MCRObjectID mcrID, String additional); /** * Allows the generation of a URN with a specific Namespace * * @param namespace the namespace of the generated URN * @param mcrID the mycore object for which the identifier is generated * @param additional additional information dedicated to the object like a mcrpath * @return a unique persistence identifier */ protected MCRDNBURN generate(@NotNull String namespace, MCRObjectID mcrID, String additional) { Objects.requireNonNull(namespace, "Namespace for an URN must not be null!"); return new MCRDNBURN(namespace, buildNISS(mcrID, additional)); } @Override public MCRDNBURN generate(MCRBase mcrObj, String additional) { return generate(getNamespace(), mcrObj.getId(), additional); } public String getNamespace() { String namespace = getProperties().get("Namespace").trim(); if (namespace.startsWith(URN_NBN_DE)) { namespace = namespace.substring(URN_NBN_DE.length()); } return namespace; } }
2,229
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRHttpUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRHttpUtils.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.pi.urn; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.ssl.SSLContexts; /** * Created by chi on 31.01.17. * * @author Huu Chi Vu */ public class MCRHttpUtils { public static CloseableHttpClient getHttpClient() { return HttpClientBuilder .create() .setSSLContext(SSLContexts.createSystemDefault()) .build(); } }
1,201
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDNBURNRegistrationCheckCronjob.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRDNBURNRegistrationCheckCronjob.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.pi.urn; import java.text.ParseException; import java.util.Date; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRException; import org.mycore.common.MCRSystemUserInformation; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.mcr.cronjob.MCRCronjob; import org.mycore.pi.MCRPIManager; import org.mycore.pi.MCRPIServiceManager; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException; import org.mycore.util.concurrent.MCRFixedUserCallable; import jakarta.persistence.EntityManager; /** * Check if created URNs are registered at the DNB */ public class MCRDNBURNRegistrationCheckCronjob extends MCRCronjob { private static final Logger LOGGER = LogManager.getLogger(); @Override public String getDescription() { return "DNB URN registration check"; } @Override public void runJob() { try { new MCRFixedUserCallable<>(() -> { LOGGER.info("Searching unregistered URNs"); EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); MCRPIManager.getInstance().getUnregisteredIdentifiers(MCRDNBURN.TYPE, -1) .stream() .peek(em::detach) .peek(mcrpi -> LOGGER.info("Found unregistered URN " + mcrpi.getIdentifier())) .forEach(this::checkIfUrnIsRegistered); return null; }, MCRSystemUserInformation.getJanitorInstance()).call(); } catch (Exception e) { LOGGER.error("Failed to check unregistered URNs", e); } } private void checkIfUrnIsRegistered(MCRPI mcrpi) { try { LOGGER.info("Checking unregistered URN {}", mcrpi.getIdentifier()); getDateRegistered(mcrpi).ifPresent(date -> updateServiceFlags(mcrpi, date)); } catch (Exception e) { LOGGER.error("Failed to check unregistered URN " + mcrpi.getIdentifier(), e); } } private Optional<Date> getDateRegistered(MCRPI mcrpi) throws MCRIdentifierUnresolvableException, ParseException { LOGGER.info("Fetching registration date for URN {}", mcrpi.getIdentifier()); MCRDNBURN dnburn = new MCRDNBURNParser() .parse(mcrpi.getIdentifier()) .orElseThrow(() -> new MCRException("Cannot parse Identifier from table: " + mcrpi.getIdentifier())); return Optional.ofNullable(MCRURNUtils.getDNBRegisterDate(dnburn)); } private void updateServiceFlags(MCRPI mcrpi, Date registerDate) { LOGGER.info("Updating service flags for URN {}", mcrpi.getIdentifier()); mcrpi.setRegistered(registerDate); MCRPIServiceManager.getInstance() .getRegistrationService(mcrpi.getService()) .updateFlag(MCRObjectID.getInstance(mcrpi.getMycoreID()), mcrpi.getAdditional(), mcrpi); MCREntityManagerProvider.getCurrentEntityManager().merge(mcrpi); } }
3,870
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCountingDNBURNGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRCountingDNBURNGenerator.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.pi.urn; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.mycore.pi.MCRPIManager; import org.mycore.pi.MCRPIRegistrationInfo; /** * A Generator which helps to generate a URN with a counter inside. */ public abstract class MCRCountingDNBURNGenerator extends MCRDNBURNGenerator { private static final Map<String, AtomicInteger> PATTERN_COUNT_MAP = new HashMap<>(); MCRCountingDNBURNGenerator() { super(); } protected AtomicInteger readCountFromDatabase(String countPattern) { Pattern regExpPattern = Pattern.compile(countPattern); Predicate<String> matching = regExpPattern.asPredicate(); List<MCRPIRegistrationInfo> list = MCRPIManager.getInstance() .getList(MCRDNBURN.TYPE, -1, -1); // extract the number of the PI Optional<Integer> highestNumber = list.stream() .map(MCRPIRegistrationInfo::getIdentifier) .filter(matching) .map(pi -> { // extract the number of the PI Matcher matcher = regExpPattern.matcher(pi); if (matcher.find() && matcher.groupCount() == 1) { String group = matcher.group(1); return Integer.parseInt(group, 10); } else { return null; } }).filter(Objects::nonNull) .min(Comparator.reverseOrder()) .map(n -> n + 1); return new AtomicInteger(highestNumber.orElse(0)); } /** * Gets the count for a specific pattern and increase the internal counter. If there is no internal counter it will * look into the Database and detect the highest count with the pattern. * * @param pattern a reg exp pattern which will be used to detect the highest count. The first group is the count. * e.G. [0-9]+-mods-2017-([0-9][0-9][0-9][0-9])-[0-9] will match 31-mods-2017-0003-3 and the returned * count will be 4 (3+1). * @return the next count */ public final synchronized int getCount(String pattern) { AtomicInteger count = PATTERN_COUNT_MAP .computeIfAbsent(pattern, this::readCountFromDatabase); return count.getAndIncrement(); } }
3,271
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDNBPIDefProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRDNBPIDefProvider.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.pi.urn; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.jdom2.Document; import org.jdom2.JDOMException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRStreamContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException; public class MCRDNBPIDefProvider { private static final String RESOLVING_URL_TEMPLATE = "https://nbn-resolving.org/resolver?identifier={urn}&verb=full&xml=on"; public static Document get(MCRDNBURN urn) throws MCRIdentifierUnresolvableException { return get(urn.asString()); } public static Document get(String identifier) throws MCRIdentifierUnresolvableException { HttpGet get = new HttpGet(RESOLVING_URL_TEMPLATE.replaceAll("\\{urn\\}", identifier)); try (CloseableHttpClient httpClient = MCRHttpUtils.getHttpClient()) { CloseableHttpResponse response = httpClient.execute(get); HttpEntity entity = response.getEntity(); MCRContent content = new MCRStreamContent(entity.getContent(), get.getURI().toString()); return MCRXMLParserFactory.getNonValidatingParser().parseXML(content); } catch (IOException | JDOMException e) { String message = "The identifier " + identifier + " is not resolvable!"; throw new MCRIdentifierUnresolvableException(identifier, message, e); } } }
2,373
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUniformResourceName.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRUniformResourceName.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.pi.urn; import org.mycore.pi.MCRPersistentIdentifier; public class MCRUniformResourceName implements MCRPersistentIdentifier { public static final String PREFIX = "urn:"; protected String subNamespace; protected String namespaceSpecificString; protected MCRUniformResourceName() { } public MCRUniformResourceName(String subNamespace, String namespaceSpecificString) { this.subNamespace = subNamespace; this.namespaceSpecificString = namespaceSpecificString; } public String getPREFIX() { return PREFIX; } public String getSubNamespace() { return subNamespace; } public String getNamespaceSpecificString() { return namespaceSpecificString; } @Override public String asString() { return getPREFIX() + getSubNamespace() + getNamespaceSpecificString(); } }
1,621
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURNResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRURNResolver.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.pi.urn; import java.util.stream.Stream; import org.jdom2.Document; 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 org.mycore.pi.MCRPIResolver; import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException; public class MCRURNResolver extends MCRPIResolver<MCRDNBURN> { public MCRURNResolver() { super("NBN-Resolver"); } @Override public Stream<String> resolve(MCRDNBURN identifier) throws MCRIdentifierUnresolvableException { Document pidefDocument = MCRDNBPIDefProvider.get(identifier); XPathExpression<Element> compile = XPathFactory.instance().compile( ".//pidef:resolving_information/pidef:url_info/pidef:url", Filters.element(), null, MCRConstants.PIDEF_NAMESPACE); return compile.evaluate(pidefDocument).stream().map(Element::getTextTrim); } }
1,718
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURNOAIService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRURNOAIService.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.pi.urn; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.pi.MCRPIService; import org.mycore.pi.MCRPIServiceDates; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; /** * This class registers urn for Metadata. */ public class MCRURNOAIService extends MCRPIService<MCRDNBURN> { public MCRURNOAIService() { super(MCRDNBURN.TYPE); } @Override protected MCRPIServiceDates registerIdentifier(MCRBase obj, String additional, MCRDNBURN urn) throws MCRPersistentIdentifierException { if (!additional.equals("")) { throw new MCRPersistentIdentifierException( getClass().getName() + " doesn't support additional information! (" + additional + ")"); } return new MCRPIServiceDates(null, null); } @Override protected void delete(MCRDNBURN identifier, MCRBase obj, String additional) { // no user information available } @Override protected void update(MCRDNBURN identifier, MCRBase obj, String additional) { // nothing to do here! } }
1,836
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURNGranularOAIService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRURNGranularOAIService.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.pi.urn; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessException; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectDerivate; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.niofs.utils.MCRFileCollectingFileVisitor; import org.mycore.pi.MCRPIManager; import org.mycore.pi.MCRPIService; import org.mycore.pi.MCRPIServiceDates; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.exceptions.MCRPersistentIdentifierException; import jakarta.persistence.EntityManager; /** * Service for assigning granular URNs to Derivate. You can call it with a Derivate-ID and it will assign a Base-URN for * the Derivate and granular URNs for every file in the Derivate (except IgnoreFileNames). If you then add a file to * Derivate you can call with Derivate-ID and additional path of the file. E.g. mir_derivate_00000060 and /image1.jpg * <p> <b>Inscriber is ignored with this {@link MCRPIService}</b> </p> Configuration Parameter(s): <dl> * <dt>IgnoreFileNames</dt> <dd>Comma seperated list of regex file which should not have a urn assigned. Default: * mets\\.xml</dd> </dl> */ public class MCRURNGranularOAIService extends MCRPIService<MCRDNBURN> { private static final Logger LOGGER = LogManager.getLogger(); public MCRURNGranularOAIService() { super(MCRDNBURN.TYPE); } @Override public MCRDNBURN register(MCRBase obj, String additional, boolean updateObject) throws MCRAccessException, MCRPersistentIdentifierException { this.validateRegistration(obj, additional); MCRObjectDerivate derivate = ((MCRDerivate) obj).getDerivate(); MCRDNBURN newURN; if (additional.equals("")) { /* Multiple URN for entire Derivate... */ newURN = registerURNsDerivate(obj, additional, derivate); } else { /* Single URN to one File... */ newURN = registerSingleURN(obj, additional, derivate); } try { MCRMetadataManager.update(obj); } catch (Exception e) { throw new MCRPersistentIdentifierException("Error while updating derivate " + obj.getId(), e); } return newURN; } private MCRDNBURN registerSingleURN(MCRBase obj, String additional, MCRObjectDerivate derivate) throws MCRPersistentIdentifierException { LOGGER.info("Add single urn to {} / {}", obj.getId(), additional); EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); MCRPath filePath = MCRPath.getPath(obj.getId().toString(), additional); if (!Files.exists(filePath)) { throw new MCRPersistentIdentifierException("Invalid path : " + additional); } int count = Math.toIntExact(derivate.getFileMetadata().stream().filter(file -> file.getUrn() != null).count()); MCRDNBURN newURN = (MCRDNBURN) MCRPIManager.getInstance().get(derivate.getURN()) .findFirst().get(); String setID = obj.getId().getNumberAsString(); MCRDNBURN urntoAssign = newURN.toGranular(setID, count + 1, count + 1); derivate.getOrCreateFileMetadata(filePath, urntoAssign.asString()).setUrn(urntoAssign.asString()); MCRPI databaseEntry = new MCRPI(urntoAssign.asString(), getType(), obj.getId().toString(), additional, this.getServiceID(), new MCRPIServiceDates(new Date(), null)); em.persist(databaseEntry); return newURN; } private MCRDNBURN registerURNsDerivate(MCRBase obj, String additional, MCRObjectDerivate derivate) throws MCRPersistentIdentifierException { LOGGER.info("Add URNs to all files of {}", obj.getId()); EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); Path path = MCRPath.getPath(obj.getId().toString(), "/"); MCRFileCollectingFileVisitor<Path> collectingFileVisitor = new MCRFileCollectingFileVisitor<>(); try { Files.walkFileTree(path, collectingFileVisitor); } catch (IOException e) { throw new MCRPersistentIdentifierException("Could not walk derivate file tree!", e); } List<String> ignoreFileNamesList = getIgnoreFileList(); List<Predicate<String>> predicateList = ignoreFileNamesList .stream() .map(Pattern::compile) .map(Pattern::asPredicate) .collect(Collectors.toList()); List<MCRPath> pathList = collectingFileVisitor .getPaths() .stream() .filter(file -> predicateList.stream() .noneMatch(p -> p.test(file.toString().split(":")[1]))) .map(p -> (MCRPath) p) .sorted() .collect(Collectors.toList()); MCRDNBURN newURN = getNewIdentifier(obj, additional); String setID = obj.getId().getNumberAsString(); for (int pathListIndex = 0; pathListIndex < pathList.size(); pathListIndex++) { MCRDNBURN subURN = newURN.toGranular(setID, pathListIndex + 1, pathList.size()); derivate.getOrCreateFileMetadata(pathList.get(pathListIndex), subURN.asString()).setUrn(subURN.asString()); MCRPI databaseEntry = new MCRPI(subURN.asString(), getType(), obj.getId().toString(), pathList.get(pathListIndex).getOwnerRelativePath(), this.getServiceID(), new MCRPIServiceDates(null, null)); em.persist(databaseEntry); } derivate.setURN(newURN.asString()); MCRPI databaseEntry = new MCRPI(newURN.asString(), getType(), obj.getId().toString(), "", this.getServiceID(), new MCRPIServiceDates(new Date(), null)); em.persist(databaseEntry); return newURN; } private List<String> getIgnoreFileList() { List<String> ignoreFileNamesList = new ArrayList<>(); String ignoreFileNames = getProperties().get("IgnoreFileNames"); if (ignoreFileNames != null) { ignoreFileNamesList.addAll(Arrays.asList(ignoreFileNames.split(","))); } else { ignoreFileNamesList.add("mets\\.xml"); // default value } return ignoreFileNamesList; } @Override protected MCRPIServiceDates registerIdentifier(MCRBase obj, String additional, MCRDNBURN urn) { return new MCRPIServiceDates(null, null); } @Override protected void delete(MCRDNBURN identifier, MCRBase obj, String additional) throws MCRPersistentIdentifierException { throw new MCRPersistentIdentifierException("Delete is not supported for " + getType()); } @Override protected void update(MCRDNBURN identifier, MCRBase obj, String additional) { //TODO: improve API, don't override method to do nothing LOGGER.info("No update in this implementation"); } }
8,112
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURNUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRURNUtils.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.pi.urn; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.mycore.pi.MCRPIRegistrationInfo; import org.mycore.pi.urn.rest.MCRDNBURNRestClient; import com.google.gson.JsonElement; public class MCRURNUtils { public static Optional<Date> getDNBRegisterDate(MCRPIRegistrationInfo dnburn) { try { return Optional.of(getDNBRegisterDate(dnburn.getIdentifier())); } catch (ParseException e) { LogManager.getLogger().warn("Could not parse: " + dnburn.getIdentifier(), e); } return Optional.empty(); } public static Date getDNBRegisterDate(MCRDNBURN dnburn) throws ParseException { return getDNBRegisterDate(dnburn.asString()); } public static Date getDNBRegisterDate(String identifier) throws ParseException { String date = MCRDNBURNRestClient.getRegistrationInfo(identifier) .map(info -> info.get("created")) .map(JsonElement::getAsString) .orElse(null); if (date == null) { return null; } return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.GERMAN).parse(date); } }
2,047
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFLURNGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/MCRFLURNGenerator.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.pi.urn; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import org.mycore.datamodel.metadata.MCRObjectID; /** * Builds a new, unique NISS based on the current date and time expressed * in seconds. The resulting NISS is non-speaking, but unique and somewhat * optimized for the nbn:de checksum algorithm. Only one NISS per second * will be generated. * * @author Frank Lützenkirchen */ public class MCRFLURNGenerator extends MCRDNBURNGenerator { private String last; protected synchronized String buildNISS(MCRObjectID mcrID, String additional) { Calendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT+01:00"), Locale.ENGLISH); int yyy = 2268 - now.get(Calendar.YEAR); int ddd = 500 - now.get(Calendar.DAY_OF_YEAR); int hh = now.get(Calendar.HOUR_OF_DAY); int mm = now.get(Calendar.MINUTE); int ss = now.get(Calendar.SECOND); int sss = 99999 - (hh * 3600 + mm * 60 + ss); String ddddd = String.valueOf(yyy * 366 + ddd); String niss = String.valueOf(ddddd.charAt(4)) + ddddd.charAt(2) + ddddd.charAt(1) + ddddd.charAt(3) + ddddd.charAt(0) + sss; if (niss.equals(last)) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } return buildNISS(mcrID, additional); } else { last = niss; return niss; } } }
2,273
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRURNGranularRESTRegistrationCronjob.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRURNGranularRESTRegistrationCronjob.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.pi.urn.rest; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.function.Function; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.backend.jpa.MCREntityManagerProvider; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.annotation.MCRProperty; import org.mycore.mcr.cronjob.MCRCronjob; import org.mycore.pi.MCRPIManager; import org.mycore.pi.MCRPIRegistrationInfo; import org.mycore.pi.backend.MCRPI; import org.mycore.pi.urn.MCRDNBURN; import org.mycore.util.concurrent.MCRFixedUserCallable; /** * Check if created URNs are registered at the DNB */ public class MCRURNGranularRESTRegistrationCronjob extends MCRCronjob { private static final Logger LOGGER = LogManager.getLogger(); private int batchSize = 20; @MCRProperty(name = "BatchSize", defaultName = "MCR.CronJob.Default.URNGranularRESTRegistration.BatchSize") public void setBatchSize(String batchSize) { this.batchSize = Integer.parseInt(batchSize); } @Override public String getDescription() { return "URN granular REST registration"; } @Override public void runJob() { MCRDNBURNRestClient client = new MCRDNBURNRestClient(getBundleProvider(), getUsernamePasswordCredentials()); try { List<MCRPI> unregisteredURNs = MCRPIManager.getInstance().getUnregisteredIdentifiers(MCRDNBURN.TYPE, batchSize); for (MCRPI urn : unregisteredURNs) { client.register(urn).ifPresent(date -> setRegisterDate(urn, date)); } } catch (Exception e) { LOGGER.error("Error occured while registering URNs!", e); } } private void setRegisterDate(MCRPI mcrpi, Date registerDate) { try { new MCRFixedUserCallable<>(() -> { mcrpi.setRegistered(registerDate); return MCREntityManagerProvider.getCurrentEntityManager().merge(mcrpi); }, MCRSystemUserInformation.getJanitorInstance()).call(); } catch (Exception e) { LOGGER.error("Error while set registered date!", e); } } private Function<MCRPIRegistrationInfo, MCRURNJsonBundle> getBundleProvider() { return urn -> MCRURNJsonBundle.instance(urn, MCRDerivateURNUtils.getURL(urn)); } private Optional<UsernamePasswordCredentials> getUsernamePasswordCredentials() { String username = MCRConfiguration2.getString("MCR.PI.DNB.Credentials.Login").orElse(null); String password = MCRConfiguration2.getString("MCR.PI.DNB.Credentials.Password").orElse(null); if (username == null || password == null || username.isBlank() || password.isBlank()) { LOGGER.warn("Could not instantiate {} as required credentials are not set", this.getClass().getName()); return Optional.empty(); } return Optional.of(new UsernamePasswordCredentials(username, password)); } }
3,881
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDNBURNRestClient.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRDNBURNRestClient.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.pi.urn.rest; import static org.apache.http.entity.ContentType.APPLICATION_JSON; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Optional; import java.util.function.Function; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.pi.MCRPIRegistrationInfo; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * <p>Class for registering and updating urn managed by the DNB.</p> * @see <a href="https://api.nbn-resolving.org/v2/docs/index.html">URN-Service API</a> * Created by chi on 25.01.17. * * @author Huu Chi Vu * @author shermann * */ public class MCRDNBURNRestClient { private static final Logger LOGGER = LogManager.getLogger(); private final Function<MCRPIRegistrationInfo, MCRURNJsonBundle> jsonProvider; private final Optional<UsernamePasswordCredentials> credentials; /** * Creates a new operator with the given configuration. * */ public MCRDNBURNRestClient(Function<MCRPIRegistrationInfo, MCRURNJsonBundle> bundleProvider) { this(bundleProvider, Optional.empty()); } /** * @param bundleProvider the provider creating the required json * @param credentials the credentials needed for authentication * */ public MCRDNBURNRestClient(Function<MCRPIRegistrationInfo, MCRURNJsonBundle> bundleProvider, Optional<UsernamePasswordCredentials> credentials) { this.jsonProvider = bundleProvider; this.credentials = credentials; } /** * Returns the base url of the urn registration service. * * @deprecated see {@link MCRDNBURNRestClient#getBaseServiceURL()} * */ @Deprecated protected String getBaseServiceURL(MCRPIRegistrationInfo urn) { return getBaseServiceURL(); } /** * Returns the base url of the urn registration service. * * @return the base url as set in mycore property MCR.PI.URNGranular.API.BaseURL * */ public static String getBaseServiceURL() { return MCRConfiguration2.getString("MCR.PI.URNGranular.API.BaseURL") .orElse("https://api.nbn-resolving.org/sandbox/v2/") + "urns/"; } /** * Returns the base url for checking the existence of a given urn. * @param urn the {@link MCRPIRegistrationInfo} to test * * @return the request url * */ protected String getBaseServiceCheckExistsURL(MCRPIRegistrationInfo urn) { return getBaseServiceURL() + "urn/" + urn.getIdentifier(); } /** * Returns the url for updating the urls assigned to a given urn. * * @param urn the urn * @return the url for updating the urls * */ protected String getUpdateURL(MCRPIRegistrationInfo urn) { return getBaseServiceURL() + "urn/" + urn.getIdentifier() + "/my-urls/"; } /** * <p>Please see list of status codes and their meaning:</p> * * <p>204 No Content: URN is in database. No further information asked.</p> * <p>301 Moved Permanently: The given URN is replaced with a newer version. * This newer version should be used instead.</p> * <p>404 Not Found: The given URN is not registered in system.</p> * <p>410 Gone: The given URN is registered in system but marked inactive.</p> * * @return the registration/update date */ public Optional<Date> register(MCRPIRegistrationInfo urn) { MCRURNJsonBundle bundle = this.jsonProvider.apply(urn); String url = getBaseServiceCheckExistsURL(urn); CloseableHttpResponse response = MCRHttpsClient.get(url, credentials); StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { LOGGER.warn("GET request for {} returns no status line.", url); return Optional.empty(); } int status = statusLine.getStatusCode(); String identifier = urn.getIdentifier(); switch (status) { case HttpStatus.SC_OK -> { LOGGER.info("URN {} is in database. No further information asked", identifier); LOGGER.info("Performing update of url"); return update(urn); } case HttpStatus.SC_NOT_FOUND -> { LOGGER.info("URN {} is not registered", identifier); return registerNew(urn); } default -> { LOGGER.error("Error while check if URN {} exists using url {}.", identifier, url); logFailure("", response, status, urn.getIdentifier(), bundle.getUrl()); } } return Optional.empty(); } public Optional<JsonObject> getRegistrationInfo(MCRPIRegistrationInfo urn) { String identifier = urn.getIdentifier(); return getRegistrationInfo(identifier); } public static Optional<JsonObject> getRegistrationInfo(String identifier) { String url = MCRDNBURNRestClient.getBaseServiceURL() + "/urn/" + identifier; CloseableHttpResponse response = MCRHttpsClient.get(url, Optional.empty()); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_OK -> { HttpEntity entity = response.getEntity(); try { Reader reader = new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8); JsonElement jsonElement = JsonParser.parseReader(reader); return Optional.of(jsonElement.getAsJsonObject()); } catch (Exception e) { LOGGER.error("Could not read Response from " + url); } } default -> { LOGGER.error("Error while get registration info for URN {} using url {}.", identifier, url); MCRDNBURNRestClient.logFailure("", response, statusCode, identifier, url); } } return Optional.empty(); } /** * <p>Registers a new URN.<p/> * * <p>201 Created: URN-Record is successfully created.</p> * <p>303 See other: At least one of the given URLs is already registered under another URN, * which means you should use this existing URN instead of assigning a new one</p> * <p>409 Conflict: URN-Record already exists and can not be created again.</p> * * @return the registration date */ private Optional<Date> registerNew(MCRPIRegistrationInfo urn) { MCRURNJsonBundle bundle = jsonProvider.apply(urn); String json = bundle.toJSON(MCRURNJsonBundle.Format.register); String baseServiceURL = getBaseServiceURL(); CloseableHttpResponse response = MCRHttpsClient.post(baseServiceURL, APPLICATION_JSON.toString(), json, credentials); StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { LOGGER.warn("POST request for {} returns no status line", baseServiceURL); return Optional.empty(); } int postStatus = statusLine.getStatusCode(); String identifier = urn.getIdentifier(); URL url = bundle.getUrl(); switch (postStatus) { case HttpStatus.SC_CREATED -> { LOGGER.info("URN {} registered to {}", identifier, url); return Optional.ofNullable(response.getFirstHeader("date")) .map(Header::getValue) .map(DateTimeFormatter.RFC_1123_DATE_TIME::parse) .map(Instant::from) .map(Date::from); } default -> { LOGGER.error("Error while register new URN {} using url {}.", identifier, url); logFailure(json, response, postStatus, identifier, url); } } return Optional.empty(); } /** * <p>Updates all URLS to a given URN.</p> * * <p>204 No Content: URN was updated successfully</p> * <p>301 Moved Permanently: URN has a newer version</p> * <p>303 See other: URL is registered for another URN</p> * * @return the status code of the request */ private Optional<Date> update(MCRPIRegistrationInfo urn) { MCRURNJsonBundle bundle = jsonProvider.apply(urn); String json = bundle.toJSON(MCRURNJsonBundle.Format.update); String updateURL = getUpdateURL(urn); CloseableHttpResponse response = MCRHttpsClient.patch(updateURL, APPLICATION_JSON.toString(), json, credentials); StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { LOGGER.warn("PATCH request for {} returns no status line", updateURL); return Optional.empty(); } int patchStatus = statusLine.getStatusCode(); String identifier = urn.getIdentifier(); switch (patchStatus) { case HttpStatus.SC_NO_CONTENT -> { LOGGER.info("URN {} updated to {}", identifier, bundle.getUrl()); return Optional.ofNullable(response.getFirstHeader("date")) .map(Header::getValue) .map(DateTimeFormatter.RFC_1123_DATE_TIME::parse) .map(Instant::from) .map(Date::from); } default -> { LOGGER.error("Error while update URN {} using url {}.", identifier, updateURL); logFailure(json, response, patchStatus, identifier, bundle.getUrl()); } } return Optional.empty(); } public static void logFailure(String json, CloseableHttpResponse response, int postStatus, String identifier, URL url) { logFailure(json, response, postStatus, identifier, url.toString()); } public static void logFailure(String json, CloseableHttpResponse response, int status, String identifier, String url) { HttpEntity entity = response.getEntity(); LOGGER.error( "Could not handle urn http request: status={}, " + "urn={}, url={} json={}", status, identifier, url, json); try { String errBody = EntityUtils.toString(entity, "UTF-8"); LOGGER.error("Server error message: {}", errBody); } catch (IOException e) { LOGGER.error("Could not get error body from http request", e); } } }
11,748
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z