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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRDefaultEnrichedDerivateLinkIDFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRDefaultEnrichedDerivateLinkIDFactory.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.datamodel.metadata;
import java.util.stream.Collectors;
import org.jdom2.Element;
public class MCRDefaultEnrichedDerivateLinkIDFactory extends MCRMetaEnrichedLinkIDFactory {
@Override
public MCREditableMetaEnrichedLinkID getDerivateLink(MCRDerivate der) {
final MCREditableMetaEnrichedLinkID derivateLinkID = getEmptyLinkID();
final String mainDoc = der.getDerivate().getInternals().getMainDoc();
derivateLinkID.setReference(der.getId().toString(), null, null);
derivateLinkID.setSubTag("derobject");
final int order = der.getOrder();
derivateLinkID.setOrder(order);
if (mainDoc != null) {
derivateLinkID.setMainDoc(mainDoc);
}
derivateLinkID.setTitles(der.getDerivate().getTitles());
derivateLinkID.setClassifications(
der.getDerivate().getClassifications().stream()
.map(metaClass -> metaClass.category)
.collect(Collectors.toList()));
return derivateLinkID;
}
@Override
public MCREditableMetaEnrichedLinkID fromDom(Element element) {
final MCREditableMetaEnrichedLinkID mcrMetaLinkID = new MCREditableMetaEnrichedLinkID();
mcrMetaLinkID.setFromDOM(element);
return mcrMetaLinkID;
}
}
| 2,036 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaDerivateLink.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaDerivateLink.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.datamodel.metadata;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRException;
import org.mycore.common.xml.MCRXMLFunctions;
import org.mycore.datamodel.niofs.MCRPath;
public class MCRMetaDerivateLink extends MCRMetaLink {
private static final String ANNOTATION = "annotation";
private static final String ATTRIBUTE = "lang";
private static final Logger LOGGER = LogManager.getLogger();
private HashMap<String, String> map;
/** Constructor initializes the HashMap */
public MCRMetaDerivateLink() {
super();
map = new HashMap<>();
}
public void setLinkToFile(MCRPath file) {
if (!file.isAbsolute()) {
throw new IllegalArgumentException("file parameter must be absolute");
}
String owner = file.getOwner();
String path = file.getOwnerRelativePath();
if (path.isEmpty()) {
throw new IllegalArgumentException("file parameter is empty");
}
if (path.charAt(0) != '/') {
path = '/' + path; //normally not the case
}
try {
path = MCRXMLFunctions.encodeURIPath(path, true);
} catch (URISyntaxException uriExc) {
LOGGER.warn("Unable to encode URI path {}", path, uriExc);
}
super.href = owner + path;
}
public void setFromDOM(Element element) throws MCRException {
super.setFromDOM(element);
List<Element> childrenList = element.getChildren(MCRMetaDerivateLink.ANNOTATION);
if (childrenList == null) {
return;
}
for (Element anAnnotation : childrenList) {
String key = anAnnotation.getAttributeValue(MCRMetaDerivateLink.ATTRIBUTE, Namespace.XML_NAMESPACE);
String annotationText = anAnnotation.getText();
this.map.put(key, annotationText);
}
}
public Element createXML() throws MCRException {
Element elm = super.createXML();
for (String key : map.keySet()) {
Element annotationElem = new Element(MCRMetaDerivateLink.ANNOTATION);
annotationElem.setAttribute(MCRMetaDerivateLink.ATTRIBUTE, key, Namespace.XML_NAMESPACE);
String content = map.get(key);
if (content == null || content.length() == 0) {
continue;
}
annotationElem.addContent(content);
elm.addContent(annotationElem);
}
return elm;
}
/**
* Returns the owner of this derivate link. In most cases this is
* the derivate id itself.
*
* @return the owner of this derivate link.
*/
public String getOwner() {
int index = super.href.indexOf('/');
if (index < 0) {
return null;
}
return super.href.substring(0, index);
}
/**
* Returns the URI decoded path of this derivate link. Use {@link #getRawPath()}
* if you want the URI encoded path.
*
* @return path of this derivate link
* @throws URISyntaxException the path couldn't be decoded
*/
public String getPath() throws URISyntaxException {
return new URI(getRawPath()).getPath();
}
/**
* Returns the raw path of this derivate link. Be aware that
* this path is URI encoded. Use {@link #getPath()} if you want
* the URI decoded path.
*
* @return URI encoded path
*/
public String getRawPath() {
int index = super.href.indexOf('/');
if (index < 0) {
return null;
}
return super.href.substring(index);
}
/**
* Returns the {@link MCRPath} to this derivate link.
*
* @return path to this derivate link
* @throws URISyntaxException the path part of this derivate link couldn't be decoded because
* its an invalid URI
*/
public MCRPath getLinkedFile() throws URISyntaxException {
return MCRPath.getPath(getOwner(), getPath());
}
/**
* Validates this MCRMetaDerivateLink. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the linked files is null or does not exist</li>
* </ul>
*
* @throws MCRException the MCRMetaDerivateLink is invalid
*/
public void validate() throws MCRException {
super.validate();
try {
MCRPath linkedFile = getLinkedFile();
if (linkedFile == null) {
throw new MCRException(getSubTag() + ": linked file is null");
}
if (!Files.exists(linkedFile)) {
LOGGER.warn("{}: File not found: {}", getSubTag(), super.href);
}
} catch (Exception exc) {
throw new MCRException(getSubTag() + ": Error while getting linked file " + super.href, exc);
}
}
@Override
public MCRMetaDerivateLink clone() {
MCRMetaDerivateLink clone = (MCRMetaDerivateLink) super.clone();
clone.map = new HashMap<>(this.map);
return clone;
}
}
| 6,136 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaHistoryDate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaHistoryDate.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.datamodel.metadata;
import java.util.ArrayList;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRCalendar;
import org.mycore.common.MCRException;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.GregorianCalendar;
/**
* This class implements all methods for handling the MCRMetaHistoryDate
* part of a metadata object. It uses the GPL licensed ICU library of IBM.
*
* @author Juergen Vogler
* @author Jens Kupferschmidt
* @author Thomas Junge
* @see <a href="http://www.icu-project.org/">http://www.icu-project.org/</a>
*/
public class MCRMetaHistoryDate extends MCRMetaDefault {
/** Logger */
private static final Logger LOGGER = LogManager.getLogger();
/** The maximal length of 'text' */
public static final int MCRHISTORYDATE_MAX_TEXT = 512;
// Data of this class
private ArrayList<MCRMetaHistoryDateText> texts;
private Calendar von;
private Calendar bis;
private int ivon;
private int ibis;
private String calendar;
/**
* This is the constructor. <br>
* The language element was set to configured default. The text element is
* set to an empty string. The calendar is set to 'Gregorian Calendar'. The
* von value is set to MIN_JULIAN_DAY_NUMBER, the bis value is set to
* MAX_JULIAN_DAY_NUMBER;
*/
public MCRMetaHistoryDate() {
super();
texts = new ArrayList<>();
calendar = MCRCalendar.CALENDARS_LIST.get(0);
setDefaultVon();
setDefaultBis();
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>default_lang</em> is
* null, empty or false <b>en </b> was set. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was thrown. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element.<br>
* The text element is set to an empty string. The calendar is set to 'Gregorian Calendar'. The von value
* is set to MIN_JULIAN_DAY_NUMBER, the bis value is set to MAX_JULIAN_DAY_NUMBER;
* @param subtag the name of the subtag
* @param type the optional type string
* @param inherted a value >= 0
*
* @exception MCRException if the parameter values are invalid
*/
public MCRMetaHistoryDate(String subtag, String type, int inherted) throws MCRException {
super(subtag, null, type, inherted);
texts = new ArrayList<>();
calendar = MCRCalendar.CALENDARS_LIST.get(0);
setDefaultVon();
setDefaultBis();
}
/**
* This method set the text field for the default language. If data exists,
* it overwrites the value of text.
*
* @param text
* the text string for a date or range
*/
@Deprecated
public final void setText(String text) {
setText(text, lang);
}
/**
* This method set the text field for the given language. If data exists, it
* overwrites the value of text.
*
* @param text
* the text string for a date or range
* @param lang
* the language of the text in the ISO format
*/
public final void setText(String text, String lang) {
if (text == null || text.length() == 0) {
LOGGER.warn("The text field of MCRMeataHistoryDate is empty.");
return;
}
if (text.length() <= MCRHISTORYDATE_MAX_TEXT) {
text = text.trim();
} else {
text = text.substring(0, MCRHISTORYDATE_MAX_TEXT);
}
if (lang == null || lang.length() == 0) {
addText(text, this.lang);
} else {
addText(text, lang);
}
}
/**
* This method add a MCRMetaHistoryDateTexts instance to the ArrayList of
* texts.
*
* @param text
* the text- String
* @param lang
* the lang- String
*/
public final void addText(String text, String lang) {
if (text == null || text.length() == 0) {
LOGGER.warn("The text field of MCRMeataHistoryDate is empty.");
return;
}
if (lang == null || lang.length() == 0) {
LOGGER.warn("The lang field of MCRMeataHistoryDate is empty.");
return;
}
for (int i = 0; i < texts.size(); i++) {
if (texts.get(i).getLang().equals(lang)) {
texts.remove(i);
break;
}
}
texts.add(new MCRMetaHistoryDateText(text, lang));
}
/**
* This method return the MCRMetaHistoryDateTexts instance with the
* corresponding language.
*
* @param lang
* the language String in ISO format
* @return an instance of MCRMetaHistoryDateTexts or null
*/
public final MCRMetaHistoryDateText getText(String lang) {
if (lang == null) {
return null;
}
return texts.stream()
.filter(text -> text.getLang().equals(lang))
.findFirst()
.orElse(null);
}
/**
* This method return the MCRMetaHistoryDateTexts instance of the indexed
* element of the ArrayList.
*
* @param index
* the index of ArryList texts
* @return an instance of MCRMetaHistoryDateTexts or null
*/
public final MCRMetaHistoryDateText getText(int index) {
if (index >= 0 && index < texts.size()) {
return texts.get(index);
}
return null;
}
/**
* This method read the ArryList texts
*
* @return an ArrayList of MCRMetaHistoryDateTexts instances
*/
public final ArrayList<MCRMetaHistoryDateText> getTexts() {
return texts;
}
/**
* This method read the size of texts
*
* @return the size of the ArrayList of language dependence texts
*/
public final int textSize() {
return texts.size();
}
/**
* The method set the calendar String value.
*
* @param calstr
* the calendar as String, one of CALENDARS.
*/
public final void setCalendar(String calstr) {
if (calstr == null || calstr.trim().length() == 0 || (!MCRCalendar.CALENDARS_LIST.contains(calstr))) {
calendar = MCRCalendar.TAG_GREGORIAN;
LOGGER.warn("The calendar field of MCRMeataHistoryDate is set to default " + MCRCalendar.TAG_GREGORIAN
+ ".");
return;
}
calendar = calstr;
}
/**
* The method set the calendar String value.
*
* @param calendar
* the date of the calendar.
*/
public final void setCalendar(Calendar calendar) {
this.calendar = MCRCalendar.getCalendarTypeString(calendar);
}
/**
* The method set the von values to the default.
*/
public final void setDefaultVon() {
von = new GregorianCalendar();
von.set(Calendar.JULIAN_DAY, MCRCalendar.MIN_JULIAN_DAY_NUMBER);
ivon = MCRCalendar.MIN_JULIAN_DAY_NUMBER;
}
/**
* The method set the bis values to the default.
*/
public final void setDefaultBis() {
bis = new GregorianCalendar();
bis.set(Calendar.JULIAN_DAY, MCRCalendar.MAX_JULIAN_DAY_NUMBER);
ibis = MCRCalendar.MAX_JULIAN_DAY_NUMBER;
}
/**
* This method set the von to the given date of a supported calendar.
*
* @param calendar
* the date of a ICU supported calendar.
*/
public final void setVonDate(Calendar calendar) {
if (calendar == null) {
setDefaultVon();
LOGGER.warn("The calendar to set 'von' is null, default is set.");
} else {
von = calendar;
ivon = von.get(Calendar.JULIAN_DAY);
}
}
/**
* This method set the von to the given date.
*
* @param date
* a date string
* @param calendar
* the calendar as String, one of CALENDARS.
*/
public final void setVonDate(String date, String calendar) {
try {
von = MCRCalendar.getHistoryDateAsCalendar(date, false, calendar);
ivon = von.get(Calendar.JULIAN_DAY);
} catch (Exception e) {
e.printStackTrace();
LOGGER.warn("The von date {} for calendar {} is false. Set to default!", date, calendar);
setDefaultVon();
}
}
/**
* This method set the bis to the given date of a supported calendar.
*
* @param calendar
* the date of a ICU supported calendar
*/
public final void setBisDate(Calendar calendar) {
if (calendar == null) {
setDefaultBis();
LOGGER.warn("The calendar to set 'bis' is null, default is set.");
} else {
bis = calendar;
ibis = bis.get(Calendar.JULIAN_DAY);
}
}
/**
* This method set the bis to the given date.
*
* @param date
* a date string
* @param calendar
* the calendar as String, one of CALENDARS.
*/
public final void setBisDate(String date, String calendar) {
Calendar c = bis;
try {
c = MCRCalendar.getHistoryDateAsCalendar(date, true, calendar);
} catch (Exception e) {
LOGGER.warn("The bis date {} for calendar {} is false.", date, calendar);
c = null;
}
setBisDate(c);
}
/**
* This method get the 'calendar' text element.
*
* @return the calendar string
*/
public final String getCalendar() {
return calendar;
}
/**
* This method get the von element as ICU-Calendar.
*
* @return the date
*/
public final Calendar getVon() {
return von;
}
/**
* This method return the von as string.
*
* @return the date
*/
public final String getVonToString() {
return MCRCalendar.getCalendarDateToFormattedString(von);
}
/**
* This method get the ivon element as Julian Day integer.
*
* @return the date
*/
public final int getIvon() {
return ivon;
}
/**
* This method get the bis element as ICU-Calendar.
*
* @return the date
*/
public final Calendar getBis() {
return bis;
}
/**
* This method return the bis as string.
*
* @return the date
*/
public final String getBisToString() {
return MCRCalendar.getCalendarDateToFormattedString(bis);
}
/**
* This method get the ibis element as Julian Day integer.
*
* @return the date
*/
public final int getIbis() {
return ibis;
}
/**
* This method reads the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
texts.clear(); // clear
for (Element textElement : element.getChildren("text")) {
String text = textElement.getText();
String lang = textElement.getAttributeValue("lang", Namespace.XML_NAMESPACE);
if (lang != null) {
setText(text, lang);
} else {
setText(text);
}
}
setCalendar(element.getChildTextTrim("calendar"));
setVonDate(element.getChildTextTrim("von"), calendar);
setBisDate(element.getChildTextTrim("bis"), calendar);
/**
* If dates higher than 1582 and calendar is Julian the calendar must switch to
* Gregorian cause the date transforming is implicit in the calendar methods. In
* other cases before 1582 both calendar are equal.
* */
if (calendar.equals(MCRCalendar.TAG_JULIAN)) {
calendar = MCRCalendar.TAG_GREGORIAN;
}
}
/**
* This method creates a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaHistoryDate definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaHistoryDate part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
for (MCRMetaHistoryDateText text : texts) {
Element elmt = new Element("text");
elmt.addContent(text.getText());
elmt.setAttribute("lang", text.getLang(), Namespace.XML_NAMESPACE);
elm.addContent(elmt);
}
elm.addContent(new Element("calendar").addContent(calendar));
elm.addContent(new Element("ivon").addContent(Integer.toString(ivon)));
elm.addContent(new Element("von").addContent(getVonToString()));
elm.addContent(new Element("ibis").addContent(Integer.toString(ibis)));
elm.addContent(new Element("bis").addContent(getBisToString()));
return elm;
}
/**
* Validates this MCRMetaHistoryDate. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the number of texts is 0 (empty texts are delete)</li>
* <li>von is null or bis is null or calendar is null</li>
* </ul>
*
* @throws MCRException the MCRMetaHistoryDate is invalid
*/
@Override
public void validate() throws MCRException {
super.validate();
texts.removeIf(textItem -> !textItem.isValid());
if (texts.size() == 0) {
throw new MCRException(getSubTag() + ": no texts defined");
}
if (von == null || bis == null || calendar == null) {
throw new MCRException(getSubTag() + ": von,bis or calendar are null");
}
if (ibis < ivon) {
Calendar swp = (Calendar) von.clone();
setVonDate((Calendar) bis.clone());
setBisDate(swp);
}
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaHistoryDate clone() {
MCRMetaHistoryDate clone = (MCRMetaHistoryDate) super.clone();
clone.texts = this.texts.stream().map(MCRMetaHistoryDateText::clone)
.collect(Collectors.toCollection(ArrayList::new));
clone.bis = (Calendar) this.bis.clone();
clone.von = (Calendar) this.von.clone();
clone.ibis = this.ibis;
clone.ivon = this.ivon;
clone.calendar = this.calendar;
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
for (MCRMetaHistoryDateText text : texts) {
LOGGER.debug("Text / lang = {} / {}", text.getText(), text.getLang());
}
LOGGER.debug("Calendar = {}", calendar);
LOGGER.debug("Von (String) = {}", getVonToString());
LOGGER.debug("Von (JulianDay) = {}", ivon);
LOGGER.debug("Bis (String) = {}", getBisToString());
LOGGER.debug("Bis (JulianDay) = {}", ibis);
LOGGER.debug("");
}
}
/**
* This method compares this instance with a MCRMetaHistoryDate object
*/
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaHistoryDate other = (MCRMetaHistoryDate) obj;
boolean fieldTest = Objects.equals(this.calendar, other.calendar) && Objects.equals(this.ivon, other.ivon);
boolean textTest = equalText(other.getTexts());
return fieldTest && textTest;
}
private boolean equalText(ArrayList<MCRMetaHistoryDateText> objtexts) {
boolean testflag = true;
int size = texts.size() < objtexts.size() ? texts.size() : objtexts.size();
for (int i = 0; i < size; i++) {
testflag &= texts.get(i).equals(objtexts.get(i));
}
return testflag;
}
/**
* This class describes the structure of pair of language an text. The
* language notation is in the ISO format.
*
*/
public static class MCRMetaHistoryDateText implements Cloneable {
private String text;
private String lang;
public MCRMetaHistoryDateText() {
text = "";
lang = DEFAULT_LANGUAGE;
}
public MCRMetaHistoryDateText(String text, String lang) {
setText(text, lang);
}
/**
* This method get the text element as String.
*
* @return the text
*/
public String getText() {
return text;
}
/**
* This method get the language element as String of ISO code.
*
* @return the language
*/
public String getLang() {
return lang;
}
/**
* This method set the text element with the corresponding language.
*
* @param text
* the text String
* @param lang
* the language String
*/
public void setText(String text, String lang) {
if (lang == null || lang.length() == 0) {
this.lang = DEFAULT_LANGUAGE;
} else {
this.lang = lang;
}
if (text == null || text.length() == 0) {
this.text = "";
} else {
this.text = text;
}
}
/**
* This method set the text element.
*
* @param text
* the text String of a date value
*/
@Deprecated
public void setText(String text) {
if (text == null || text.length() == 0) {
this.text = "";
} else {
this.text = text;
}
}
/**
* This method set the lang element.
*
* @param lang
* the language String of a date value
*/
@Deprecated
public void setLang(String lang) {
if (lang == null || lang.length() == 0) {
this.lang = DEFAULT_LANGUAGE;
} else {
this.lang = lang;
}
}
/**
* This method validate the content. If lang and text are not empty, it return true otherwise it return false.
*
* @return true if the content is valid.
*/
public boolean isValid() {
return !(lang.length() == 0 || text.length() == 0);
}
/**
* This method check the equivalence of lang and text between this object
* and a given MCRMetaHistoryDateText object.
*
* @param obj a MCRMetaHistoryDateText instance
* @return true if both parts are equal
*/
public boolean equals(MCRMetaHistoryDateText obj) {
return lang.equals(obj.getLang()) && text.equals(obj.getText());
}
@Override
protected MCRMetaHistoryDateText clone() {
MCRMetaHistoryDateText clone = null;
try {
clone = (MCRMetaHistoryDateText) super.clone();
} catch (Exception e) {
// this can not happen!
}
clone.text = this.text;
clone.lang = this.lang;
return clone;
}
}
}
| 20,969 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileMetaEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRFileMetaEventHandler.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.datamodel.metadata;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.common.events.MCREventManager;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.niofs.MCRPath;
/**
* Handles category links to files
* @author Thomas Scheffler (yagee)
*
*/
public class MCRFileMetaEventHandler extends MCREventHandlerBase {
private static MCRCategLinkService CATEGLINK_SERVICE = MCRCategLinkServiceFactory.getInstance();
private static Logger LOGGER = LogManager.getLogger(MCRFileMetaEventHandler.class);
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
MCRObjectID derivateID = der.getId();
MCRObjectDerivate objectDerivate = der.getDerivate();
List<MCRFileMetadata> fileMetadata = objectDerivate.getFileMetadata();
for (MCRFileMetadata metadata : fileMetadata) {
Collection<MCRCategoryID> categories = metadata.getCategories();
if (!categories.isEmpty()) {
MCRPath path = MCRPath.getPath(derivateID.toString(), metadata.getName());
MCRCategLinkReference linkReference = new MCRCategLinkReference(path);
CATEGLINK_SERVICE.setLinks(linkReference, categories);
}
}
}
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
HashSet<MCRCategLinkReference> before = new HashSet<>(CATEGLINK_SERVICE.getReferences(der.getId().toString()));
handleDerivateDeleted(evt, der);
handleDerivateCreated(evt, der);
HashSet<MCRCategLinkReference> after = new HashSet<>(CATEGLINK_SERVICE.getReferences(der.getId().toString()));
HashSet<MCRCategLinkReference> combined = new HashSet<>(before);
combined.addAll(after);
for (MCRCategLinkReference ref : combined) {
MCRObjectID derId = der.getId();
String path = ref.getObjectID();
MCRPath file = MCRPath.getPath(derId.toString(), path);
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(file, BasicFileAttributes.class);
} catch (IOException e) {
LOGGER.warn("File is linked to category but cannot be read:{}{}", der.getId(), ref.getObjectID(), e);
continue;
}
MCREvent fileEvent = new MCREvent(MCREvent.ObjectType.PATH, MCREvent.EventType.INDEX);
fileEvent.put(MCREvent.PATH_KEY, file);
fileEvent.put(MCREvent.FILEATTR_KEY, attrs);
MCREventManager.instance().handleEvent(fileEvent);
}
}
@Override
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
Collection<MCRCategLinkReference> references = CATEGLINK_SERVICE.getReferences(der.getId().toString());
CATEGLINK_SERVICE.deleteLinks(references);
}
@Override
protected void handlePathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) {
if (attrs != null && attrs.isDirectory()) {
return;
}
MCRPath mcrPath = MCRPath.toMCRPath(path);
MCRObjectID derivateID = MCRObjectID.getInstance(mcrPath.getOwner());
if (!MCRMetadataManager.exists(derivateID)) {
LOGGER.warn("Derivate {} from file '{}' does not exist.", derivateID, path);
return;
}
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
MCRObjectDerivate objectDerivate = derivate.getDerivate();
String filePath = '/' + path.subpath(0, path.getNameCount()).toString();
Optional<MCRFileMetadata> fileMetaWithoutURN = objectDerivate.getFileMetadata()
.stream()
.filter(m -> filePath.equals(m.getName()))
.filter(m -> m.getUrn() == null && m.getHandle() == null)
.findAny();
if (fileMetaWithoutURN.isPresent() && objectDerivate.deleteFileMetaData(filePath)) {
try {
MCRMetadataManager.update(derivate);
} catch (MCRPersistenceException | MCRAccessException e) {
throw new MCRPersistenceException("Could not update derivate: " + derivateID, e);
}
}
}
}
| 5,662 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaElement.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaElement.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.datamodel.metadata;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* This class is designed to to have a basic class for all metadata. The class
* has inside a ArrayList that holds all metaddata elements for one XML tag.
* Furthermore, this class supports the linking of a document owing this
* metadata element to another document, the id of which is given in the
* xlink:href attribute of the MCRMetaLink representing the link. The class name
* of such a metadata element must be MCRMetaLink, and the metadata element is
* considered to be a folder of links.
*
* @author Jens Kupferschmidt
* @author Mathias Hegner
*/
public class MCRMetaElement implements Iterable<MCRMetaInterface>, Cloneable {
// common data
public static final String DEFAULT_LANGUAGE = MCRConfiguration2.getString("MCR.Metadata.DefaultLang")
.orElse(MCRConstants.DEFAULT_LANG);
public static final boolean DEFAULT_HERITABLE = MCRConfiguration2.getBoolean("MCR.MetaElement.defaults.heritable")
.orElse(false);
public static final boolean DEFAULT_NOT_INHERIT = MCRConfiguration2
.getBoolean("MCR.MetaElement.defaults.notinherit").orElse(true);
private static final String META_PACKAGE_NAME = "org.mycore.datamodel.metadata.";
// logger
static Logger LOGGER = LogManager.getLogger();
private Class<? extends MCRMetaInterface> clazz = null;
private String tag = null;
private boolean heritable;
private boolean notinherit;
private ArrayList<MCRMetaInterface> list = null;
/**
* This is the constructor of the MCRMetaElement class. The default language
* for the element was set to <b>MCR.Metadata.DefaultLang</b>.
*/
public MCRMetaElement() {
list = new ArrayList<>();
heritable = DEFAULT_HERITABLE;
notinherit = DEFAULT_NOT_INHERIT;
}
/**
* This is the constructor of the MCRMetaElement class.
* @param tag
* the name of this tag
* @param heritable
* set this flag to true if all child objects of this element can
* inherit this data
* @param notinherit
* set this flag to true if this element should not inherit from
* his parent object
* @param list
* a list of MCRMeta... data lines to add in this element (can be null)
*/
public MCRMetaElement(Class<? extends MCRMetaInterface> clazz, String tag, boolean heritable, boolean notinherit,
List<? extends MCRMetaInterface> list) {
this();
this.clazz = clazz;
setTag(tag);
this.heritable = heritable;
this.notinherit = notinherit;
if (list != null) {
this.list.addAll(list);
}
}
/**
* This methode return the name of this metadata class as string.
*
* @return the name of this metadata class as string
*/
public final String getClassName() {
return getClazz().getSimpleName();
}
/**
* This method returns the instance of an element from the list with index
* i.
*
* @return the instance of an element, if index is out of range return null
*/
public final MCRMetaInterface getElement(int index) {
if ((index < 0) || (index > list.size())) {
return null;
}
return list.get(index);
}
/**
* This method returns the instance of an element from the list with the given
* name
*
* @return the instance of the element with the given name or null if there is no such element
* */
public final MCRMetaInterface getElementByName(String name) {
for (MCRMetaInterface sub : this) {
if (sub.getSubTag().equals(name)) {
return sub;
}
}
return null;
}
/**
* This methode return the heritable flag of this metadata as boolean value.
*
* @return the heritable flag of this metadata class
*/
public final boolean isHeritable() {
return heritable;
}
/**
* This methode return the nonherit flag of this metadata as boolean value.
*
* @return the notherit flag of this metadata class
*/
public final boolean inheritsNot() {
return notinherit;
}
/**
* This methode return the tag of this metadata class as string.
*
* @return the tag of this metadata class as string
*/
public final String getTag() {
return tag;
}
/**
* This methode set the heritable flag for the metadata class.
*
* @param heritable
* the heritable flag as boolean value
*/
public void setHeritable(boolean heritable) {
this.heritable = heritable;
}
/**
* This methode set the notinherit flag for the metadata class.
*
* @param notinherit
* the notinherit flag as boolean value
*/
public void setNotInherit(boolean notinherit) {
this.notinherit = notinherit;
}
/**
* This methode set the tag for the metadata class.
*
* @param tag
* the tag for the metadata class
*/
public void setTag(String tag) {
MCRUtils.filterTrimmedNotEmpty(tag)
.ifPresent(s -> this.tag = s);
}
/**
* This methode set the element class for the metadata elements.
*
* @param clazz
* the class for the metadata elements
*/
public final void setClass(Class<? extends MCRMetaInterface> clazz) {
this.clazz = clazz;
}
public Class<? extends MCRMetaInterface> getClazz() {
return clazz;
}
/**
* <em>size</em> returns the number of elements in this instance.
*
* @return int the size of "list"
*/
public final int size() {
return list.size();
}
/**
* The method add a metadata object, that implements the MCRMetaInterface to
* this element.
*
* @param obj
* a metadata object
* @exception MCRException
* if the class name of the object is not the same like the
* name of all store metadata in this element.
*/
public final void addMetaObject(MCRMetaInterface obj) {
list.add(obj);
}
/**
* This method remove the instance of an element from the list with index
* i.
*
* @return true if the instance is removed, otherwise return else
*/
public final boolean removeElement(int index) {
if ((index < 0) || (index > list.size())) {
return false;
}
list.remove(index);
return true;
}
/**
* The method remove a metadata object, that implements the MCRMetaInterface to
* this element.
*
* @param obj
* a metadata object
* @exception MCRException
* if the class name of the object is not the same like the
* name of all store metadata in this element.
* @return true if this <code>MCRMetaElement</code> contained the specified
* <code>MCRMetaInterface</code>
*/
public final boolean removeMetaObject(MCRMetaInterface obj) {
return list.remove(obj);
}
/**
* The method removes all inherited metadata objects of this MCRMetaElement.
*/
public final void removeInheritedMetadata() {
list.removeIf(mi -> mi.getInherited() > 0);
}
/**
* This methode read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
* @exception MCRException
* if the class can't loaded
*/
@SuppressWarnings("unchecked")
public final void setFromDOM(Element element) throws MCRException {
String fullname;
Class<? extends MCRMetaInterface> forName;
try {
String classname = element.getAttributeValue("class");
if (classname == null) {
throw new MCRException("Missing required class attribute in element " + element.getName());
}
fullname = META_PACKAGE_NAME + classname;
forName = MCRClassTools.forName(fullname);
setClass(forName);
} catch (ClassNotFoundException e) {
throw new MCRException(e);
}
tag = element.getName();
String heritable = element.getAttributeValue("heritable");
if (heritable != null) {
setHeritable(Boolean.parseBoolean(heritable));
}
String notInherit = element.getAttributeValue("notinherit");
if (notInherit != null) {
setNotInherit(Boolean.parseBoolean(notInherit));
}
List<Element> elementList = element.getChildren();
for (Element subtag : elementList) {
MCRMetaInterface obj;
try {
obj = forName.getDeclaredConstructor().newInstance();
obj.setFromDOM(subtag);
} catch (ReflectiveOperationException e) {
throw new MCRException(fullname + " ReflectiveOperationException", e);
}
list.add(obj);
}
}
/**
* This methode create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRLangText definition for the given subtag.
*
* @param flag
* true if all inherited data should be include, else false
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML Element part
*/
public final Element createXML(boolean flag) throws MCRException {
try {
validate();
} catch (MCRException exc) {
debug();
throw new MCRException("MCRMetaElement : The content is not valid: Tag=" + this.tag, exc);
}
Element elm = new Element(tag);
elm.setAttribute("class", getClassName());
elm.setAttribute("heritable", String.valueOf(heritable));
elm.setAttribute("notinherit", String.valueOf(notinherit));
list
.stream()
.filter(metaInterface -> (flag || metaInterface.getInherited() == 0))
.map(MCRMetaInterface::createXML)
.forEachOrdered(elm::addContent);
return elm;
}
/**
* Creates the JSON representation of this metadata element.
*
* <pre>
* {
* class: 'MCRMetaLangText',
* heritable: true,
* notinherit: false,
* data: [
* {@link MCRMetaInterface#createJSON()},
* ...
* ]
* }
* </pre>
*
* @return a json gson representation of this metadata element
*/
public JsonObject createJSON(boolean flag) {
JsonObject meta = new JsonObject();
meta.addProperty("class", getClassName());
meta.addProperty("heritable", isHeritable());
meta.addProperty("notinherit", notinherit);
JsonArray data = new JsonArray();
list
.stream()
.filter(metaInterface -> (flag || metaInterface.getInherited() == 0))
.map(MCRMetaInterface::createJSON)
.forEachOrdered(data::add);
meta.add("data", data);
return meta;
}
/**
* This methode check the validation of the content of this class. The
* methode returns <em>true</em> if
* <ul>
* <li>the classname is not null or empty
* <li>the tag is not null or empty
* <li>if the list is empty
* <li>the lang value was supported
* </ul>
* otherwise the methode return <em>false</em>
*
* @return a boolean value
*/
public final boolean isValid() {
try {
validate();
return true;
} catch (MCRException exc) {
LOGGER.warn("The '{}' is invalid.", getTag(), exc);
}
return false;
}
/**
* Validates this MCRMetaElement. This method throws an exception if:
* <ul>
* <li>the classname is not null or empty</li>
* <li>the tag is not null or empty</li>
* <li>if the list is empty</li>
* <li>the lang value was supported</li>
* </ul>
*
* @throws MCRException the MCRMetaElement is invalid
*/
public void validate() throws MCRException {
tag = MCRUtils.filterTrimmedNotEmpty(tag).orElse(null);
if (tag == null) {
throw new MCRException("No tag name defined!");
}
if (clazz == null) {
throw new MCRException(getTag() + ": @class is not defined");
}
if (!clazz.getPackage().getName().equals(META_PACKAGE_NAME.substring(0, META_PACKAGE_NAME.length() - 1))) {
throw new MCRException(
getTag() + ": package " + clazz.getPackage().getName() + " does not equal " + META_PACKAGE_NAME);
}
if (list.size() == 0) {
throw new MCRException(getTag() + ": does not contain any sub elements");
}
}
/**
* This method make a clone of this class.
*/
@Override
public final MCRMetaElement clone() {
MCRMetaElement out = new MCRMetaElement();
out.setClass(getClazz());
out.setTag(tag);
out.setHeritable(heritable);
out.setNotInherit(notinherit);
for (int i = 0; i < size(); i++) {
MCRMetaInterface mif = (list.get(i)).clone();
out.addMetaObject(mif);
}
return out;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
public final void debug() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ClassName = {}", getClassName());
LOGGER.debug("Tag = {}", tag);
LOGGER.debug("Heritable = {}", String.valueOf(heritable));
LOGGER.debug("NotInherit = {}", String.valueOf(notinherit));
LOGGER.debug("Elements = {}", String.valueOf(list.size()));
LOGGER.debug(" ");
for (MCRMetaInterface aList : list) {
aList.debug();
}
}
}
/**
* Streams the {@link MCRMetaInterface} of this element.
*
* @return stream of MCRMetaInterface's
*/
public Stream<MCRMetaInterface> stream() {
return list.stream();
}
@Override
public Iterator<MCRMetaInterface> iterator() {
return list.iterator();
}
}
| 15,844 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectMetadata.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectMetadata.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.datamodel.metadata;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import com.google.gson.JsonObject;
/**
* This class implements all methode for handling one object metadata part. This
* class uses only metadata type classes of the general datamodel code of
* MyCoRe.
*
* @author Jens Kupferschmidt
* @author Mathias Hegner
*/
public class MCRObjectMetadata implements Iterable<MCRMetaElement> {
private static final Logger LOGGER = LogManager.getLogger();
// common data
private boolean heritedXML;
// metadata list
private final ArrayList<MCRMetaElement> metadataElements;
/**
* This is the constructor of the MCRObjectMetadata class. It set the
* default language for all metadata to the value from the configuration
* propertie <em>MCR.Metadata.DefaultLang</em>.
*
* @exception MCRConfigurationException
* a special exception for configuartion data
*/
public MCRObjectMetadata() throws MCRConfigurationException {
heritedXML = MCRConfiguration2.getBoolean("MCR.Metadata.HeritedForXML").orElse(true);
metadataElements = new ArrayList<>();
}
/**
* <em>size</em> returns the number of tag names in the ArrayList.
*
* @return int number of tags and meta elements
*/
public int size() {
return metadataElements.size();
}
/**
* <em>getHeritableMetadata</em> returns an instance of MCRObjectMetadata
* containing all the heritable MetaElement's of this object.
*
* @return MCRObjectMetadata the heritable part of this MCRObjectMetadata
*/
public final MCRObjectMetadata getHeritableMetadata() {
MCRObjectMetadata heritableMetadata = new MCRObjectMetadata();
stream().filter(MCRMetaElement::isHeritable).map(MCRMetaElement::clone).forEach(metaElement -> {
metaElement.stream().forEach(MCRMetaInterface::incrementInherited);
heritableMetadata.setMetadataElement(metaElement);
});
return heritableMetadata;
}
/**
* <em>removeInheritedMetadata</em> removes all inherited metadata elements
*/
public final void removeInheritedMetadata() {
Iterator<MCRMetaElement> elements = metadataElements.iterator();
while (elements.hasNext()) {
MCRMetaElement me = elements.next();
me.removeInheritedMetadata();
//remove meta element if empty (else isValid() will fail)
if (me.size() == 0) {
elements.remove();
}
}
}
/**
* This method append MCRMetaElement's from a given MCRObjectMetadata to
* this data set.
*
* @param input
* the MCRObjectMetadata, that should merged into this data set
*/
public final void appendMetadata(MCRObjectMetadata input) {
for (MCRMetaElement newelm : input) {
int pos = -1;
for (int j = 0; j < size(); j++) {
if (metadataElements.get(j)
.getTag()
.equals(newelm.getTag())) {
pos = j;
}
}
if (pos != -1) {
if (!metadataElements.get(pos)
.inheritsNot()) {
metadataElements.get(pos)
.setHeritable(true);
for (int j = 0; j < newelm.size(); j++) {
MCRMetaInterface obj = newelm.getElement(j);
metadataElements.get(pos)
.addMetaObject(obj);
}
}
} else {
metadataElements.add(newelm);
}
}
}
/**
* This method return the MCRMetaElement selected by tag. If this was not
* found, null was returned.
*
* @param tag
* the element tag
* @return the MCRMetaElement for the tag
*/
public final MCRMetaElement getMetadataElement(String tag) {
for (MCRMetaElement sub : this) {
if (sub.getTag().equals(tag)) {
return sub;
}
}
return null;
}
/**
* This method return the MCRMetaElement selected by an index. If this was
* not found, null was returned.
*
* @param index
* the element index
* @return the MCRMetaElement for the index
*/
public final MCRMetaElement getMetadataElement(int index) {
return metadataElements.get(index);
}
/**
* sets the given MCRMetaElement to the list. If the tag exists
* the MCRMetaElement was replaced.
*
* @param obj
* the MCRMetaElement object
*/
public final void setMetadataElement(MCRMetaElement obj) {
MCRMetaElement old = getMetadataElement(obj.getTag());
if (old == null) {
metadataElements.add(obj);
return;
}
int i = metadataElements.indexOf(old);
metadataElements.remove(i);
metadataElements.add(i, obj);
}
/**
* Removes the given element.
*
* @param element the meta element to remove
* @return true if the element was removed
*/
public final boolean removeMetadataElement(MCRMetaElement element) {
return metadataElements.remove(element);
}
/**
* This method remove the MCRMetaElement selected by tag from the list.
*
* @return true if set was successful, otherwise false
*/
public final MCRMetaElement removeMetadataElement(String tag) {
MCRMetaElement old = getMetadataElement(tag);
if (old != null) {
removeMetadataElement(old);
return old;
}
return null;
}
/**
* This method remove the MCRMetaElement selected a index from the list.
*
* @return true if set was successful, otherwise false
*/
public final MCRMetaElement removeMetadataElement(int index) {
if (index < 0 || index > size()) {
return null;
}
return metadataElements.remove(index);
}
/**
* Finds the first, not inherited {@link MCRMetaInterface} with the given tag.
*
* @param tag the metadata tag e.g. 'maintitles'
* @return an optional of the first meta interface
*/
public final <T extends MCRMetaInterface> Optional<T> findFirst(String tag) {
return findFirst(tag, null, 0);
}
/**
* Finds the first, not inherited {@link MCRMetaInterface} with the given tag
* where the @type attribute is equal to the given type. If the type is null,
* this method doesn't care if the @type attribute is set or not.
*
* @param tag the metadata tag e.g. 'subtitles'
* @param type the @type attribute which have to match
* @return an optional of the first meta interface
*/
public final <T extends MCRMetaInterface> Optional<T> findFirst(String tag, String type) {
return findFirst(tag, type, 0);
}
/**
* Finds the first {@link MCRMetaInterface} with the given tag where the
* inheritance level is equal the inherited value.
*
* @param tag the metadata tag e.g. 'maintitles'
* @param inherited level of inheritance. Zero is the current level,
* parent is one and so on.
* @return an optional of the first meta interface
*/
public final <T extends MCRMetaInterface> Optional<T> findFirst(String tag, Integer inherited) {
return findFirst(tag, null, inherited);
}
/**
* Finds the first {@link MCRMetaInterface} with the given tag where the
* inheritance level is equal the inherited value and the @type attribute
* is equal to the given type. If the type is null, this method doesn't
* care if the @type attribute is set or not.
*
* @param tag the metadata tag e.g. 'subtitles'
* @param type the @type attribute which have to match
* @param inherited level of inheritance. Zero is the current level,
* parent is one and so on.
* @return an optional of the first meta interface
*/
public final <T extends MCRMetaInterface> Optional<T> findFirst(String tag, String type, Integer inherited) {
Stream<T> stream = stream(tag);
return stream.filter(filterByType(type))
.filter(filterByInherited(inherited))
.findFirst();
}
/**
* Streams the {@link MCRMetaElement}'s.
*
* @return stream of MCRMetaElement's
*/
public final Stream<MCRMetaElement> stream() {
return metadataElements.stream();
}
/**
* Streams the {@link MCRMetaInterface}s of the given tag.
* <pre>
* {@code
* Stream<MCRMetaLangText> stream = mcrObjectMetadata.stream("maintitles");
* }
* </pre>
*
* @param tag tag the metadata tag e.g. 'maintitles'
* @return a stream of the requested meta interfaces
*/
public final <T extends MCRMetaInterface> Stream<T> stream(String tag) {
Optional<MCRMetaElement> metadata = Optional.ofNullable(getMetadataElement(tag));
// waiting for https://bugs.openjdk.java.net/browse/JDK-8050820
return metadata.map(
mcrMetaInterfaces -> StreamSupport.stream(mcrMetaInterfaces.spliterator(), false).map(metaInterface -> {
@SuppressWarnings("unchecked")
T t = (T) metaInterface;
return t;
})).orElseGet(Stream::empty);
}
/**
* Lists the {@link MCRMetaInterface}s of the given tag. This is not a
* live list. Removals or adds are not reflected on the
* {@link MCRMetaElement}. Use {@link #getMetadataElement(String)}
* for those operations.
*
* <pre>
* {@code
* List<MCRMetaLangText> list = mcrObjectMetadata.list("maintitles");
* }
* </pre>
*
* @param tag tag the metadata tag e.g. 'maintitles'
* @return a list of the requested meta interfaces
*/
public final <T extends MCRMetaInterface> List<T> list(String tag) {
Stream<T> stream = stream(tag);
return stream.collect(Collectors.toList());
}
/**
* Checks if the type of an {@link MCRMetaInterface} is equal
* the given type. If the given type is null, true is returned.
*
* @param type the type to compare
* @return true if the types are equal
*/
private Predicate<MCRMetaInterface> filterByType(String type) {
return (metaInterface) -> type == null || type.equals(metaInterface.getType());
}
/**
* Checks if the inheritance level of an {@link MCRMetaInterface}
* is equal the given inherited value.
*
* @param inherited the inherited value
* @return true if the inherited values are equal
*/
private Predicate<MCRMetaInterface> filterByInherited(Integer inherited) {
return (metaInterface) -> metaInterface.getInherited() == inherited;
}
/**
* This methode read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a list of relevant DOM elements for the metadata
* @exception MCRException
* if a problem occured
*/
public final void setFromDOM(Element element) throws MCRException {
List<Element> elements = element.getChildren();
metadataElements.clear();
for (Element sub : elements) {
MCRMetaElement obj = new MCRMetaElement();
obj.setFromDOM(sub);
metadataElements.add(obj);
}
}
/**
* This methode create a XML stream for all metadata.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML data of the metadata part
*/
public final Element createXML() throws MCRException {
try {
validate();
} catch (MCRException exc) {
throw new MCRException("MCRObjectMetadata : The content is not valid.", exc);
}
Element elm = new Element("metadata");
for (MCRMetaElement e : this) {
elm.addContent(e.createXML(heritedXML));
}
return elm;
}
/**
* Creates the JSON representation of this metadata container.
*
* <pre>
* {
* "def.maintitles": {
* {@link MCRMetaLangText#createJSON()}
* }
* "def.dates": {
* {@link MCRMetaISO8601Date#createJSON()}
* }
* ...
* }
* </pre>
*
* @return a json gson representation of this metadata container
*/
public JsonObject createJSON() {
JsonObject metadata = new JsonObject();
StreamSupport.stream(spliterator(), true)
.forEach(metaElement -> metadata.add(metaElement.getTag(), metaElement.createJSON(heritedXML)));
return metadata;
}
/**
* This methode check the validation of the content of this class. The
* methode returns <em>true</em> if
* <ul>
* <li>the array is empty
* <li>the default lang value was supported
* </ul>
* otherwise the methode return <em>false</em>
*
* @return a boolean value
*/
public final boolean isValid() {
try {
validate();
return true;
} catch (MCRException exc) {
LOGGER.warn("The <metadata> element is invalid.", exc);
}
return false;
}
/**
* Validates this MCRObjectMetadata. This method throws an exception if:
* <ul>
* <li>one of the MCRMetaElement children is invalid</li>
* </ul>
*
* @throws MCRException the MCRObjectMetadata is invalid
*/
public void validate() throws MCRException {
for (MCRMetaElement e : this) {
try {
e.validate();
} catch (Exception exc) {
throw new MCRException("The <metadata> element is invalid because '" + e.getTag() + "' is invalid.",
exc);
}
}
}
/**
* This method put debug data to the logger (for the debug mode).
*/
public final void debug() {
if (LOGGER.isDebugEnabled()) {
for (MCRMetaElement sub : this) {
sub.debug();
}
}
}
@Override
public Iterator<MCRMetaElement> iterator() {
return metadataElements.iterator();
}
}
| 15,761 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaAccessRule.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaAccessRule.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.datamodel.metadata;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
/**
* This class implements all method for handling with the MCRMetaAccessRule part
* of a metadata object. The MCRMetaAccessRule class present a single item,
* which hold an ACL condition for a defined permission.
*
* @author Jens Kupferschmidt
*/
public class MCRMetaAccessRule extends MCRMetaDefault {
// MCRMetaAccessRule data
protected Element condition;
protected String permission;
private static final Logger LOGGER = LogManager.getLogger();
/**
* This is the constructor. <br>
* The constructor of the MCRMetaDefault runs. The <em>permission</em> Attribute
* is set to 'READ'. The <b>condition</b> is set to 'null'.
*/
public MCRMetaAccessRule() {
super();
condition = null;
permission = "READ";
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>default_lang</em> is
* null, empty or false <b>en</b> was set. This is not use in other methods
* of this class. The subtag element was set to the value of
* <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception will be throwed. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The condition element was set to the value of
* <em>condition</em>, if it is null, an exception will be throwed.
* @param subtag the name of the subtag
* @param type the optional type string
* @param inherted a value >= 0
* @param permission permission
* @param condition the JDOM Element included the condition tree
* @exception MCRException if the subtag value or condition is null or empty
*/
public MCRMetaAccessRule(String subtag, String type, int inherted, String permission, Element condition)
throws MCRException {
super(subtag, null, type, inherted);
if (condition == null || !condition.getName().equals("condition")) {
throw new MCRException("The condition Element of MCRMetaAccessRule is null.");
}
set(permission, condition);
}
/**
* This method set the permission and the condition.
*
* @param permission the format string, if it is empty 'READ' will be set.
* @param condition
* the JDOM Element included the condition tree
* @exception MCRException
* if the condition is null or empty
*/
public final void set(String permission, Element condition) throws MCRException {
setCondition(condition);
setPermission(permission);
}
/**
* This method set the condition.
*
* @param condition
* the JDOM Element included the condition tree
* @exception MCRException
* if the condition is null or empty
*/
public final void setCondition(Element condition) throws MCRException {
if (condition == null || !condition.getName().equals("condition")) {
throw new MCRException("The condition Element of MCRMetaAccessRule is null.");
}
this.condition = condition.clone();
}
/**
* This method set the permission attribute.
*
* @param permission
* the new permission string.
*/
public final void setPermission(String permission) {
this.permission = permission;
}
/**
* This method get the condition.
*
* @return the condition as JDOM Element
*/
public final Element getCondition() {
return condition;
}
/**
* This method get the permission attribute.
*
* @return the permission attribute
*/
public final String getPermission() {
return permission;
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
setCondition(element.getChild("condition"));
setPermission(element.getAttributeValue("permission"));
}
/**
* This method create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaAccessRule definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaAccessRule part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
elm.setAttribute("permission", permission);
elm.addContent(condition.clone());
return elm;
}
/**
* Validates this MCRMetaAccessRule. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the condition is null</li>
* <li>the permission is null or empty</li>
* </ul>
*
* @throws MCRException the MCRMetaAccessRule is invalid
*/
@Override
public void validate() throws MCRException {
super.validate();
if (condition == null) {
throw new MCRException(getSubTag() + ": condition is null");
}
if (permission == null || permission.length() == 0) {
throw new MCRException(getSubTag() + ": permission is null or empty");
}
}
/**
* This method make a clone of this class.
*/
@Override
public MCRMetaAccessRule clone() {
MCRMetaAccessRule clone = (MCRMetaAccessRule) super.clone();
clone.permission = this.permission;
clone.condition = this.condition.clone();
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public final void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Permission = {}", permission);
LOGGER.debug("Rule = " + "condition");
LOGGER.debug(" ");
}
}
}
| 7,214 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaNumber.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaNumber.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.datamodel.metadata;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
/**
* <p>
* Implements methods to handle MCRMetaNumber fields of a metadata object.
* The MCRMetaNumber class presents a number value in decimal
* format and optional a dimension type and a measurement. The input number can have the format
* like <em>xxxx</em>, <em>xxxx.x</em> or <em>xxxx,xxx</em>.
* </p>
* <p>
* The length of the dimension type is limited by the property <em>MCR.Metadata.MetaNumber.DimensionLength</em>.
* The default length is defined in MAX_DIMENSION_LENGTH = 128.
* </p>
* <p>
* The length of the measurement type is limited by the property <em>MCR.Metadata.MetaNumber.MeasurementLength</em>.
* The default length is defined in MAX_MEASURE_LENGTH = 64.
* </p>
* <p>
* The String output format of the number is determined by the property
* <em>MCR.Metadata.MetaNumber.FractionDigits</em>, default is DEFAULT_FRACTION_DIGITS = 3, and the ENGLISH Locale.
* For more digits in fraction as defined in property <em>MCR.Metadata.MetaNumber.FractionDigits</em>
* will be round the output!
* </p>
* <p>
* For transforming the dot of the ENGLISH locale to other Characters use the tools of your layout process.
* </p>
* <pre>
* <tag class="MCRMetaNumber" heritable="...">
* <subtag type="..." measurement="..." dimension="...">
* xxxx.xxx or xxx
* </subtag>
* </tag>
* </pre>
*
* @author Jens Kupferschmidt
*/
public final class MCRMetaNumber extends MCRMetaDefault {
public static final int MAX_DIMENSION_LENGTH = 128;
public static final int MAX_MEASUREMENT_LENGTH = 64;
public static final int DEFAULT_FRACTION_DIGITS = 3;
private BigDecimal number;
private String dimension;
private String measurement;
private static final Logger LOGGER = LogManager.getLogger();
private int fractionDigits;
private int dimensionLength;
private int measurementLength;
private void loadProperties() {
fractionDigits = MCRConfiguration2.getInt("MCR.Metadata.MetaNumber.FractionDigits")
.orElse(DEFAULT_FRACTION_DIGITS);
dimensionLength = MCRConfiguration2.getInt("MCR.Metadata.MetaNumber.DimensionLength")
.orElse(MAX_DIMENSION_LENGTH);
measurementLength = MCRConfiguration2.getInt("MCR.Metadata.MetaNumber.MeasurementLength")
.orElse(MAX_MEASUREMENT_LENGTH);
}
/**
* This is the constructor. <br>
* Sets the number to zero, the measurement and the dimension to an empty string.
*/
public MCRMetaNumber() {
super();
loadProperties();
number = new BigDecimal("0");
dimension = "";
measurement = "";
}
/**
* This is the constructor. <br>
* The subtag element was set to the value of <em>subtag</em>.
* If the value of <em>subtag</em> is null or empty a MCRException will be thrown.
* The dimension element was set to the value of <em>dimension</em>, if it is null,
* an empty string was set to the dimension element.
* The measurement element was set to the value of <em>measurement</em>, if it is null,
* an empty string was set to the measurement element.
* The number string <em>number</em> was set to the number element, if it is null, empty or not a number, a
* MCRException will be thown.
* @param subtag the name of the subtag
* @param inherted a value >= 0
* @param dimension the optional dimension string
* @param measurement the optional measurement string
* @param number the number string
* @exception MCRException if the subtag value is null or empty or if
* the number string is not in a number format
*/
public MCRMetaNumber(String subtag, int inherted, String dimension, String measurement, String number)
throws MCRException {
super(subtag, null, null, inherted);
loadProperties();
setDimension(dimension);
setMeasurement(measurement);
setNumber(number);
}
/**
* This is the constructor. <br>
* The subtag element was set to the value of <em>subtag</em>.
* If the value of <em>subtag</em> is null or empty a MCRException will be thrown.
* The dimension element was set to the value of <em>dimension</em>, if it is null,
* an empty string was set to the dimension element.
* The measurement element was set to the value of <em>measurement</em>, if it is null,
* an empty string was set to the measurement element.
* The number <em>number</em> was set to the number element, if it is null a MCRException will be thrown.
* @param subtag the name of the subtag
* @param inherted a value >= 0
* @param dimension the optional dimension string
* @param measurement the optional measurement string
* @param number the number string
* @exception MCRException if the subtag value is null or empty or if
* the number string is not in a number format
*/
public MCRMetaNumber(String subtag, int inherted, String dimension, String measurement, BigDecimal number)
throws MCRException {
super(subtag, null, null, inherted);
loadProperties();
setDimension(dimension);
setMeasurement(measurement);
setNumber(number);
}
/**
* This method set the dimension, if it is null, an empty string was set to
* the dimension element.
*
* @param dimension
* the dimension string
*/
public void setDimension(String dimension) {
if (dimension == null) {
this.dimension = "";
} else {
if (dimension.length() > dimensionLength) {
this.dimension = dimension.substring(dimensionLength);
LOGGER.warn("{}: dimension is too long: {}", getSubTag(), dimension.length());
} else {
this.dimension = dimension;
}
}
}
/**
* This method set the measurement, if it is null, an empty string was set
* to the measurement element.
*
* @param measurement
* the measurement string
*/
public void setMeasurement(String measurement) {
if (measurement == null) {
this.measurement = "";
} else {
if (measurement.length() > measurementLength) {
this.measurement = measurement.substring(measurementLength);
LOGGER.warn("{}: measurement is too long: {}", getSubTag(), measurement.length());
} else {
this.measurement = measurement;
}
}
}
/**
* This method set the number, if it is null or not a number, a MCRException
* will be throw.
*
* @param number
* the number string
* @exception MCRException
* if the number string is not in a number format
*/
public void setNumber(String number) throws MCRException {
try {
if (number == null) {
throw new MCRException("Number cannot be null");
}
String tmpNumber = number.replace(',', '.');
this.number = new BigDecimal(tmpNumber);
} catch (NumberFormatException e) {
throw new MCRException("The format of a number is invalid.");
}
}
/**
* This method set the number, if it is null a MCRException will be throw.
*
* @param number
* the number as BigDecimal
* @exception MCRException
* if the number string is null
*/
public void setNumber(BigDecimal number) throws MCRException {
if (number == null) {
throw new MCRException("Number cannot be null");
}
this.number = number;
}
/**
* This method get the dimension element.
*
* @return the dimension String
*/
public String getDimension() {
return dimension;
}
/**
* This method get the measurement element.
*
* @return the measurement String
*/
public String getMeasurement() {
return measurement;
}
/**
* This method get the number element.
*
* @return the number as BigDecimal
*/
public BigDecimal getNumberAsBigDecimal() {
return number;
}
/**
* This method get the number element as formatted String. The number of
* fraction digits is defined by property <em>MCR.Metadata.MetaNumber.FractionDigits</em>.
* The default is 3 fraction digits.
*
* @return the number as formatted String
*/
public String getNumberAsString() {
final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
numberFormat.setGroupingUsed(false);
numberFormat.setMaximumFractionDigits(fractionDigits);
numberFormat.setMinimumFractionDigits(fractionDigits);
return numberFormat.format(number);
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
setMeasurement(element.getAttributeValue("measurement"));
setDimension(element.getAttributeValue("dimension"));
setNumber(element.getTextTrim());
}
/**
* This method creates an XML element containing all data in this instance,
* as defined by the MyCoRe XML MCRNumber definition for the given subtag.
*
* @exception MCRException
* if the content of this instance is not valid
* @return a JDOM Element with the XML MCRNumber part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
if (dimension != null && dimension.length() != 0) {
elm.setAttribute("dimension", dimension);
}
if (measurement != null && measurement.length() != 0) {
elm.setAttribute("measurement", measurement);
}
elm.addContent(getNumberAsString());
return elm;
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaNumber clone() {
MCRMetaNumber clone = (MCRMetaNumber) super.clone();
clone.dimension = this.dimension;
clone.measurement = this.measurement;
clone.number = this.number;
return clone;
}
/**
* Logs debug output.
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Measurement = {}", measurement);
LOGGER.debug("Dimension = {}", dimension);
LOGGER.debug("Value = {}", number.toPlainString());
LOGGER.debug("");
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaNumber other = (MCRMetaNumber) obj;
return Objects.equals(measurement, other.measurement) && Objects.equals(dimension, other.dimension)
&& Objects.equals(number, other.number);
}
}
| 12,492 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDerivateDefaultClassEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRDerivateDefaultClassEventHandler.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.datamodel.metadata;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
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.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
public class MCRDerivateDefaultClassEventHandler extends MCREventHandlerBase {
private static final List<String> DEFAULT_CATEGORIES = MCRConfiguration2
.getString("MCR." + MCRDerivateDefaultClassEventHandler.class.getSimpleName() + ".DefaultCategories")
.map(MCRConfiguration2::splitValue)
.orElseGet(() -> Stream.of("derivate_types:content"))
.collect(Collectors.toUnmodifiableList());
private static final Logger LOGGER = LogManager.getLogger();
private static MCRMetaClassification asMetaClassification(MCRCategoryID categoryId) {
return new MCRMetaClassification("classification", 0, null,
categoryId.getRootID(), categoryId.getId());
}
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
final ArrayList<MCRMetaClassification> classifications = der.getDerivate().getClassifications();
if (!classifications.isEmpty()) {
//already defined at creation
return;
}
final List<MCRCategoryID> categories = DEFAULT_CATEGORIES.stream()
.map(MCRCategoryID::fromString) //checks syntax
.collect(Collectors.toList());
final MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
final List<MCRCategoryID> missingCategories = categories.stream()
.filter(Predicate.not(categoryDAO::exist))
.collect(Collectors.toList());
if (!missingCategories.isEmpty()) {
LOGGER.error(() -> "Categories do not exist: " + missingCategories.stream()
.map(MCRCategoryID::toString)
.collect(Collectors.joining(", ")));
return;
}
LOGGER.warn(() -> der.getId() + " has no classification, using "
+ DEFAULT_CATEGORIES.stream().collect(Collectors.joining(", ")) + " by default.");
classifications.addAll(categories.stream()
.map(MCRDerivateDefaultClassEventHandler::asMetaClassification)
.collect(Collectors.toList()));
}
}
| 3,403 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaEnrichedLinkIDFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaEnrichedLinkIDFactory.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.datamodel.metadata;
import org.jdom2.Element;
import org.mycore.common.config.MCRConfiguration2;
/**
* Handles andle which information is present in the {@link MCRMetaEnrichedLinkID} for Derivates.
* Set class with: MCR.Metadata.EnrichedDerivateLinkIDFactory.Class
*/
public abstract class MCRMetaEnrichedLinkIDFactory {
protected MCRMetaEnrichedLinkIDFactory() {
}
public static MCRMetaEnrichedLinkIDFactory getInstance() {
return MCRConfiguration2
.<MCRMetaEnrichedLinkIDFactory>getInstanceOf("MCR.Metadata.EnrichedDerivateLinkIDFactory.Class")
.orElseGet(MCRDefaultEnrichedDerivateLinkIDFactory::new);
}
public abstract MCREditableMetaEnrichedLinkID getDerivateLink(MCRDerivate der);
public abstract MCREditableMetaEnrichedLinkID fromDom(Element element);
public MCREditableMetaEnrichedLinkID getEmptyLinkID() {
return new MCREditableMetaEnrichedLinkID();
}
}
| 1,691 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaLinkID.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaLinkID.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.datamodel.metadata;
import java.util.Objects;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* This class implements all method for special handling with the MCRMetaLink
* part of a metadata object. The MCRMetaLinkID class present two types. At once
* a reference only of a other MCRObject. At second a bidirectional link between
* two MCRObject's. Optional you can append the reference with the label
* attribute. See to W3C XLink Standard for more informations.
* <p>
* <tag class="MCRMetaLinkID">
* <br>
* <subtag xlink:type="locator" xlink:href=" <em>MCRObjectID</em>"
* xlink:label="..." xlink:title="..."/> <br>
* <subtag xlink:type="arc" xlink:from=" <em>MCRObjectID</em>"
* xlink:to="MCRObjectID"/> <br>
* </tag> <br>
*
* @author Jens Kupferschmidt
*/
@JsonClassDescription("Links to other objects or derivates")
public class MCRMetaLinkID extends MCRMetaLink {
/**
* initializes with empty values.
*/
public MCRMetaLinkID() {
super();
}
/**
* initializes with given values.
* @see MCRMetaLink#MCRMetaLink(String, int)
*/
public MCRMetaLinkID(String subtag, int inherted) {
super(subtag, inherted);
}
/**
* initializes with all values needed to link to an MCRObject.
*
* This is the same as running {@link #MCRMetaLinkID(String, int)} and
* {@link #setReference(MCRObjectID, String, String)}.
*/
public MCRMetaLinkID(String subtag, MCRObjectID id, String label, String title) {
this(subtag, id, label, title, null);
}
/**
* initializes with all values needed to link to an MCRObject.
*
*/
public MCRMetaLinkID(String subtag, MCRObjectID id, String label, String title, String role) {
this(subtag, 0);
setReference(id, label, title);
setXLinkRole(role);
}
/**
* This method set a reference with xlink:href, xlink:label and xlink:title.
*
* @param href
* the reference as MCRObjectID string
* @param label
* the new label string
* @param title
* the new title string
* @exception MCRException
* if the set_href value is null, empty or not a MCRObjectID
*/
@Override
public final void setReference(String href, String label, String title) throws MCRException {
try {
MCRObjectID hrefid = MCRObjectID.getInstance(href);
super.setReference(hrefid.toString(), label, title);
} catch (Exception e) {
throw new MCRException("The href value is not a MCRObjectID: " + href, e);
}
}
/**
* This method set a reference with xlink:href, xlink:label and xlink:title.
*
* @param href
* the reference as MCRObjectID
* @param label
* the new label string
* @param title
* the new title string
* @exception MCRException
* if the href value is null, empty or not a MCRObjectID
*/
public final void setReference(MCRObjectID href, String label, String title) throws MCRException {
if (href == null) {
throw new MCRException("The href value is null.");
}
super.setReference(href.toString(), label, title);
}
/**
* This method set a bidirectional link with xlink:from, xlink:to and
* xlink:title.
*
* @param from
* the source MCRObjectID string
* @param to
* the target MCRObjectID string
* @param title
* the new title string
* @exception MCRException
* if the from or to element is not a MCRObjectId
*/
@Override
public final void setBiLink(String from, String to, String title) throws MCRException {
try {
MCRObjectID fromid = MCRObjectID.getInstance(from);
MCRObjectID toid = MCRObjectID.getInstance(to);
super.setBiLink(fromid.toString(), toid.toString(), title);
} catch (Exception e) {
linktype = null;
throw new MCRException("The from/to value is not a MCRObjectID.");
}
}
/**
* This method set a bidirectional link with xlink:from, xlink:to and
* xlink:title.
*
* @param from
* the source MCRObjectID
* @param to
* the target MCRObjectID
* @param title
* the new title string
* @exception MCRException
* if the from or to element is not a MCRObjectId
*/
public final void setBiLink(MCRObjectID from, MCRObjectID to, String title) throws MCRException {
if (from == null || to == null) {
throw new MCRException("The from/to value is null.");
}
super.setBiLink(from.toString(), to.toString(), title);
}
/**
* This method get the xlink:href element as MCRObjectID.
*
* @return the xlink:href element as MCRObjectID
*/
@JsonIgnore
public final MCRObjectID getXLinkHrefID() {
return MCRObjectID.getInstance(href);
}
/**
* This method get the xlink:from element as MCRObjectID.
*
* @return the xlink:from element as MCRObjectID
*/
@JsonIgnore
public final MCRObjectID getXLinkFromID() {
return MCRObjectID.getInstance(from);
}
/**
* This method get the xlink:to element as MCRObjectID.
*
* @return the xlink:to element as MCRObjectID
*/
@JsonIgnore
public final MCRObjectID getXLinkToID() {
return MCRObjectID.getInstance(to);
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant DOM element for the metadata
* @exception MCRException
* if the xlink:type is not locator or arc or if href or from
* and to are not a MCRObjectID
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
if (linktype.equals("locator")) {
try {
MCRObjectID hrefid = MCRObjectID.getInstance(href);
href = hrefid.toString();
} catch (Exception e) {
throw new MCRException("The xlink:href is not a MCRObjectID.");
}
} else {
try {
MCRObjectID fromid = MCRObjectID.getInstance(from);
from = fromid.toString();
} catch (Exception e) {
throw new MCRException("The xlink:from is not a MCRObjectID.");
}
try {
MCRObjectID toid = MCRObjectID.getInstance(to);
to = toid.toString();
} catch (Exception e) {
throw new MCRException("The xlink:to is not a MCRObjectID.");
}
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
MCRMetaLinkID other = (MCRMetaLinkID) obj;
if (!Objects.equals(from, other.from)) {
return false;
} else if (!Objects.equals(href, other.href)) {
return false;
} else if (!Objects.equals(label, other.label)) {
return false;
} else if (!Objects.equals(linktype, other.linktype)) {
return false;
} else if (!Objects.equals(role, other.role)) {
return false;
} else if (!Objects.equals(title, other.title)) {
return false;
} else {
return Objects.equals(to, other.to);
}
}
@Override
public MCRMetaLinkID clone() {
return (MCRMetaLinkID) super.clone();
}
@Override
public final String toString() {
return getXLinkHref();
}
}
| 8,800 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaISO8601Date.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaISO8601Date.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.datamodel.metadata;
import java.util.Date;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRException;
import org.mycore.datamodel.common.MCRISO8601Date;
import org.mycore.datamodel.common.MCRISO8601Format;
import com.google.gson.JsonObject;
/**
* provides support for a restricted range of formats, all of which are valid
* ISO 8601 dates and times.
*
* The range of supported formats is exactly the same range that is suggested by
* the W3C <a href="http://www.w3.org/TR/NOTE-datetime">datetime profile</a> in
* its version from 1997-09-15.
*
* @author Thomas Scheffler (yagee)
*
* @since 1.3
*/
public final class MCRMetaISO8601Date extends MCRMetaDefault {
private Element export;
private boolean changed = true;
private static final Namespace DEFAULT_NAMESPACE = Namespace.NO_NAMESPACE;
private MCRISO8601Date isoDate;
private static final Logger LOGGER = LogManager.getLogger();
/**
* constructs a empty instance.
*
* @see MCRMetaDefault#MCRMetaDefault()
*/
public MCRMetaISO8601Date() {
super();
this.isoDate = new MCRISO8601Date();
}
/**
* same as superImplentation but sets lang attribute to "null"
*
* @see MCRMetaDefault#MCRMetaDefault(String, String, String, int)
*/
public MCRMetaISO8601Date(String subtag, String type, int inherted) {
super(subtag, null, type, inherted);
this.isoDate = new MCRISO8601Date();
}
/*
* (non-Javadoc)
*
* @see org.mycore.datamodel.metadata.MCRMetaDefault#createXML()
*/
@Override
public Element createXML() throws MCRException {
if (!changed) {
return export.clone();
}
Element elm = super.createXML();
if (!(isoDate.getIsoFormat() == null || isoDate.getIsoFormat() == MCRISO8601Format.COMPLETE_HH_MM_SS_SSS)) {
elm.setAttribute("format", isoDate.getIsoFormat().toString());
}
elm.setText(getISOString());
export = elm;
changed = false;
return export.clone();
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* date: "2016-02-08",
* format: "YYYY-MM-DD"
* }
* </pre>
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
obj.addProperty("date", getISOString());
if (isoDate.getIsoFormat() != null) {
obj.addProperty("format", isoDate.getIsoFormat().toString());
}
return obj;
}
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
setFormat(element.getAttributeValue("format"));
setDate(element.getTextTrim());
export = element.clone();
}
/**
* returns the namespace of this element
*
* @return Returns the ns.
*/
protected static Namespace getNs() {
return DEFAULT_NAMESPACE;
}
/**
* sets the date for this meta data object
*
* @param isoString
* Date in any form that is a valid W3C dateTime
*/
public void setDate(String isoString) {
isoDate.setDate(isoString);
}
/**
* returns the Date representing this element.
*
* @return a new Date instance of the time set in this element
*/
public Date getDate() {
return isoDate.getDate();
}
/**
* sets the date for this meta data object
*
* @param dt
* Date object representing date String in Element
*/
public void setDate(Date dt) {
isoDate.setDate(dt);
}
/**
* returns a ISO 8601 conform String using the current set format.
*
* @return date in ISO 8601 format, or null if date is unset.
*/
public String getISOString() {
return isoDate.getISOString();
}
/**
* sets the input and output format.
*
* please use only the formats defined on the <a
* href="http://www.w3.org/TR/NOTE-datetime">W3C Page</a>, which are also
* exported as static fields by this class.
*
* @param format
* a format string that is valid conforming to xsd:duration
* schema type.
*
*/
public void setFormat(String format) {
isoDate.setFormat(format);
}
public String getFormat() {
return isoDate == null || isoDate.getIsoFormat() == null ? null : isoDate.getIsoFormat().toString();
}
/**
* Returns the internal date.
*
* @return the base date
*/
public MCRISO8601Date getMCRISO8601Date() {
return isoDate;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Date={}", isoDate != null ? isoDate.getISOString() : "null");
if (isoDate != null) {
MCRISO8601Format isoFormat = isoDate.getIsoFormat();
LOGGER.debug("Format={}", isoFormat);
}
}
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaISO8601Date clone() {
MCRMetaISO8601Date clone = (MCRMetaISO8601Date) super.clone();
clone.changed = this.changed;
clone.export = this.export.clone();
clone.isoDate = this.isoDate; // this is ok because iso Date is immutable
return clone;
}
/**
* Validates this MCRMetaISO8601Date. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the isoDate or the temporal accessor is null</li>
* </ul>
*
* @throws MCRException the MCRMetaISO8601Date is invalid
*/
public void validate() throws MCRException {
super.validate();
if (isoDate == null || isoDate.getDt() == null) {
throw new MCRException(getSubTag() + ": date is invalid");
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaISO8601Date other = (MCRMetaISO8601Date) obj;
return Objects.equals(this.isoDate, other.isoDate);
}
}
| 7,486 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectID.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectID.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.datamodel.metadata;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Matcher;
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.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* This class holds all informations and methods to handle the MyCoRe Object ID.
* The MyCoRe Object ID is a special ID to identify each metadata object with
* three parts, they are the project identifier, the type identifier and a
* string with a number. The syntax of the ID is "<em>projectID</em>_
* <em>typeID</em>_ <em>number</em>" as "<em>String_String_Integer</em>".
*
* @author Jens Kupferschmidt
* @author Thomas Scheffler (yagee)
*/
@JsonClassDescription("MyCoRe ObjectID in form {project}_{type}_{int32}, "
+ "where project is a namespace and type defines the datamodel")
@JsonFormat(shape = JsonFormat.Shape.STRING)
public final class MCRObjectID implements Comparable<MCRObjectID> {
/**
* public constant value for the MCRObjectID length
*/
public static final int MAX_LENGTH = 64;
private static NumberFormat NUMBER_FORMAT = initNumberFormat();
private static final Logger LOGGER = LogManager.getLogger(MCRObjectID.class);
/** ID pattern with named capturing groups */
private static Pattern ID_PATTERN = Pattern
.compile("^(?<projectId>[a-zA-Z][a-zA-Z0-9]*)_(?<objectType>[a-zA-Z0-9]+)_(?<numberPart>[0-9]+)$");
private static HashSet<String> VALID_TYPE_LIST;
private static Comparator<MCRObjectID> COMPARATOR_FOR_MCR_OBJECT_ID = Comparator
.comparing(MCRObjectID::getProjectId)
.thenComparing(MCRObjectID::getTypeId)
.thenComparingInt(MCRObjectID::getNumberAsInteger);
static {
final String confPrefix = "MCR.Metadata.Type.";
VALID_TYPE_LIST = MCRConfiguration2.getSubPropertiesMap(confPrefix)
.entrySet()
.stream()
.filter(p -> Boolean.parseBoolean(p.getValue()))
.map(prop -> prop.getKey())
.collect(Collectors.toCollection(HashSet::new));
}
// parts of the ID
private final String projectId;
private final String objectType;
private final int numberPart;
// complete id as formatted string
private final String combinedId;
/**
* The constructor for MCRObjectID from a given string.
*
* @exception MCRException
* if the given string is not valid.
*/
MCRObjectID(String id) throws MCRException {
if (!isValid(id)) {
throw new MCRException("The ID is not valid: " + id
+ " , it should match the pattern String_String_Integer");
}
String[] idParts = getIDParts(id.trim());
projectId = idParts[0].intern();
objectType = idParts[1].toLowerCase(Locale.ROOT).intern();
numberPart = Integer.parseInt(idParts[2]);
this.combinedId = formatID(projectId, objectType, numberPart);
}
//ID generation methods move to MCRObjectIDGenerator
//deprecated in 2023.06
@Deprecated
public static MCRObjectID getNextFreeId(String baseId) {
return MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(baseId);
}
@Deprecated
public static MCRObjectID getNextFreeId(String projectId, String type) {
return MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(projectId, type);
}
@Deprecated
public static MCRObjectID getNextFreeId(String baseId, int maxInWorkflow) {
return MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(baseId, maxInWorkflow);
}
@Deprecated
public static MCRObjectID getLastID(String baseId) {
return MCRMetadataManager.getMCRObjectIDGenerator().getLastID(baseId);
}
/**
* This method instantiate this class with a given identifier in MyCoRe schema.
*
* @param id
* the MCRObjectID
* @return an MCRObjectID class instance
* @exception MCRException if the given identifier is not valid
*/
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static MCRObjectID getInstance(String id) {
return MCRObjectIDPool.getMCRObjectID(Objects.requireNonNull(id, "'id' must not be null."));
}
/**
* Normalizes to a object ID of form <em>project_id</em>_ <em>type_id</em>_
* <em>number</em>, where number has leading zeros.
* @return <em>project_id</em>_<em>type_id</em>_<em>number</em>
*/
public static String formatID(String projectID, String type, int number) {
if (projectID == null) {
throw new IllegalArgumentException("projectID cannot be null");
}
if (type == null) {
throw new IllegalArgumentException("type cannot be null");
}
if (number < 0) {
throw new IllegalArgumentException("number must be non negative integer");
}
return projectID + '_' + type.toLowerCase(Locale.ROOT) + '_' + NUMBER_FORMAT.format(number);
}
/**
* Normalizes to a object ID of form <em>project_id</em>_ <em>type_id</em>_
* <em>number</em>, where number has leading zeros.
*
* @param baseID
* is <em>project_id</em>_<em>type_id</em>
* @return <em>project_id</em>_<em>type_id</em>_<em>number</em>
*/
public static String formatID(String baseID, int number) {
String[] idParts = getIDParts(baseID);
return formatID(idParts[0], idParts[1], number);
}
/**
* Splits the submitted <code>id</code> in its parts.
* <code>MyCoRe_document_00000001</code> would be transformed in { "MyCoRe",
* "document", "00000001" }
*
* @param id
* either baseID or complete ID
*/
public static String[] getIDParts(String id) {
return id.split("_");
}
/**
* Returns a list of available mycore object types.
*/
public static List<String> listTypes() {
return new ArrayList<>(VALID_TYPE_LIST);
}
/**
* Check whether the type passed is a valid type in the current mycore environment.
* That being said property <code>MCR.Metadata.Type.<type></code> must be set to <code>true</code> in mycore.properties.
*
* @param type the type to check
* @return true if valid, false otherwise
*/
public static boolean isValidType(String type) {
return VALID_TYPE_LIST.contains(type);
}
/**
* Checks if the given id is a valid mycore id in the form of {project}_{object_type}_{number}.
*
* @param id the id to check
* @return true if the id is valid, false otherwise
*/
public static boolean isValid(String id) {
if (id == null) {
return false;
}
if (id.length() > MAX_LENGTH) {
return false;
}
Matcher m = ID_PATTERN.matcher(id);
if (m.matches()) {
String objectType = m.group("objectType").toLowerCase(Locale.ROOT).intern();
if (!MCRConfiguration2.getBoolean("MCR.Metadata.Type." + objectType).orElse(false)) {
LOGGER.warn("Property MCR.Metadata.Type.{} is not set to 'true'. Thus {} cannot be a valid id.",
objectType, id);
return false;
}
try {
int numberPart = Integer.parseInt(m.group("numberPart"));
if (numberPart < 0) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
} else {
return false;
}
return true;
}
/**
* This method get the string with <em>project_id</em>. If the ID is not
* valid, an empty string was returned.
*
* @return the string of the project id
*/
public String getProjectId() {
return projectId;
}
/**
* This method gets the string with <em>type_id</em>.
*
* @return the string of the type id
*/
public String getTypeId() {
return objectType;
}
/**
* This method gets the string with <em>number</em>.
*
* @return the string of the number
*/
public String getNumberAsString() {
return NUMBER_FORMAT.format(numberPart);
}
/**
* This method gets the integer with <em>number</em>.
*
* @return the number as integer
*/
public int getNumberAsInteger() {
return numberPart;
}
/**
* This method gets the basic string with <em>project_id</em>_
* <em>type_id</em>.
*
* @return the string of the schema name
*/
public String getBase() {
return projectId + "_" + objectType;
}
/**
* This method check this data again the input and retuns the result as
* boolean.
*
* @param in
* the MCRObjectID to check
* @return true if all parts are equal, else return false
*/
public boolean equals(MCRObjectID in) {
return this == in || (in != null && toString().equals(in.toString()));
}
/**
* This method check this data again the input and retuns the result as
* boolean.
*
* @param in
* the MCRObjectID to check
* @return true if all parts are equal, else return false.
* @see java.lang.Object#equals(Object)
*/
@Override
public boolean equals(Object in) {
if (in instanceof MCRObjectID objectID) {
return equals(objectID);
}
return false;
}
@Override
public int compareTo(MCRObjectID o) {
return COMPARATOR_FOR_MCR_OBJECT_ID.compare(this, o);
}
/**
* @see java.lang.Object#toString()
* @return {@link #formatID(String, String, int)} with
* {@link #getProjectId()}, {@link #getTypeId()},
* {@link #getNumberAsInteger()}
*/
@Override
@JsonValue
public String toString() {
return combinedId;
}
/**
* returns toString().hashCode()
*
* @see #toString()
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return toString().hashCode();
}
private static NumberFormat initNumberFormat() {
String numberPattern = MCRConfiguration2.getString("MCR.Metadata.ObjectID.NumberPattern")
.orElse("0000000000").trim();
NumberFormat format = NumberFormat.getIntegerInstance(Locale.ROOT);
format.setGroupingUsed(false);
format.setMinimumIntegerDigits(numberPattern.length());
return format;
}
}
| 11,844 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaSpatial.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaSpatial.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.datamodel.metadata;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* Stores spatial information for geographic references. The latitude longitude values are stored in an array list,
* where two BigDecimal build a point.
*
* @author Matthias Eichner
* @author Jens Kupferschmidt
*/
public class MCRMetaSpatial extends MCRMetaDefault {
private List<BigDecimal> data;
/**
* initializes with empty values.
*/
public MCRMetaSpatial() {
super();
this.data = new ArrayList<>();
}
@Deprecated
public MCRMetaSpatial(String subtag, String defaultLanguage, String type, Integer inherited) throws MCRException {
super(subtag, defaultLanguage, type, inherited);
this.data = new ArrayList<>();
}
/**
* The constructor for a MCRMetaSpatial instance with an empty data container.
* @param subtag the name of the subtag
* @param type an optional type or an empty string
* @param inherited a value >= 0
*
* @throws MCRException if the set_subtag value is null or empty
*/
public MCRMetaSpatial(String subtag, String type, Integer inherited) throws MCRException {
super(subtag, null, type, inherited);
this.data = new ArrayList<>();
}
/**
* Returns the spatial data. Two entries build a point. The first is always the latitude and the second one
* is always the longitude value.
*
* @return list of the spatial data
*/
public List<BigDecimal> getData() {
return this.data;
}
public void setData(List<BigDecimal> data) {
this.data = data;
}
/**
* Adds a new point to the data.
*
* @param lat the latitude value
* @param lng the longitude value
*/
public void add(BigDecimal lat, BigDecimal lng) {
this.data.add(lat);
this.data.add(lng);
}
@Override
public void setFromDOM(Element element) throws MCRException {
super.setFromDOM(element);
String textData = element.getText();
String[] splitData = textData.split(",");
if (splitData.length % 2 != 0) {
throw new MCRException(String.format(Locale.ROOT,
"Unable to parse MCRMetaSpatial cause text data '%s' contains invalid content", textData));
}
try {
Arrays.stream(splitData).map(BigDecimal::new).forEach(this.data::add);
} catch (NumberFormatException nfe) {
throw new MCRException(String.format(Locale.ROOT,
"Unable to parse MCRMetaSpatial cause text data '%s' contains invalid content", textData), nfe);
}
}
@Override
public Element createXML() throws MCRException {
Element element = super.createXML();
return element.setText(this.data.stream().map(BigDecimal::toPlainString).collect(Collectors.joining(",")));
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* data: [50.92878, 11.5899]
* }
* </pre>
*
*/
@Override
public JsonObject createJSON() {
JsonObject json = super.createJSON();
JsonArray dataArray = new JsonArray();
this.data.forEach(dataArray::add);
json.add("data", dataArray);
return json;
}
@Override
public void validate() throws MCRException {
super.validate();
if (this.data.isEmpty()) {
throw new MCRException("spatial list should contain content");
}
if (this.data.size() % 2 != 0) {
throw new MCRException(
String.format(Locale.ROOT, "spatial list content '%s' is uneven", this.data));
}
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaSpatial clone() {
MCRMetaSpatial clone = (MCRMetaSpatial) super.clone();
clone.data = new ArrayList<>(this.data); // Big Integer is immutable
return clone;
}
}
| 5,158 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileMetadata.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRFileMetadata.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.datamodel.metadata;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.jdom2.Element;
import org.mycore.datamodel.classifications2.MCRCategoryID;
/**
* This holds information about file metadata that is stored in derivate xml
*
* @author Thomas Scheffler (yagee)
* @author shermann
* @see MCRObjectDerivate
*/
public class MCRFileMetadata implements Comparable<MCRFileMetadata> {
private Collection<MCRCategoryID> categories;
private String urn, handle;
private String name;
public MCRFileMetadata(Element file) {
this.name = file.getAttributeValue("name");
this.urn = file.getChildText("urn");
this.handle = file.getChildText("handle");
List<Element> categoryElements = file.getChildren("category");
this.categories = Collections.emptySet();
if (!categoryElements.isEmpty()) {
categories = new ArrayList<>(categoryElements.size());
for (Element categElement : categoryElements) {
MCRCategoryID categId = MCRCategoryID.fromString(categElement.getAttributeValue("id"));
categories.add(categId);
}
}
}
public MCRFileMetadata() {
this(null, null, null);
}
public MCRFileMetadata(String name, String urn, Collection<MCRCategoryID> categories) {
super();
setName(name);
setUrn(urn);
setHandle(null);
setCategories(categories);
}
public MCRFileMetadata(String name, String urn, String handle, Collection<MCRCategoryID> categories) {
this(name, urn, categories);
setHandle(handle);
}
public Element createXML() {
Element file = new Element("file");
file.setAttribute("name", name);
if (urn != null) {
Element urn = new Element("urn");
urn.setText(this.urn);
file.addContent(urn);
}
if (handle != null) {
Element handle = new Element("handle");
handle.setText(this.handle);
file.addContent(handle);
}
for (MCRCategoryID categid : categories) {
Element category = new Element("category");
category.setAttribute("id", categid.toString());
file.addContent(category);
}
return file;
}
public Collection<MCRCategoryID> getCategories() {
return Collections.unmodifiableCollection(categories);
}
public void setCategories(Collection<MCRCategoryID> categories) {
if (categories == null || categories.isEmpty()) {
this.categories = Collections.emptySet();
} else {
this.categories = new ArrayList<>(categories);
}
}
public String getUrn() {
return urn;
}
public void setUrn(String urn) {
this.urn = urn;
}
/**
* @return the handle
*/
public String getHandle() {
return handle;
}
/**
* @param handle the handle to set
*/
public void setHandle(String handle) {
this.handle = handle;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(MCRFileMetadata o) {
return this.name.compareTo(o.name);
}
}
| 4,134 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaInterface.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaInterface.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.datamodel.metadata;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import com.google.gson.JsonObject;
/**
* This interface is designed to to have a general description of the common
* method set of all metadata classes.
*
* @author Jens Kupferschmidt
*/
public interface MCRMetaInterface extends Cloneable {
/**
* This method get the inherited element.
*
* @return the inherited flag as int
*/
int getInherited();
/**
* This method get the language element.
*
* @return the language
*/
String getLang();
/**
* This method get the subtag element.
*
* @return the subtag
*/
String getSubTag();
/**
* This method get the type element.
*
* @return the type
*/
String getType();
/**
* This method set the inherited level. This can be 0 or an integer higher
* 0.
*
* @param value
* the inherited level value, if it is < 0, 0 is set
*/
void setInherited(int value);
/**
* This method increments the inherited value with 1.
*/
void incrementInherited();
/**
* This method decrements the inherited value with 1.
*/
void decrementInherited();
/**
* This methode set the default language to the class.
*
* @param lang
* the language
*/
void setLang(String lang);
/**
* This method set the subtag element. If the value of <em>subtag</em>
* is null or empty an exception is throwed.
*
* @param subtag
* the subtag
* @exception MCRException
* if the subtag value is null or empty
*/
void setSubTag(String subtag) throws MCRException;
/**
* This method set the type element. If the value of <em>type</em> is
* null or empty nothing was changed.
*
* @param type
* the optional type
*/
void setType(String type);
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
void setFromDOM(Element element);
/**
* This method create a XML stream for a metadata part.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML data of the metadata part
*/
Element createXML() throws MCRException;
/**
* This method creates a JSON representation of the metadata part.
*
* @return a GSON object containing the json data of the metadata part
*/
JsonObject createJSON();
/**
* This method check the validation of the content of this class.
*
* @return a boolean value
*/
boolean isValid();
/**
* Validates the content of this class.
*
* @throws MCRException the content is invalid
*/
void validate() throws MCRException;
/**
* This method make a clone of this class.
*/
MCRMetaInterface clone();
/**
* This method put debug data to the logger (for the debug mode).
*/
void debug();
}
| 4,012 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaXML.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaXML.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.datamodel.metadata;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Content;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.xml.MCRXMLHelper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* This class implements all method for handling with the MCRMetaLangText part
* of a metadata object. The MCRMetaLangText class present a single item, which
* has triples of a text and his corresponding language and optional a type.
*
* @author Thomas Scheffler (yagee)
* @author Jens Kupferschmidt
* @author Johannes B\u00fchler
*/
public class MCRMetaXML extends MCRMetaDefault {
List<Content> content;
private static final Logger LOGGER = LogManager.getLogger();
/**
* This is the constructor. <br>
* Set the java.util.ArrayList of child elements to new.
*/
public MCRMetaXML() {
super();
}
public MCRMetaXML(String subtag, String type, int inherited) throws MCRException {
super(subtag, null, type, inherited);
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
content = element.cloneContent();
}
public void addContent(Content content) {
if (this.content == null) {
this.content = new ArrayList<>();
}
this.content.add(content);
}
public List<Content> getContent() {
return content;
}
/**
* This method create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaLangText definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaLangText part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
List<Content> addedContent = new ArrayList<>(content.size());
cloneListContent(addedContent, content);
elm.addContent(addedContent);
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* content: [
* ... json objects of parsed content ...
* ]
* }
* </pre>
*
* @see MCRXMLHelper#jsonSerialize(Element)
*/
@Override
public JsonObject createJSON() {
JsonObject json = super.createJSON();
JsonArray jsonContentArray = new JsonArray();
getContent().forEach(content -> {
JsonElement jsonContent = MCRXMLHelper.jsonSerialize(content);
if (jsonContent == null) {
LOGGER.warn("Unable to serialize xml content '{}' to json.", content);
return;
}
jsonContentArray.add(jsonContent);
});
json.add("content", jsonContentArray);
return json;
}
private static void cloneListContent(List<Content> dest, List<Content> source) {
dest.clear();
for (Content c : source) {
dest.add(c.clone());
}
}
/**
* Validates this MCRMetaXML. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the content is null</li>
* </ul>
*
* @throws MCRException the MCRMetaXML is invalid
*/
public void validate() throws MCRException {
super.validate();
if (content == null) {
throw new MCRException(getSubTag() + ": content is null or empty");
}
}
/**
* This method make a clone of this class.
*/
@Override
public MCRMetaXML clone() {
MCRMetaXML clone = (MCRMetaXML) super.clone();
clone.content = this.content.stream().map(Content::clone).collect(Collectors.toList());
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Number of contents = \n{}", content.size());
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaXML other = (MCRMetaXML) obj;
return MCRXMLHelper.deepEqual(this.createXML(), other.createXML());
}
}
| 5,706 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDerivate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRDerivate.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.datamodel.metadata;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRException;
import com.google.gson.JsonObject;
/**
* This class holds all information of a derivate. For persistence operations
* see methods of {@link MCRMetadataManager}.
*
* @author Jens Kupferschmidt
* @author Thomas Scheffler
*/
public final class MCRDerivate extends MCRBase {
private static final Logger LOGGER = LogManager.getLogger();
public static final String ROOT_NAME = "mycorederivate";
public static final int MAX_LABEL_LENGTH = 256;
// the object content
private MCRObjectDerivate mcrDerivate;
private int order;
protected String mcrLabel = null;
/**
* This is the constructor of the MCRDerivate class. It make an instance of
* the parser class and the metadata class.
*
* @exception MCRException
* general Exception of MyCoRe
*/
public MCRDerivate() throws MCRException {
super();
mcrDerivate = new MCRObjectDerivate(getId());
order = 1;
}
public MCRDerivate(byte[] bytes, boolean valid) throws JDOMException {
this();
setFromXML(bytes, valid);
}
public MCRDerivate(Document doc) {
this();
setFromJDOM(doc);
}
public MCRDerivate(URI uri) throws IOException, JDOMException {
this();
setFromURI(uri);
}
/**
* This methode return the instance of the MCRObjectDerivate class. If this
* was not found, null was returned.
*
* @return the instance of the MCRObjectDerivate class
*/
public MCRObjectDerivate getDerivate() {
return mcrDerivate;
}
/**
* The given DOM was convert into an internal view of metadata. This are the
* object ID and the object label, also the blocks structure, flags and
* metadata.
*
* @exception MCRException
* general Exception of MyCoRe
*/
@Override
protected void setUp() throws MCRException {
super.setUp();
setLabel(jdomDocument.getRootElement().getAttributeValue("label"));
// get the derivate data of the object
Element derivateElement = jdomDocument.getRootElement().getChild("derivate");
mcrDerivate = new MCRObjectDerivate(mcrId, derivateElement);
}
/**
* This methode create a XML stream for all object data.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Document with the XML data of the object as byte array
*/
@Override
public Document createXML() throws MCRException {
Document doc = super.createXML();
Element elm = doc.getRootElement();
elm.setAttribute("order", String.valueOf(order));
if (mcrLabel != null) {
elm.setAttribute("label", mcrLabel);
}
elm.addContent(mcrDerivate.createXML());
elm.addContent(mcrService.createXML());
return doc;
}
@Override
protected String getRootTagName() {
return ROOT_NAME;
}
/**
* Reads all files and urns from the derivate.
*
* @return A {@link Map} which contains the files as key and the urns as value.
* If no URN assigned the map will be empty.
*/
public Map<String, String> getUrnMap() {
Map<String, String> fileUrnMap = new HashMap<>();
XPathExpression<Element> filesetPath = XPathFactory.instance().compile("./mycorederivate/derivate/fileset",
Filters.element());
Element result = filesetPath.evaluateFirst(this.createXML());
if (result == null) {
return fileUrnMap;
}
String urn = result.getAttributeValue("urn");
if (urn != null) {
XPathExpression<Element> filePath = XPathFactory
.instance()
.compile("./mycorederivate/derivate/fileset[@urn='" + urn + "']/file", Filters.element());
List<Element> files = filePath.evaluate(this.createXML());
for (Element currentFileElement : files) {
String currentUrn = currentFileElement.getChildText("urn");
String currentFile = currentFileElement.getAttributeValue("name");
fileUrnMap.put(currentFile, currentUrn);
}
}
return fileUrnMap;
}
/**
* This methode return the label or null if it was not set.
*
* @return the label as a string
*/
public String getLabel() {
return mcrLabel;
}
/**
* The method print all informations about this MCRObject.
*/
public void debug() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("MCRDerivate ID : {}", mcrId);
LOGGER.debug("MCRDerivate Schema : {}", mcrSchema);
LOGGER.debug("");
}
}
/**
* Validates this MCRDerivate. This method throws an exception if:
* <ul>
* <li>the mcr_id is null</li>
* <li>the XML schema is null or empty</li>
* <li>the service part is null or invalid</li>
* <li>the MCRObjectDerivate is null or invalid</li>
* </ul>
*
* @throws MCRException the MCRDerivate is invalid
*/
@Override
public void validate() throws MCRException {
super.validate();
MCRObjectDerivate derivate = getDerivate();
if (derivate == null) {
throw new MCRException("The <derivate> part of '" + getId() + "' is undefined.");
}
try {
derivate.validate();
} catch (Exception exc) {
throw new MCRException("The <derivate> part of '" + getId() + "' is invalid.", exc);
}
}
/**
* @return the {@link MCRObjectID} of the owner of the derivate
*/
public MCRObjectID getOwnerID() {
return this.getDerivate().getMetaLink().getXLinkHrefID();
}
@Override
public void setId(MCRObjectID id) {
super.setId(id);
this.mcrDerivate.setDerivateID(id);
}
/**
* This method set the derivate label.
*
* @param label - the derivate label
*/
public void setLabel(String label) {
if (label == null) {
mcrLabel = label;
} else {
mcrLabel = label.trim();
if (mcrLabel.length() > MAX_LABEL_LENGTH) {
mcrLabel = mcrLabel.substring(0, MAX_LABEL_LENGTH);
}
}
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
@Override
protected void setFromJDOM(Document doc) {
super.setFromJDOM(doc);
this.order = Optional.ofNullable(doc.getRootElement().getAttributeValue("order"))
.map(Integer::valueOf)
.orElse(1);
}
@Override
public JsonObject createJSON() {
JsonObject base = super.createJSON();
if (mcrLabel != null) {
base.addProperty("label", mcrLabel);
}
return base;
}
}
| 8,211 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRBase.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.datamodel.metadata;
import static org.mycore.common.MCRConstants.DEFAULT_ENCODING;
import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
import static org.mycore.common.MCRConstants.XSI_NAMESPACE;
import java.io.IOException;
import java.net.URI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.MCRCoreVersion;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import com.google.gson.JsonObject;
/**
* This class is a abstract basic class for objects in the MyCoRe Project. It is
* the frame to produce a full functionality object.
*
* @author Jens Kupferschmidt
*/
public abstract class MCRBase {
protected static final String MCR_ENCODING;
// the DOM document
protected Document jdomDocument = null;
// the object content
protected MCRObjectID mcrId = null;
protected String mcrVersion = null;
protected String mcrSchema = null;
protected final MCRObjectService mcrService;
// other
protected static final String NL;
protected static final String SLASH;
protected boolean importMode = false;
// logger
private static final Logger LOGGER = LogManager.getLogger();
static {
NL = System.getProperty("line.separator");
SLASH = System.getProperty("file.separator");
// Default Encoding
MCR_ENCODING = MCRConfiguration2.getString("MCR.Metadata.DefaultEncoding").orElse(DEFAULT_ENCODING);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Encoding = {}", MCR_ENCODING);
}
}
/**
* This is the constructor of the MCRBase class. It make an instance of the
* parser class and the metadata class. <br>
*
* @exception MCRException
* general Exception of MyCoRe
*/
public MCRBase() throws MCRException {
mcrVersion = MCRCoreVersion.getVersion();
mcrSchema = "";
// Service class
mcrService = new MCRObjectService();
}
protected void setFromJDOM(Document doc) {
jdomDocument = doc;
setUp();
}
protected void setUp() {
if (jdomDocument == null) {
throw new MCRException("The JDOM document is null or empty.");
}
Element rootElement = jdomDocument.getRootElement();
setId(MCRObjectID.getInstance(rootElement.getAttributeValue("ID")));
setVersion(rootElement.getAttributeValue("version"));
setSchema(rootElement.getAttribute("noNamespaceSchemaLocation", XSI_NAMESPACE).getValue());
// get the service data of the object
Element serviceElement = rootElement.getChild("service");
if (serviceElement != null) {
mcrService.setFromDOM(serviceElement);
}
}
/**
* This methode return the object id. If this is not set, null was returned.
*
* @return the id as MCRObjectID
*/
public final MCRObjectID getId() {
return mcrId;
}
/**
* This methode return the MyCoRe version of the data structure.
*
* @return the version as a string
*/
public final String getVersion() {
return mcrVersion;
}
/**
* Method returns the object schema. If the schema is not set <code>null</code> will be returned.
*
* @return the schema as a string
*/
public final String getSchema() {
return mcrSchema;
}
/**
* This methode return the instance of the MCRObjectService class. If this
* was not found, null was returned.
*
* @return the instance of the MCRObjectService class
*/
public final MCRObjectService getService() {
return mcrService;
}
/**
* This method read the XML input stream from an URI to build up the
* MyCoRe-Object.
*
* @param uri
* an URI
* @exception MCRException
* general Exception of MyCoRe
*/
protected final void setFromURI(URI uri) throws JDOMException, IOException {
setFromXML(new MCRURLContent(uri.toURL()).asByteArray(), false);
}
/**
* This method read the XML input stream from a byte array to build up the
* MyCoRe-Object.
*
* @param xml
* a XML string
* @exception MCRException
* general Exception of MyCoRe
*/
protected final void setFromXML(byte[] xml, boolean valid) throws JDOMException {
Document jdom = null;
try {
jdom = MCRXMLParserFactory.getParser(valid).parseXML(new MCRByteContent(xml));
} catch (IOException e) {
//Why oh why?
throw new JDOMException("Unexpected IOException while building JDOM document.", e);
}
setFromJDOM(jdom);
}
/**
* This method set the object ID.
*
* @param id
* the object ID
*/
public void setId(MCRObjectID id) {
mcrId = id;
}
/**
* This methods set the MyCoRe version to the string 'Version 1.3'.
*/
public final void setVersion(String version) {
mcrVersion = version != null ? version : MCRCoreVersion.getVersion();
}
/**
* This methode set the object schema.
*
* @param schema
* the object schema
*/
public final void setSchema(String schema) {
if (schema == null) {
mcrSchema = "";
return;
}
mcrSchema = schema.trim();
}
/**
* This method create a XML stream for all object data.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Document with the XML data of the object as byte array
*/
public Document createXML() throws MCRException {
validate();
Element elm = new Element(getRootTagName());
Document doc = new Document(elm);
elm.addNamespaceDeclaration(XSI_NAMESPACE);
elm.addNamespaceDeclaration(XLINK_NAMESPACE);
elm.setAttribute("noNamespaceSchemaLocation", mcrSchema, XSI_NAMESPACE);
elm.setAttribute("ID", mcrId.toString());
elm.setAttribute("version", mcrVersion);
return doc;
}
/**
* Creates the JSON representation of this object.
*
* <pre>
* {
* id: "mycore_project_00000001",
* version: "3.0"
* }
* </pre>
*
*/
public JsonObject createJSON() {
JsonObject object = new JsonObject();
object.addProperty("id", mcrId.toString());
object.addProperty("version", mcrVersion);
return object;
}
protected abstract String getRootTagName();
/**
* This method check the validation of the content of this class. The method
* returns <em>true</em> if
* <ul>
* <li>the mcr_id value is valid
* </ul>
* otherwise the method return <em>false</em>
*
* @return a boolean value
*/
public boolean isValid() {
try {
validate();
return true;
} catch (MCRException exc) {
LOGGER.warn("The content of this object '{}' is invalid.", mcrId, exc);
}
return false;
}
/**
* Validates the content of this class. This method throws an exception if:
* <ul>
* <li>the mcr_id is null</li>
* <li>the XML schema is null or empty</li>
* <li>the service part is null or invalid</li>
* </ul>
*
* @throws MCRException the content is invalid
*/
public void validate() throws MCRException {
if (mcrId == null) {
throw new MCRException("MCRObjectID is undefined.");
}
if (getSchema() == null || getSchema().length() == 0) {
throw new MCRException("XML Schema of '" + mcrId + "' is undefined.");
}
MCRObjectService service = getService();
if (service == null) {
throw new MCRException("The <service> part of '" + mcrId + "' is undefined.");
}
try {
service.validate();
} catch (MCRException exc) {
throw new MCRException("The <service> part of '" + mcrId + "' is invalid.", exc);
}
}
public boolean isImportMode() {
return importMode;
}
public void setImportMode(boolean importMode) {
this.importMode = importMode;
}
@Override
public String toString() {
return this.mcrId.toString();
}
}
| 9,521 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaAddress.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaAddress.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.datamodel.metadata;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import com.google.gson.JsonObject;
/**
* This class implements all methods for handling with the MCRMetaAddress part
* of a metadata object. The MCRMetaAddress class represents a natural address
* specified by a list of names.
*
* @author J. Vogler
*/
public final class MCRMetaAddress extends MCRMetaDefault {
// MetaAddress data
private String country;
private String state;
private String zipCode;
private String city;
private String street;
private String number;
private static final Logger LOGGER = LogManager.getLogger();
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. All other elemnts are set to
* an empty string.
*/
public MCRMetaAddress() {
super();
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>defaultLang</em> is
* null, empty or false <b>en </b> was set. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was thrown. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The country, state, zipCode, city, street and
* number element was set to the value of <em>...</em>, if they are null,
* an empty string was set to this element.
* @param subtag the name of the subtag
* @param defaultLang the default language
* @param type the optional type string
* @param inherted a value >= 0
* @param country the country name
* @param state the state name
* @param zipcode the zipCode string
* @param city the city name
* @param street the street name
* @param number the number string
*
* @exception MCRException if the parameter values are invalid
*/
public MCRMetaAddress(final String subtag, final String defaultLang, final String type,
final int inherted, final String country,
final String state, final String zipcode, final String city, final String street,
final String number) throws MCRException {
super(subtag, defaultLang, type, inherted);
setCountry(country);
setState(state);
setZipCode(zipcode);
setCity(city);
setStreet(street);
setNumber(number);
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaAddress clone() {
MCRMetaAddress clone = (MCRMetaAddress) super.clone();
clone.country = this.country;
clone.state = this.state;
clone.zipCode = this.zipCode;
clone.city = this.city;
clone.street = this.street;
clone.number = this.number;
return clone;
}
/**
* This method creates a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaAddress definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaAddress part
*/
@Override
public Element createXML() throws MCRException {
final Element elm = super.createXML();
if (getCountry() != null) {
elm.addContent(new Element("country").addContent(getCountry()));
}
if (getState() != null) {
elm.addContent(new Element("state").addContent(getState()));
}
if (getZipCode() != null) {
elm.addContent(new Element("zipcode").addContent(getZipCode()));
}
if (getCity() != null) {
elm.addContent(new Element("city").addContent(getCity()));
}
if (getStreet() != null) {
elm.addContent(new Element("street").addContent(getStreet()));
}
if (getNumber() != null) {
elm.addContent(new Element("number").addContent(getNumber()));
}
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* "country": "Deutschland",
* "state": "Thüringen",
* "zipcode": "07743",
* "city": "Jena",
* "street": "Bibliothekspl.",
* "number": "2"
* }
* </pre>
*
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
if (getCountry() != null) {
obj.addProperty("country", getCountry());
}
if (getState() != null) {
obj.addProperty("state", getState());
}
if (getZipCode() != null) {
obj.addProperty("zipcode", getZipCode());
}
if (getCity() != null) {
obj.addProperty("city", getCity());
}
if (getStreet() != null) {
obj.addProperty("street", getStreet());
}
if (getNumber() != null) {
obj.addProperty("number", getNumber());
}
return obj;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Country = {}", country);
LOGGER.debug("State = {}", state);
LOGGER.debug("Zipcode = {}", zipCode);
LOGGER.debug("City = {}", city);
LOGGER.debug("Street = {}", street);
LOGGER.debug("Number = {}", number);
LOGGER.debug(" ");
}
}
/**
* Check the equivalence between this instance and the given object.
*
* @param obj the MCRMetaAddress object
* @return true if its equal
*/
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaAddress other = (MCRMetaAddress) obj;
return Objects.equals(this.country, other.country) && Objects.equals(this.state, other.state)
&& Objects.equals(this.zipCode, other.zipCode) && Objects.equals(this.city, other.city)
&& Objects.equals(this.street, other.street) && Objects.equals(this.number, other.number);
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @return the country
*/
public String getCountry() {
return country;
}
/**
* @return the number
*/
public String getNumber() {
return number;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @return the street
*/
public String getStreet() {
return street;
}
/**
* @return the zipCode
*/
public String getZipCode() {
return zipCode;
}
/**
* Validates this MCRMetaAddress. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>all of country, state, zip, city, street and number is empty</li>
* </ul>
*
* @throws MCRException the MCRMetaAddress is invalid
*/
public void validate() throws MCRException {
super.validate();
if (getCountry() == null && getState() == null && getZipCode() == null && getCity() == null
&& getStreet() == null && getNumber() == null) {
throw new MCRException(getSubTag() + ": address is empty");
}
}
/**
* @param city the city to set
*/
public void setCity(final String city) {
this.city = city;
}
/**
* @param country the country to set
*/
public void setCountry(final String country) {
this.country = country;
}
/**
* This method reads the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(final Element element) {
super.setFromDOM(element);
country = element.getChildTextTrim("country");
state = element.getChildTextTrim("state");
zipCode = element.getChildTextTrim("zipcode");
city = element.getChildTextTrim("city");
street = element.getChildTextTrim("street");
number = element.getChildTextTrim("number");
}
/**
* @param number the number to set
*/
public void setNumber(final String number) {
this.number = number;
}
/**
* @param state the state to set
*/
public void setState(final String state) {
this.state = state;
}
/**
* @param street the street to set
*/
public void setStreet(final String street) {
this.street = street;
}
/**
* @param zipCode the zipCode to set
*/
public void setZipCode(final String zipCode) {
this.zipCode = zipCode;
}
}
| 10,294 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* All classes related to the change history of {@link org.mycore.datamodel.metadata.MCRObject}
* and {@link org.mycore.datamodel.metadata.MCRDerivate}.
*
* @author Thomas Scheffler
*
*/
package org.mycore.datamodel.metadata.history;
| 971 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataHistoryEventType.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryEventType.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.datamodel.metadata.history;
public enum MCRMetadataHistoryEventType {
Create('c'), Delete('d');
private final char abbr;
MCRMetadataHistoryEventType(char abbr) {
this.abbr = abbr;
}
public static MCRMetadataHistoryEventType fromAbbr(char abbr) {
return switch (abbr) {
case 'c' -> MCRMetadataHistoryEventType.Create;
case 'd' -> MCRMetadataHistoryEventType.Delete;
default -> throw new IllegalArgumentException(
"No such " + MCRMetadataHistoryEventType.class.getSimpleName() + ": " + abbr);
};
}
protected char getAbbr() {
return abbr;
}
}
| 1,409 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaHistoryItem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetaHistoryItem.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.datamodel.metadata.history;
import java.io.Serializable;
import java.time.Instant;
import jakarta.persistence.Basic;
import org.mycore.backend.jpa.MCRObjectIDConverter;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
/**
* Entity implementation class for Entity: MCRMetaHistoryItem
*
*/
@Entity
@Table(name = "MCRMetaHistory",
indexes = {
@Index(name = "IDX_ID_TIME", columnList = "id,time"),
@Index(name = "IDX_TIME", columnList = "time")
})
@NamedQueries({
@NamedQuery(name = "MCRMetaHistory.getLastOfType",
query = "SELECT MAX(time) FROM MCRMetaHistoryItem i WHERE i.id=:id and i.eventTypeChar=:type"),
@NamedQuery(name = "MCRMetaHistory.getLastEventByID",
query = "SELECT a FROM MCRMetaHistoryItem a "
+ "WHERE a.time BETWEEN :from AND :until "
+ "AND a.eventTypeChar=:eventType "
+ "ORDER BY a.time DESC "
+ "FETCH FIRST 1 ROWS ONLY"),
@NamedQuery(name = "MCRMetaHistory.getFirstDate", query = "SELECT MIN(time) from MCRMetaHistoryItem"),
@NamedQuery(name = "MCRMetaHistory.getHighestID",
query = "SELECT MAX(history.id) from MCRMetaHistoryItem history"
+ " WHERE CAST(history.id as string) like :looksLike escape '\\'"),
@NamedQuery(name = "MCRMetaHistory.getNextActiveIDs",
query = "SELECT c"
+ " FROM MCRMetaHistoryItem c"
+ " WHERE (:afterID is null or c.id >:afterID)"
+ " AND c.eventTypeChar='Created'"
+ " AND (:kind!='object' OR CAST(c.id as string) NOT LIKE '%\\_derivate\\_%')"
+ " AND (:kind!='derivate' OR CAST(c.id as string) LIKE '%\\_derivate\\_%')"
+ " AND (NOT EXISTS (SELECT d.time FROM MCRMetaHistoryItem d WHERE d.eventTypeChar ='d' AND c.id=d.id)"
+ " OR c.time > ALL (SELECT d.time FROM MCRMetaHistoryItem d "
+ " WHERE d.eventTypeChar ='d' AND c.id=d.id))"
+ " ORDER by c.id"),
@NamedQuery(name = "MCRMetaHistory.countActiveIDs",
query = "SELECT count(c)"
+ " FROM MCRMetaHistoryItem c"
+ " WHERE c.eventTypeChar='Created'"
+ " AND (:kind!='object' OR CAST(c.id as string) NOT LIKE '%\\_derivate\\_%')"
+ " AND (:kind!='derivate' OR CAST(c.id as string) LIKE '%\\_derivate\\_%')"
+ " AND (NOT EXISTS (SELECT d.time FROM MCRMetaHistoryItem d WHERE d.eventTypeChar ='d' AND c.id=d.id)"
+ " OR c.time > ALL (SELECT d.time FROM MCRMetaHistoryItem d "
+ " WHERE d.eventTypeChar ='d' AND c.id=d.id))")
})
public class MCRMetaHistoryItem implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long internalid;
@Column(length = MCRObjectID.MAX_LENGTH)
@Convert(converter = MCRObjectIDConverter.class)
@Basic
private MCRObjectID id;
private Instant time;
@Column(length = 1, name = "eventType")
private char eventTypeChar;
private String userID;
private String userIP;
private static final long serialVersionUID = 1L;
static MCRMetaHistoryItem createdNow(MCRObjectID id) {
return now(id, MCRMetadataHistoryEventType.Create);
}
static MCRMetaHistoryItem deletedNow(MCRObjectID id) {
return now(id, MCRMetadataHistoryEventType.Delete);
}
static MCRMetaHistoryItem now(MCRObjectID id, MCRMetadataHistoryEventType type) {
MCRMetaHistoryItem historyItem = new MCRMetaHistoryItem();
historyItem.setId(id);
historyItem.setTime(Instant.now());
historyItem.setEventType(type);
if (MCRSessionMgr.hasCurrentSession()) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
historyItem.setUserID(currentSession.getUserInformation().getUserID());
historyItem.setUserIP(currentSession.getCurrentIP());
}
return historyItem;
}
public long getInternalid() {
return this.internalid;
}
public void setInternalid(long internalid) {
this.internalid = internalid;
}
public MCRObjectID getId() {
return this.id;
}
public void setId(MCRObjectID id) {
this.id = id;
}
public Instant getTime() {
return this.time;
}
public void setTime(Instant time) {
this.time = time;
}
public MCRMetadataHistoryEventType getEventType() {
return MCRMetadataHistoryEventType.fromAbbr(getEventTypeChar());
}
public void setEventType(MCRMetadataHistoryEventType eventType) {
setEventTypeChar(eventType.getAbbr());
}
public String getUserID() {
return this.userID;
}
public void setUserID(String userId) {
this.userID = userId;
}
public String getUserIP() {
return this.userIP;
}
public void setUserIP(String ip) {
this.userIP = ip;
}
public char getEventTypeChar() {
return eventTypeChar;
}
public void setEventTypeChar(char eventTypeChar) {
this.eventTypeChar = eventTypeChar;
}
@Override
public String toString() {
return "MCRMetaHistoryItem [eventType=" + getEventType() + ", id=" + id + ", time=" + time + ", userID="
+ userID + ", userIP=" + userIP + "]";
}
}
| 6,571 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataHistoryManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryManager.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.datamodel.metadata.history;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.mycore.access.MCRAccessManager;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
/**
* @author Thomas Scheffler
*
*/
public class MCRMetadataHistoryManager extends MCREventHandlerBase {
public static Optional<MCRObjectID> getHighestStoredID(String project, String type) {
String looksLike = Objects.requireNonNull(project) + "\\_" + Objects.requireNonNull(type) + "%";
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRObjectID> query = em.createNamedQuery("MCRMetaHistory.getHighestID", MCRObjectID.class);
query.setParameter("looksLike", looksLike);
return Optional.ofNullable(query.getSingleResult());
}
public static Optional<Instant> getHistoryStart() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<Instant> query = em.createNamedQuery("MCRMetaHistory.getFirstDate", Instant.class);
return Optional.ofNullable(query.getSingleResult());
}
public static Map<MCRObjectID, Instant> getDeletedItems(Instant from, Optional<Instant> until) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRMetaHistoryItem> query = em.createNamedQuery("MCRMetaHistory.getLastEventByID",
MCRMetaHistoryItem.class);
query.setParameter("from", from);
query.setParameter("until", until.orElseGet(Instant::now));
query.setParameter("eventType", MCRMetadataHistoryEventType.Delete.getAbbr());
return query.getResultList()
.stream()
.collect(Collectors.toMap(MCRMetaHistoryItem::getId, MCRMetaHistoryItem::getTime));
}
public static Optional<Instant> getLastDeletedDate(MCRObjectID identifier) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<Instant> query = em.createNamedQuery("MCRMetaHistory.getLastOfType", Instant.class);
query.setParameter("id", identifier);
query.setParameter("type", MCRMetadataHistoryEventType.Delete.getAbbr());
return Optional.ofNullable(query.getSingleResult());
}
public static List<MCRMetaHistoryItem> listNextObjectIDs(MCRObjectID afterID, int maxResults) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRMetaHistoryItem> query = em.createNamedQuery("MCRMetaHistory.getNextActiveIDs",
MCRMetaHistoryItem.class);
query.setParameter("afterID", afterID);
query.setParameter("kind", "object");
query.setMaxResults(maxResults);
return query.getResultList();
}
public static List<MCRMetaHistoryItem> listNextDerivateIDs(MCRObjectID afterID, int maxResults) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRMetaHistoryItem> query = em.createNamedQuery("MCRMetaHistory.getNextActiveIDs",
MCRMetaHistoryItem.class);
query.setParameter("afterID", afterID);
query.setParameter("kind", "derivate");
query.setMaxResults(maxResults);
return query.getResultList();
}
public static Long countObjectIDs() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<Long> query = em.createNamedQuery("MCRMetaHistory.countActiveIDs",
Long.class);
query.setParameter("kind", "object");
return query.getSingleResult();
}
public static Long countDerivateIDs() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<Long> query = em.createNamedQuery("MCRMetaHistory.countActiveIDs",
Long.class);
query.setParameter("kind", "derivate");
return query.getSingleResult();
}
private void createNow(MCRObjectID id) {
store(MCRMetaHistoryItem.createdNow(id));
}
private void deleteNow(MCRObjectID id) {
store(MCRMetaHistoryItem.deletedNow(id));
}
private void store(MCRMetaHistoryItem item) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.persist(item);
}
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
createNow(obj.getId());
if (objectIsHidden(obj)) {
deleteNow(obj.getId());
}
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
MCRObject oldVersion = (MCRObject) evt.get(MCREvent.OBJECT_OLD_KEY);
if (updateRequired(oldVersion, obj)) {
if (objectIsHidden(obj)) {
deleteNow(obj.getId());
} else {
createNow(obj.getId());
}
}
}
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
deleteNow(obj.getId());
}
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
createNow(der.getId());
if (!MCRAccessManager.checkDerivateDisplayPermission(der.getId().toString())) {
deleteNow(der.getId());
}
}
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
MCRDerivate oldVersion = (MCRDerivate) evt.get(MCREvent.DERIVATE_OLD_KEY);
if (updateRequired(oldVersion, der)) {
if (MCRAccessManager.checkDerivateDisplayPermission(der.getId().toString())) {
createNow(der.getId());
} else {
deleteNow(der.getId());
}
}
}
@Override
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
deleteNow(der.getId());
}
private boolean updateRequired(MCRObject oldVersion, MCRObject newVersion) {
return objectIsHidden(oldVersion) != objectIsHidden(newVersion);
}
static boolean objectIsHidden(MCRObject obj) {
MCRCategoryID state = obj.getService().getState();
if (state == null) {
LogManager.getLogger().debug("{} is visible as it does not use a service state.", obj.getId());
return false;
}
boolean hidden = !"published".equals(state.getId());
LogManager.getLogger().debug("{} is hidden due to service state '{}': {}", obj.getId(), state, hidden);
return hidden;
}
private boolean updateRequired(MCRDerivate oldVersion, MCRDerivate newVersion) {
return MCRAccessManager.checkDerivateDisplayPermission(oldVersion.getId().toString()) != MCRAccessManager
.checkDerivateDisplayPermission(newVersion.getId().toString());
}
}
| 8,015 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataHistoryCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryCommands.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.datamodel.metadata.history;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.jdom2.JDOMException;
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.MCRUsageException;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.mycore.datamodel.common.MCRCreatorCache;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.ifs2.MCRMetadataVersion;
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.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.util.concurrent.MCRTransactionableCallable;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.Root;
/**
* @author Thomas Scheffler (yagee)
*
*/
@MCRCommandGroup(name = "Metadata history")
public class MCRMetadataHistoryCommands {
@MCRCommand(syntax = "clear metadata history of base {0}",
help = "clears metadata history of all objects with base id {0}")
public static void clearHistory(String baseId) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaDelete<MCRMetaHistoryItem> delete = cb.createCriteriaDelete(MCRMetaHistoryItem.class);
Root<MCRMetaHistoryItem> item = delete.from(MCRMetaHistoryItem.class);
int rowsDeleted = em.createQuery(
delete.where(
cb.like(item.get(MCRMetaHistoryItem_.id).as(String.class), baseId + "_".replace("_", "$_") + '%', '$')))
.executeUpdate();
LogManager.getLogger().info("Deleted {} items in history of {}", rowsDeleted, baseId);
}
@MCRCommand(syntax = "clear metadata history of id {0}",
help = "clears metadata history of object/derivate with id {0}")
public static void clearSingleHistory(String mcrId) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaDelete<MCRMetaHistoryItem> delete = cb.createCriteriaDelete(MCRMetaHistoryItem.class);
Root<MCRMetaHistoryItem> item = delete.from(MCRMetaHistoryItem.class);
int rowsDeleted = em.createQuery(
delete.where(cb.equal(item.get(MCRMetaHistoryItem_.id).as(String.class), mcrId)))
.executeUpdate();
LogManager.getLogger().info("Deleted {} items in history of {}", rowsDeleted, mcrId);
}
@MCRCommand(syntax = "clear metadata history completely", help = "clears metadata history completely")
public static List<String> clearHistory() {
return MCRXMLMetadataManager.instance()
.getObjectBaseIds()
.stream()
.map(s -> "clear metadata history of base " + s)
.collect(Collectors.toList());
}
@MCRCommand(syntax = "build metadata history completely", help = "build metadata history completely")
public static List<String> buildHistory() {
return MCRXMLMetadataManager.instance()
.getObjectBaseIds()
.stream()
.map(s -> "build metadata history of base " + s)
.collect(Collectors.toList());
}
@MCRCommand(syntax = "build metadata history of base {0}",
help = "build metadata history of all objects with base id {0}")
public static List<String> buildHistory(String baseId) {
MCRXMLMetadataManager mm = MCRXMLMetadataManager.instance();
mm.verifyStore(baseId);
ExecutorService executorService = Executors.newWorkStealingPool();
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
String[] idParts = MCRObjectID.getIDParts(baseId);
if (idParts.length != 2) {
throw new MCRUsageException("Valid base ID required!");
}
int maxId = mm.getHighestStoredID(idParts[0], idParts[1]);
AtomicInteger completed = new AtomicInteger(maxId);
IntStream.rangeClosed(1, maxId)
.parallel()
.mapToObj(i -> MCRObjectID.formatID(baseId, i))
.map(MCRObjectID::getInstance)
.map(id -> new MCRTransactionableCallable<>(Executors.callable(() -> {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
getHistoryItems(id).sequential().forEach(em::persist);
completed.decrementAndGet();
}), currentSession))
.forEach(executorService::submit);
executorService.shutdown();
boolean waitToFinish = true;
while (!executorService.isTerminated() && waitToFinish) {
LogManager.getLogger().info("Waiting for history of {} objects/derivates.", completed.get());
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
waitToFinish = false;
}
}
return Collections.emptyList();
}
@MCRCommand(syntax = "build metadata history of id {0}",
help = "build metadata history of object/derivate with id {0}")
public static void buildSingleHistory(String mcrId) {
MCRObjectID objId = MCRObjectID.getInstance(mcrId);
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
getHistoryItems(objId).sequential().forEach(em::persist);
}
private static Stream<MCRMetaHistoryItem> getHistoryItems(MCRObjectID objId) {
return objId.getTypeId().equals("derivate") ? buildDerivateHistory(objId)
: buildObjectHistory(objId);
}
private static Stream<MCRMetaHistoryItem> buildDerivateHistory(MCRObjectID derId) {
try {
List<? extends MCRAbstractMetadataVersion<?>> versions = MCRXMLMetadataManager.instance()
.listRevisions(derId);
if (versions == null || versions.isEmpty()) {
return buildSimpleDerivateHistory(derId);
} else {
return buildDerivateHistory(derId, versions);
}
} catch (IOException e) {
LogManager.getLogger().error("Error while getting history of {}", derId);
return Stream.empty();
}
}
private static Stream<MCRMetaHistoryItem> buildObjectHistory(MCRObjectID objId) {
try {
List<? extends MCRAbstractMetadataVersion<?>> versions = MCRXMLMetadataManager.instance()
.listRevisions(objId);
if (versions == null || versions.isEmpty()) {
return buildSimpleObjectHistory(objId);
} else {
return buildObjectHistory(objId, versions);
}
} catch (IOException e) {
LogManager.getLogger().error("Error while getting history of {}", objId);
return Stream.empty();
}
}
private static Stream<MCRMetaHistoryItem> buildSimpleDerivateHistory(MCRObjectID derId) throws IOException {
LogManager.getLogger().debug("Store of {} has no old revisions. History rebuild is limited", derId);
if (MCRMetadataManager.exists(derId)) {
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derId);
Instant lastModified = Instant
.ofEpochMilli(MCRXMLMetadataManager.instance().getLastModified(derId));
String creator;
try {
creator = MCRCreatorCache.getCreator(der.getId());
} catch (ExecutionException e) {
LogManager.getLogger().warn("Error while getting creator of {}", derId, e);
creator = null;
}
String user = Optional.ofNullable(creator)
.orElseGet(() -> MCRSystemUserInformation.getSystemUserInstance().getUserID());
MCRMetaHistoryItem create = create(derId,
user,
lastModified);
boolean objectIsHidden = !MCRAccessManager.checkDerivateDisplayPermission(derId.toString());
if (objectIsHidden) {
return Stream.of(create, delete(derId, user, lastModified.plusMillis(1)));
}
return Stream.of(create);
} else {
return Stream.of(delete(derId, null, Instant.now()));
}
}
private static Stream<MCRMetaHistoryItem> buildSimpleObjectHistory(MCRObjectID objId) throws IOException {
LogManager.getLogger().debug("Store of {} has no old revisions. History rebuild is limited", objId);
if (MCRMetadataManager.exists(objId)) {
MCRObject obj = MCRMetadataManager.retrieveMCRObject(objId);
Instant lastModified = Instant
.ofEpochMilli(MCRXMLMetadataManager.instance().getLastModified(objId));
String creator;
try {
creator = MCRCreatorCache.getCreator(obj.getId());
} catch (ExecutionException e) {
LogManager.getLogger().warn("Error while getting creator of {}", objId, e);
creator = null;
}
String user = Optional.ofNullable(creator)
.orElseGet(() -> MCRSystemUserInformation.getSystemUserInstance().getUserID());
MCRMetaHistoryItem create = create(objId, user, lastModified);
boolean objectIsHidden = MCRMetadataHistoryManager.objectIsHidden(obj);
if (objectIsHidden) {
return Stream.of(create, delete(objId, user, lastModified.plusMillis(1)));
}
return Stream.of(create);
} else {
return Stream.of(delete(objId, null, Instant.now()));
}
}
private static Stream<MCRMetaHistoryItem> buildDerivateHistory(MCRObjectID derId,
List<? extends MCRAbstractMetadataVersion<?>> versions)
throws IOException {
boolean exist = false;
LogManager.getLogger().debug("Complete history rebuild of {} should be possible", derId);
ArrayList<MCRMetaHistoryItem> items = new ArrayList<>(100);
for (MCRAbstractMetadataVersion<?> version : versions) {
String user = version.getUser();
Instant revDate = version.getDate().toInstant();
if (version.getType() == MCRMetadataVersion.DELETED) {
if (exist) {
items.add(delete(derId, user, revDate));
exist = false;
}
} else {
//created or updated
int timeOffset = 0;
if (version.getType() == MCRMetadataVersion.CREATED && !exist) {
items.add(create(derId, user, revDate));
timeOffset = 1;
exist = true;
}
try {
MCRDerivate derivate = new MCRDerivate(version.retrieve().asXML());
boolean derivateIsHidden = !MCRAccessManager
.checkDerivateDisplayPermission(derivate.getId().toString());
if (derivateIsHidden && exist) {
items.add(delete(derId, user, revDate.plusMillis(timeOffset)));
exist = false;
} else if (!derivateIsHidden && !exist) {
items.add(create(derId, user,
revDate.plusMillis(timeOffset)));
exist = true;
}
} catch (JDOMException e) {
LogManager.getLogger()
.error("Error while reading revision {} of {}", version.getRevision(), derId, e);
}
}
}
return items.stream();
}
private static Stream<MCRMetaHistoryItem> buildObjectHistory(MCRObjectID objId,
List<? extends MCRAbstractMetadataVersion<?>> versions)
throws IOException {
boolean exist = false;
LogManager.getLogger().debug("Complete history rebuild of {} should be possible", objId);
ArrayList<MCRMetaHistoryItem> items = new ArrayList<>(100);
for (MCRAbstractMetadataVersion<?> version : versions) {
String user = version.getUser();
Instant revDate = version.getDate().toInstant();
if (version.getType() == MCRMetadataVersion.DELETED) {
if (exist) {
items.add(delete(objId, user, revDate));
exist = false;
}
} else {
//created or updated
int timeOffset = 0;
if (version.getType() == MCRMetadataVersion.CREATED && !exist) {
items.add(create(objId, user, revDate));
timeOffset = 1;
exist = true;
}
try {
MCRObject obj = new MCRObject(version.retrieve().asXML());
boolean objectIsHidden = MCRMetadataHistoryManager.objectIsHidden(obj);
if (objectIsHidden && exist) {
items.add(delete(objId, user, revDate.plusMillis(timeOffset)));
exist = false;
} else if (!objectIsHidden && !exist) {
items.add(create(objId, user, revDate.plusMillis(timeOffset)));
exist = true;
}
} catch (JDOMException e) {
LogManager.getLogger()
.error("Error while reading revision {} of {}", version.getRevision(), objId, e);
}
}
}
return items.stream();
}
private static MCRMetaHistoryItem create(MCRObjectID mcrid, String author, Instant instant) {
return newHistoryItem(mcrid, author, instant, MCRMetadataHistoryEventType.Create);
}
private static MCRMetaHistoryItem delete(MCRObjectID mcrid, String author, Instant instant) {
return newHistoryItem(mcrid, author, instant, MCRMetadataHistoryEventType.Delete);
}
private static MCRMetaHistoryItem newHistoryItem(MCRObjectID mcrid, String author, Instant instant,
MCRMetadataHistoryEventType eventType) {
MCRMetaHistoryItem item = new MCRMetaHistoryItem();
item.setId(mcrid);
item.setTime(instant);
item.setUserID(author);
item.setEventType(eventType);
LogManager.getLogger().debug(() -> item);
return item;
}
}
| 16,053 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/share/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Contains classes dealing with sharing of metadata.
*
* @author Thomas Scheffler (yagee)
* @since 2015.03
*/
package org.mycore.datamodel.metadata.share;
| 892 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataShareAgentFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/share/MCRMetadataShareAgentFactory.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.datamodel.metadata.share;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* This factory creates {@link MCRMetadataShareAgent} instances.
*
* To configure a custom metadata share agent define a property <code>MCR.Metadata.ShareAgent.{objectType}</code>
* that points to a class that implements the {@link MCRMetadataShareAgent} interface.
* @author Thomas Scheffler (yagee)
*
*/
public class MCRMetadataShareAgentFactory {
private static final String CONFIG_PREFIX = "MCR.Metadata.ShareAgent.";
private static final MCRDefaultMetadataShareAgent DEFAULT_AGENT = new MCRDefaultMetadataShareAgent();
public static MCRMetadataShareAgent getAgent(MCRObjectID objectId) {
String propertyName = CONFIG_PREFIX + objectId.getTypeId();
return MCRConfiguration2.<MCRMetadataShareAgent>getSingleInstanceOf(propertyName)
.orElseGet(MCRMetadataShareAgentFactory::getDefaultAgent);
}
/**
* Standard agent that uses <code>org.mycore.datamodel.MCRMeta*</code> classes.
*/
public static MCRMetadataShareAgent getDefaultAgent() {
return DEFAULT_AGENT;
}
}
| 1,930 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataShareAgent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/share/MCRMetadataShareAgent.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.datamodel.metadata.share;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.datamodel.metadata.MCRObject;
/**
* @author Thomas Scheffler (yagee)
* @see MCRMetadataShareAgentFactory
*/
public interface MCRMetadataShareAgent {
/**
* Determines if shareable metadata changed from <code>oldVersion</code> to <code>newVersion</code>
* @param oldVersion previous version of MCRObject
* @param newVersion new version of MCRObject
*/
boolean shareableMetadataChanged(MCRObject oldVersion, MCRObject newVersion);
/**
* updates all recipients of shareable metadata from <code>holder</code>.
* @param holder usually the parent object that can distrivute metadata
*/
void distributeMetadata(MCRObject holder) throws MCRPersistenceException, MCRAccessException;
/**
* Include shareable metadata from <code>holder</code> before persisting <code>recipient</code>.
* @param recipient on update/create before handling events.
*/
void receiveMetadata(MCRObject recipient);
}
| 1,848 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultMetadataShareAgent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/share/MCRDefaultMetadataShareAgent.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.datamodel.metadata.share;
import java.util.stream.StreamSupport;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.datamodel.metadata.MCRMetaElement;
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.metadata.MCRObjectMetadata;
/**
* @author Thomas Scheffler (yagee)
*/
class MCRDefaultMetadataShareAgent implements MCRMetadataShareAgent {
private static final Logger LOGGER = LogManager.getLogger();
/* (non-Javadoc)
* @see org.mycore.datamodel.metadata.share.MCRMetadataShareAgent#inheritableMetadataChanged(org.mycore.datamodel.metadata.MCRObject, org.mycore.datamodel.metadata.MCRObject)
*/
@Override
public boolean shareableMetadataChanged(MCRObject oldVersion, MCRObject newVersion) {
final MCRObjectMetadata md = newVersion.getMetadata();
final MCRObjectMetadata mdold = oldVersion.getMetadata();
final Element newXML = md.createXML();
Element oldXML = null;
try {
oldXML = mdold.createXML();
} catch (MCRException exc) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("The old metadata of the object {} was invalid.", oldVersion.getId(), exc);
}
}
//simple save without changes, this is also a short-path for mycore-mods
//TODO: handle inheritance of mycore-mods in that component
if (oldXML != null && MCRXMLHelper.deepEqual(newXML, oldXML)) {
return false;
}
int numheritablemd = 0;
int numheritablemdold;
for (int i = 0; i < md.size(); i++) {
final MCRMetaElement melm = md.getMetadataElement(i);
if (melm.isHeritable()) {
numheritablemd++;
try {
final MCRMetaElement melmold = mdold.getMetadataElement(melm.getTag());
final Element jelm = melm.createXML(true);
Element jelmold = null;
try {
jelmold = melmold.createXML(true);
} catch (MCRException exc) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("One of the old metadata elements is invalid.", exc);
}
}
if (jelmold == null || !MCRXMLHelper.deepEqual(jelmold, jelm)) {
return true;
}
} catch (final RuntimeException e) {
return true;
}
}
}
numheritablemdold = (int) StreamSupport.stream(mdold.spliterator(), false)
.filter(MCRMetaElement::isHeritable)
.count();
return numheritablemd != numheritablemdold;
}
/* (non-Javadoc)
* @see org.mycore.datamodel.metadata.share.MCRMetadataShareAgent#inheritMetadata(org.mycore.datamodel.metadata.MCRObject)
*/
@Override
public void distributeMetadata(MCRObject parent) throws MCRPersistenceException, MCRAccessException {
for (MCRMetaLinkID childId : parent.getStructure().getChildren()) {
LOGGER.debug("Update metadata from Child {}", childId);
final MCRObject child = MCRMetadataManager.retrieveMCRObject(childId.getXLinkHrefID());
MCRMetadataManager.update(child);
}
}
/* (non-Javadoc)
* @see org.mycore.datamodel.metadata.share.MCRMetadataShareAgent#inheritMetadata(org.mycore.datamodel.metadata.MCRObject, org.mycore.datamodel.metadata.MCRObject)
*/
@Override
public void receiveMetadata(MCRObject child) {
MCRObjectID parentID = child.getStructure().getParentID();
if (parentID == null) {
return;
}
LOGGER.debug("Parent ID = {}", parentID);
MCRObject parent = MCRMetadataManager.retrieveMCRObject(parentID);
// remove already embedded inherited tags
child.getMetadata().removeInheritedMetadata();
// insert heritable tags
child.getMetadata().appendMetadata(parent.getMetadata().getHeritableMetadata());
}
}
| 5,258 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREditorMetadataValidator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/validator/MCREditorMetadataValidator.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.datamodel.metadata.validator;
import org.jdom2.Element;
/**
* Validates the output of the Editor framework.
* Implementors have to be thread safe.
* @author Thomas Scheffler (yagee)
*/
public interface MCREditorMetadataValidator {
/**
* Gives hints to the editor form developer.
*
* If an element is not valid it is removed from the JDOM document.
* The returned String then can give a hint to the form developer, why it is removed.
* This method may throw a {@link RuntimeException} in which case the whole validation process will fail.
* @return
* null, everything is OK
* validation error message
*/
String checkDataSubTag(Element datasubtag);
}
| 1,459 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREditorOutValidator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/validator/MCREditorOutValidator.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.datamodel.metadata.validator;
import static org.jdom2.Namespace.XML_NAMESPACE;
import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
import static org.mycore.common.MCRConstants.XSI_NAMESPACE;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathFactory;
import org.mycore.access.MCRAccessManager;
import org.mycore.access.MCRRuleAccessInterface;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.metadata.MCRMetaAccessRule;
import org.mycore.datamodel.metadata.MCRMetaAddress;
import org.mycore.datamodel.metadata.MCRMetaBoolean;
import org.mycore.datamodel.metadata.MCRMetaClassification;
import org.mycore.datamodel.metadata.MCRMetaDerivateLink;
import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID;
import org.mycore.datamodel.metadata.MCRMetaHistoryDate;
import org.mycore.datamodel.metadata.MCRMetaISO8601Date;
import org.mycore.datamodel.metadata.MCRMetaInstitutionName;
import org.mycore.datamodel.metadata.MCRMetaInterface;
import org.mycore.datamodel.metadata.MCRMetaLangText;
import org.mycore.datamodel.metadata.MCRMetaLink;
import org.mycore.datamodel.metadata.MCRMetaLinkID;
import org.mycore.datamodel.metadata.MCRMetaNumber;
import org.mycore.datamodel.metadata.MCRMetaPersonName;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* @author Thomas Scheffler (yagee)
*/
public class MCREditorOutValidator {
private static final String CONFIG_PREFIX = "MCR.EditorOutValidator.";
private static final SAXBuilder SAX_BUILDER = new SAXBuilder();
private static Logger LOGGER = LogManager.getLogger();
private static Map<String, MCREditorMetadataValidator> VALIDATOR_MAP = getValidatorMap();
private static Map<String, Class<? extends MCRMetaInterface>> CLASS_MAP = new HashMap<>();
private Document input;
private MCRObjectID id;
private List<String> errorlog;
/**
* instantiate the validator with the editor input <code>jdom_in</code>.
*
* <code>id</code> will be set as the MCRObjectID for the resulting object
* that can be fetched with <code>generateValidMyCoReObject()</code>
*
* @param jdomIn
* editor input
*/
public MCREditorOutValidator(Document jdomIn, MCRObjectID id) throws JDOMException, IOException {
errorlog = new ArrayList<>();
input = jdomIn;
this.id = id;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("XML before validation:\n{}", new XMLOutputter(Format.getPrettyFormat()).outputString(input));
}
checkObject();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("XML after validation:\n{}", new XMLOutputter(Format.getPrettyFormat()).outputString(input));
}
}
private static Map<String, MCREditorMetadataValidator> getValidatorMap() {
Map<String, MCREditorMetadataValidator> map = new HashMap<>();
map.put(MCRMetaBoolean.class.getSimpleName(), getObjectCheckInstance(MCRMetaBoolean.class));
map.put(MCRMetaPersonName.class.getSimpleName(), getObjectCheckWithLangInstance(MCRMetaPersonName.class));
map.put(MCRMetaInstitutionName.class.getSimpleName(),
getObjectCheckWithLangInstance(MCRMetaInstitutionName.class));
map.put(MCRMetaAddress.class.getSimpleName(), new MCRMetaAdressCheck());
map.put(MCRMetaNumber.class.getSimpleName(), getObjectCheckWithLangNotEmptyInstance(MCRMetaNumber.class));
map.put(MCRMetaLinkID.class.getSimpleName(), getObjectCheckWithLinksInstance(MCRMetaLinkID.class));
map.put(MCRMetaEnrichedLinkID.class.getSimpleName(),
getObjectCheckWithLinksInstance(MCRMetaEnrichedLinkID.class));
map.put(MCRMetaDerivateLink.class.getSimpleName(), getObjectCheckWithLinksInstance(MCRMetaDerivateLink.class));
map.put(MCRMetaLink.class.getSimpleName(), getObjectCheckWithLinksInstance(MCRMetaLink.class));
map.put(MCRMetaISO8601Date.class.getSimpleName(),
getObjectCheckWithLangNotEmptyInstance(MCRMetaISO8601Date.class));
map.put(MCRMetaLangText.class.getSimpleName(), getObjectCheckWithLangNotEmptyInstance(MCRMetaLangText.class));
map.put(MCRMetaAccessRule.class.getSimpleName(), getObjectCheckInstance(MCRMetaAccessRule.class));
map.put(MCRMetaClassification.class.getSimpleName(), new MCRMetaClassificationCheck());
map.put(MCRMetaHistoryDate.class.getSimpleName(), new MCRMetaHistoryDateCheck());
Map<String, String> props = MCRConfiguration2.getPropertiesMap()
.entrySet()
.stream()
.filter(p -> p.getKey().startsWith(CONFIG_PREFIX + "class."))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
for (Entry<String, String> entry : props.entrySet()) {
try {
String className = entry.getKey();
className = className.substring(className.lastIndexOf('.') + 1);
LOGGER.info("Adding Validator {} for class {}", entry.getValue(), className);
@SuppressWarnings("unchecked")
Class<? extends MCREditorMetadataValidator> cl = (Class<? extends MCREditorMetadataValidator>) Class
.forName(entry.getValue());
map.put(className, cl.getDeclaredConstructor().newInstance());
} catch (Exception e) {
final String msg = "Cannot instantiate " + entry.getValue() + " as validator for class "
+ entry.getKey();
LOGGER.error(msg);
throw new MCRException(msg, e);
}
}
return map;
}
@SuppressWarnings("unchecked")
public static Class<? extends MCRMetaInterface> getClass(String mcrclass) throws ClassNotFoundException {
Class<? extends MCRMetaInterface> clazz = CLASS_MAP.get(mcrclass);
if (clazz == null) {
clazz = MCRClassTools.forName("org.mycore.datamodel.metadata." + mcrclass);
CLASS_MAP.put(mcrclass, clazz);
}
return clazz;
}
public static String checkMetaObject(Element datasubtag, Class<? extends MCRMetaInterface> metaClass,
boolean keepLang) {
if (!keepLang) {
datasubtag.removeAttribute("lang", XML_NAMESPACE);
}
MCRMetaInterface test = null;
try {
test = metaClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new MCRException("Could not instantiate " + metaClass.getCanonicalName());
}
test.setFromDOM(datasubtag);
test.validate();
return null;
}
public static String checkMetaObjectWithLang(Element datasubtag, Class<? extends MCRMetaInterface> metaClass) {
if (datasubtag.getAttribute("lang") != null) {
datasubtag.getAttribute("lang").setNamespace(XML_NAMESPACE);
LOGGER.warn("namespace add for xml:lang attribute in {}", datasubtag.getName());
}
return checkMetaObject(datasubtag, metaClass, true);
}
public static String checkMetaObjectWithLangNotEmpty(Element datasubtag,
Class<? extends MCRMetaInterface> metaClass) {
String text = datasubtag.getTextTrim();
if (text == null || text.length() == 0) {
return "Element " + datasubtag.getName() + " has no text.";
}
return checkMetaObjectWithLang(datasubtag, metaClass);
}
public static String checkMetaObjectWithLinks(Element datasubtag, Class<? extends MCRMetaInterface> metaClass) {
if (datasubtag.getAttributeValue("href") == null
&& datasubtag.getAttributeValue("href", XLINK_NAMESPACE) == null) {
return datasubtag.getName() + " has no href attribute defined";
}
if (datasubtag.getAttribute("xtype") != null) {
datasubtag.getAttribute("xtype").setNamespace(XLINK_NAMESPACE).setName("type");
} else if (datasubtag.getAttribute("type") != null
&& datasubtag.getAttribute("type", XLINK_NAMESPACE) == null) {
datasubtag.getAttribute("type").setNamespace(XLINK_NAMESPACE);
LOGGER.warn("namespace add for xlink:type attribute in {}", datasubtag.getName());
}
if (datasubtag.getAttribute("href") != null) {
datasubtag.getAttribute("href").setNamespace(XLINK_NAMESPACE);
LOGGER.warn("namespace add for xlink:href attribute in {}", datasubtag.getName());
}
if (datasubtag.getAttribute("title") != null) {
datasubtag.getAttribute("title").setNamespace(XLINK_NAMESPACE);
LOGGER.warn("namespace add for xlink:title attribute in {}", datasubtag.getName());
}
if (datasubtag.getAttribute("label") != null) {
datasubtag.getAttribute("label").setNamespace(XLINK_NAMESPACE);
LOGGER.warn("namespace add for xlink:label attribute in {}", datasubtag.getName());
}
return checkMetaObject(datasubtag, metaClass, false);
}
static MCREditorMetadataValidator getObjectCheckInstance(final Class<? extends MCRMetaInterface> clazz) {
return datasubtag -> MCREditorOutValidator.checkMetaObject(datasubtag, clazz, false);
}
static MCREditorMetadataValidator getObjectCheckWithLangInstance(final Class<? extends MCRMetaInterface> clazz) {
return datasubtag -> MCREditorOutValidator.checkMetaObjectWithLang(datasubtag, clazz);
}
static MCREditorMetadataValidator getObjectCheckWithLangNotEmptyInstance(
final Class<? extends MCRMetaInterface> clazz) {
return datasubtag -> MCREditorOutValidator.checkMetaObjectWithLangNotEmpty(datasubtag, clazz);
}
static MCREditorMetadataValidator getObjectCheckWithLinksInstance(final Class<? extends MCRMetaInterface> clazz) {
return datasubtag -> MCREditorOutValidator.checkMetaObjectWithLinks(datasubtag, clazz);
}
/**
* The method add a default ACL-block.
*/
public static void setDefaultDerivateACLs(Element service) {
// Read stylesheet and add user
InputStream aclxml = MCREditorOutValidator.class.getResourceAsStream("/editor_default_acls_derivate.xml");
if (aclxml == null) {
LOGGER.warn("Can't find default derivate ACL file editor_default_acls_derivate.xml.");
return;
}
try {
Document xml = SAX_BUILDER.build(aclxml);
Element acls = xml.getRootElement().getChild("servacls");
if (acls != null) {
service.addContent(acls.detach());
}
} catch (Exception e) {
LOGGER.warn("Error while parsing file editor_default_acls_derivate.xml.");
}
}
/**
* tries to generate a valid MCRObject as JDOM Document.
*
* @return MCRObject
*/
public Document generateValidMyCoReObject() throws JDOMException, IOException {
MCRObject obj;
// load the JDOM object
XPathFactory.instance()
.compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute())
.evaluate(input)
.forEach(Attribute::detach);
try {
byte[] xml = new MCRJDOMContent(input).asByteArray();
obj = new MCRObject(xml, true);
} catch (JDOMException e) {
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
LOGGER.warn("Failure while parsing document:\n{}", xout.outputString(input));
throw e;
}
// remove that, because its set in MCRMetadataManager, and we need the information (MCR-2603).
//Date curTime = new Date();
//obj.getService().setDate("modifydate", curTime);
// return the XML tree
input = obj.createXML();
return input;
}
/**
* returns a List of Error log entries
*
* @return log entries for the whole validation process
*/
public List<String> getErrorLog() {
return errorlog;
}
private void checkObject() throws JDOMException, IOException {
// add the namespaces (this is a workaround)
Element root = input.getRootElement();
root.addNamespaceDeclaration(XLINK_NAMESPACE);
root.addNamespaceDeclaration(XSI_NAMESPACE);
// set the schema
String mcrSchema = "datamodel-" + id.getTypeId() + ".xsd";
root.setAttribute("noNamespaceSchemaLocation", mcrSchema, XSI_NAMESPACE);
// check the label
String label = MCRUtils.filterTrimmedNotEmpty(root.getAttributeValue("label"))
.orElse(null);
if (label == null) {
root.setAttribute("label", id.toString());
}
// remove the path elements from the incoming
Element pathes = root.getChild("pathes");
if (pathes != null) {
root.removeChildren("pathes");
}
Element structure = root.getChild("structure");
if (structure == null) {
root.addContent(new Element("structure"));
} else {
checkObjectStructure(structure);
}
Element metadata = root.getChild("metadata");
checkObjectMetadata(metadata);
Element service = root.getChild("service");
checkObjectService(root, service);
}
private boolean checkMetaTags(Element datatag) {
String mcrclass = datatag.getAttributeValue("class");
List<Element> datataglist = datatag.getChildren();
Iterator<Element> datatagIt = datataglist.iterator();
while (datatagIt.hasNext()) {
Element datasubtag = datatagIt.next();
MCREditorMetadataValidator validator = VALIDATOR_MAP.get(mcrclass);
String returns = null;
if (validator != null) {
returns = validator.checkDataSubTag(datasubtag);
} else {
LOGGER.warn("Tag <{}> of type {} has no validator defined, fallback to default behaviour",
datatag.getName(), mcrclass);
// try to create MCRMetaInterface instance
try {
Class<? extends MCRMetaInterface> metaClass = getClass(mcrclass);
// just checks if class would validate this element
returns = checkMetaObject(datasubtag, metaClass, true);
} catch (ClassNotFoundException e) {
throw new MCRException("Failure while trying fallback. Class not found: " + mcrclass, e);
}
}
if (returns != null) {
datatagIt.remove();
final String msg = datatag.getName() + ": " + returns;
errorlog.add(msg);
}
}
return datatag.getChildren().size() != 0;
}
private void checkObjectService(Element root, Element service) throws JDOMException, IOException {
if (service == null) {
service = new Element("service");
root.addContent(service);
}
List<Element> servicelist = service.getChildren();
for (Element datatag : servicelist) {
checkMetaTags(datatag);
}
if (service.getChild("servacls") == null &&
MCRAccessManager.getAccessImpl() instanceof MCRRuleAccessInterface) {
Collection<String> li = MCRAccessManager.getPermissionsForID(id.toString());
if (li == null || li.isEmpty()) {
setDefaultObjectACLs(service);
}
}
}
/**
* The method add a default ACL-block.
*
*/
private void setDefaultObjectACLs(Element service) throws JDOMException, IOException {
if (!MCRConfiguration2.getBoolean("MCR.Access.AddObjectDefaultRule").orElse(true)) {
LOGGER.info("Adding object default acl rule is disabled.");
return;
}
String resourcetype = "/editor_default_acls_" + id.getTypeId() + ".xml";
String resourcebase = "/editor_default_acls_" + id.getBase() + ".xml";
// Read stylesheet and add user
InputStream aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcebase);
if (aclxml == null) {
aclxml = MCREditorOutValidator.class.getResourceAsStream(resourcetype);
if (aclxml == null) {
LOGGER.warn("Can't find default object ACL file {} or {}", resourcebase.substring(1),
resourcetype.substring(1));
String resource = "/editor_default_acls.xml"; // fallback
aclxml = MCREditorOutValidator.class.getResourceAsStream(resource);
if (aclxml == null) {
return;
}
}
}
Document xml = SAX_BUILDER.build(aclxml);
Element acls = xml.getRootElement().getChild("servacls");
if (acls == null) {
return;
}
for (Element acl : acls.getChildren()) {
Element condition = acl.getChild("condition");
if (condition == null) {
continue;
}
Element rootbool = condition.getChild("boolean");
if (rootbool == null) {
continue;
}
for (Element orbool : rootbool.getChildren("boolean")) {
for (Element firstcond : orbool.getChildren("condition")) {
if (firstcond == null) {
continue;
}
String value = firstcond.getAttributeValue("value");
if (value == null) {
continue;
}
if (value.equals("$CurrentUser")) {
String thisuser = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
firstcond.setAttribute("value", thisuser);
continue;
}
if (value.equals("$CurrentGroup")) {
throw new MCRException(
"The parameter $CurrentGroup in default ACLs is not supported as of MyCoRe 2014.06"
+ " because it is not supported in Servlet API 3.0");
}
int i = value.indexOf("$CurrentIP");
if (i != -1) {
String thisip = MCRSessionMgr.getCurrentSession().getCurrentIP();
firstcond.setAttribute("value",
value.substring(0, i) + thisip + value.substring(i + 10));
}
}
}
}
service.addContent(acls.detach());
}
private void checkObjectMetadata(Element metadata) {
if (metadata.getAttribute("lang") != null) {
metadata.getAttribute("lang").setNamespace(XML_NAMESPACE);
}
List<Element> metadatalist = metadata.getChildren();
Iterator<Element> metaIt = metadatalist.iterator();
while (metaIt.hasNext()) {
Element datatag = metaIt.next();
if (!checkMetaTags(datatag)) {
// e.g. datatag is empty
LOGGER.debug("Removing element :{}", datatag.getName());
metaIt.remove();
}
}
}
private void checkObjectStructure(Element structure) {
// e.g. datatag is empty
structure.getChildren().removeIf(datatag -> !checkMetaTags(datatag));
}
static class MCRMetaHistoryDateCheck implements MCREditorMetadataValidator {
public String checkDataSubTag(Element datasubtag) {
Element[] children = datasubtag.getChildren("text").toArray(Element[]::new);
int textCount = children.length;
for (Element child : children) {
String text = child.getTextTrim();
if (text == null || text.length() == 0) {
child.detach();
textCount--;
continue;
}
if (child.getAttribute("lang") != null) {
child.getAttribute("lang").setNamespace(XML_NAMESPACE);
LOGGER.warn("namespace add for xml:lang attribute in {}", datasubtag.getName());
}
}
if (textCount == 0) {
return "history date is empty";
}
return checkMetaObjectWithLang(datasubtag, MCRMetaHistoryDate.class);
}
}
static class MCRMetaClassificationCheck implements MCREditorMetadataValidator {
public String checkDataSubTag(Element datasubtag) {
String categid = datasubtag.getAttributeValue("categid");
if (categid == null) {
return "Attribute categid is empty";
}
return checkMetaObject(datasubtag, MCRMetaClassification.class, false);
}
}
static class MCRMetaAdressCheck implements MCREditorMetadataValidator {
public String checkDataSubTag(Element datasubtag) {
if (datasubtag.getChildren().size() == 0) {
return "adress is empty";
}
return checkMetaObjectWithLang(datasubtag, MCRMetaAddress.class);
}
}
static class MCRMetaPersonNameCheck implements MCREditorMetadataValidator {
public String checkDataSubTag(Element datasubtag) {
if (datasubtag.getChildren().size() == 0) {
return "person name is empty";
}
return checkMetaObjectWithLang(datasubtag, MCRMetaAddress.class);
}
}
}
| 23,157 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategory.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.datamodel.classifications2;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.SortedSet;
/**
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public interface MCRCategory {
/**
* @return true if this is a root category
*/
boolean isClassification();
/**
* @return true if this is not a root category
* @see #isClassification()
*/
boolean isCategory();
/**
* Tells if this category has subcategories.
*
* @return true if this category has subcategories
* @see #getChildren()
*/
boolean hasChildren();
/**
* Returns a list of subcategories.
*
* Implementors must never return <code>null</code> if no children are
* present. As this method may need a new call the underlaying persistence
* layer use hasChildren() if you just want to know if subcategories are
* present. Changes to the list may not affect the underlaying persistence
* layer.
*
* @return subcategories
* @see #hasChildren()
*/
List<MCRCategory> getChildren();
/**
* @return the id
*/
MCRCategoryID getId();
/**
* @param id
* the id to set
*/
void setId(MCRCategoryID id);
/**
* @return the labels
*/
SortedSet<MCRLabel> getLabels();
/**
* @return the label in the current language (if available), default language (if available), any language in
* MCR.Metadata.Languages(if available), any other language that does not start with x- or any other language
*/
Optional<MCRLabel> getCurrentLabel();
/**
* @return the label in the specified language (if available) or null
*/
Optional<MCRLabel> getLabel(String lang);
/**
* Returns the hierarchie level of this category.
*
* @return 0 if this is the root category
*/
int getLevel();
/**
* Returns root category (the classification).
*
* @return the root category
*/
MCRCategory getRoot();
/**
* Returns the parent element
*
* @return the categories parent or null if isClassification()==true or
* category currently not attached
*/
MCRCategory getParent();
/**
* Returns the URI associated with this category.
*
* @return the URI
*/
URI getURI();
/**
* @param uri
* the URI to set
*/
void setURI(URI uri);
}
| 3,242 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryID.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategoryID.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.datamodel.classifications2;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.mycore.common.MCRException;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonValue;
import jakarta.persistence.Access;
import jakarta.persistence.AccessType;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Transient;
/**
* The composite identifier of a MCRCategory. If <code>rootID == ID</code> the
* associated MCRCategory instance is a root category (a classification).
*
* @author Thomas Scheffler (yagee)
* @since 2.0
*/
@Embeddable
@Access(AccessType.FIELD)
@JsonFormat(shape = JsonFormat.Shape.STRING)
public class MCRCategoryID implements Serializable {
private static final long serialVersionUID = -5672923571406252855L;
public static final Pattern VALID_ID = Pattern.compile("[^:$\\{\\}]+");
public static final int ROOT_ID_LENGTH = 32;
public static final int CATEG_ID_LENGTH = 128;
@Basic
@Column(name = "ClassID", length = ROOT_ID_LENGTH, nullable = false, updatable = false)
private String rootID;
@Basic
@Column(name = "CategID", length = CATEG_ID_LENGTH, updatable = false)
private String id;
private MCRCategoryID() {
super();
}
/**
* @param rootID
* aka Classification ID
* @param id
* aka Category ID
*/
public MCRCategoryID(String rootID, String id) {
this();
setId(id);
setRootID(rootID);
}
public static MCRCategoryID rootID(String rootID) {
return new MCRCategoryID(rootID, "");
}
/**
* @param categoryId must be in format classificationId:categoryId
* @return the {@link MCRCategoryID} if any
*/
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static MCRCategoryID fromString(String categoryId) {
StringTokenizer tok = new StringTokenizer(categoryId, ":");
String rootId = tok.nextToken();
if (!tok.hasMoreTokens()) {
return rootID(rootId);
}
String categId = tok.nextToken();
if (tok.hasMoreTokens()) {
throw new IllegalArgumentException("CategoryId is ambiguous: " + categoryId);
}
return new MCRCategoryID(rootId, categId);
}
@Transient
public boolean isRootID() {
return id == null || id.isEmpty();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (id == null || id.isEmpty() ? 0 : id.hashCode());
result = prime * result + (rootID == null ? 0 : rootID.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MCRCategoryID other = (MCRCategoryID) obj;
if (id == null) {
if (other.id != null && !other.id.isEmpty()) {
return false;
}
} else if (!id.equals(other.id) && (!id.isEmpty() || other.id != null && other.id.length() >= 0)) {
return false;
}
if (rootID == null) {
return other.rootID == null;
} else {
return rootID.equals(other.rootID);
}
}
/**
* @deprecated Use {@link #getId()} instead.
*/
@Deprecated
@Transient
public String getID(){
return getId();
}
/**
* @return the ID
*/
public String getId() {
return id == null ? "" : id;
}
/**
* @param id
* the ID to set
*/
private void setId(String id) {
if (id != null && !id.isEmpty()) {
if (!VALID_ID.matcher(id).matches()) {
throw new MCRException("category ID '" + id + "' is invalid and does not match: " + VALID_ID);
}
if (id.length() > CATEG_ID_LENGTH) {
throw new MCRException(
new MessageFormat("category ID ''{0}'' is more than {1} characters long: {2}", Locale.ROOT)
.format(new Object[] { id, CATEG_ID_LENGTH, id.length() }));
}
}
this.id = id;
}
/**
* @param id
* the ID to check
* @return true, if the given String is a valid categoryID
*/
public static boolean isValid(String id) {
try {
MCRCategoryID.fromString(id);
return true;
} catch (Exception e) {
return false;
}
}
/**
* @return the rootID
*/
public String getRootID() {
return rootID;
}
/**
* @param rootID
* the rootID to set
*/
private void setRootID(String rootID) {
if (!VALID_ID.matcher(rootID).matches()) {
throw new MCRException(
new MessageFormat("classification ID ''{0}'' is invalid and does not match: {1}", Locale.ROOT)
.format(new Object[] { rootID, VALID_ID }));
}
if (rootID.length() > ROOT_ID_LENGTH) {
throw new MCRException(String.format(Locale.ENGLISH,
"classification ID ''%s'' is more than %d chracters long: %d", rootID, ROOT_ID_LENGTH,
rootID.length()));
}
this.rootID = rootID.intern();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
@JsonValue
public String toString() {
if (id == null || id.isEmpty()) {
return rootID;
}
return rootID + ':' + id;
}
}
| 6,913 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryDAOFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategoryDAOFactory.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.datamodel.classifications2;
import java.util.Objects;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImpl;
/**
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public class MCRCategoryDAOFactory {
/**
* Returns an instance of a MCRCategoryDAO implementator.
*/
public static MCRCategoryDAO getInstance() {
return Objects.requireNonNull(MCRCategoryDAOHolder.INSTANCE,
"MCRCategoryDAO cannot be NULL - There is a problem with the loading order of classes");
}
/**
* Sets a new category dao implementation for this factory. This could be useful for different test cases
* with mock objects.
*
* @param daoClass new dao class
*/
public static synchronized void set(Class<? extends MCRCategoryDAO> daoClass) throws ReflectiveOperationException {
MCRCategoryDAOHolder.INSTANCE = daoClass.getDeclaredConstructor().newInstance();
}
// encapsulate the INSTANCE in an inner static class to avoid issues with class loading order
// this is known as "Bill Pugh singleton"
private static class MCRCategoryDAOHolder {
private static MCRCategoryDAO INSTANCE = MCRConfiguration2.<MCRCategoryDAO>getInstanceOf("MCR.Category.DAO")
.orElseGet(MCRCategoryDAOImpl::new);
}
}
| 2,108 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryLink.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategoryLink.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.datamodel.classifications2;
/**
* Link between a category and an object.
*
* @author Matthias Eichner
*/
public interface MCRCategoryLink {
MCRCategory getCategory();
MCRCategLinkReference getObjectReference();
}
| 976 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryDAO.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategoryDAO.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.datamodel.classifications2;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
/**
* Interface of the Data Access Object for Classifications.
*
* @author Thomas Scheffler (yagee)
* @since 2.0
*/
public interface MCRCategoryDAO {
/**
* Adds a category as child of another category.
* When parentID is null a root category will be created.
*
* @param parentID
* ID of the parent category
* @param category
* Category (with children) to be added
* @return the parent category
*/
MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category);
/**
* Adds a category as child of another category.
* When parentID is null a root category will be created.
*
* @param parentID
* ID of the parent category
* @param category
* Category (with children) to be added
* @param position
* insert position
* @return the parent category
*/
MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category, int position);
/**
* Deletes a category with all child categories.
*
* @param id
* ID of Category to be removed
*/
void deleteCategory(MCRCategoryID id);
/**
* Tells if a given category exists.
*
* @param id
* ID of Category
* @return true if category is present
*/
boolean exist(MCRCategoryID id);
/**
* Retrieve all Categories tagged by a specific label in a specific lang.
*
* @param baseID
* base Category which subtree is searched for the label.
* @param lang
* language attribute of the label
* @param text
* text of the label
* @return a collection of MCRCategories with matching labels
*/
List<MCRCategory> getCategoriesByLabel(MCRCategoryID baseID, String lang, String text);
/**
* Retrieve all Categories tagged by a specific label in a specific lang.
*
* @param lang
* language attribute of the label
* @param text
* text of the label
* @return a collection of MCRCategories with matching labels
*/
List<MCRCategory> getCategoriesByLabel(String lang, String text);
/**
* Returns MCRCategory with this id and childLevel levels of subcategories.
*
* @param id
* ID of category
* @param childLevel
* how many levels of subcategories should be retrieved (-1 for
* infinitive)
* @return MCRCategory with <code>id</code> or null if the category cannot be found
*/
MCRCategory getCategory(MCRCategoryID id, int childLevel);
/**
* Returns the list of child categories for the specified category.
*
* @param id
* ID of category
* @return list of child category
*/
List<MCRCategory> getChildren(MCRCategoryID id);
/**
* Returns the parent of the given category and its parent and so on. The
* last element in the list is the root category (the classification)
*
* @param id
* ID of Category
* @return list of parents
*/
List<MCRCategory> getParents(MCRCategoryID id);
/**
* Returns all category IDs that do not have a parent category.
*
* @return list of category IDs
*/
List<MCRCategoryID> getRootCategoryIDs();
/**
* Returns all categories that do not have a parent category.
*
* @return list of category IDs
*/
List<MCRCategory> getRootCategories();
/**
* Returns the root Category with ancestor axis of the specified category
* and childLevel levels of subcategories.
*
* You can say it is the combination of getParents(MCRCategoryID) and
* getCategory(MCRCategoryID, int).
*
* @param baseID
* Category with relative level set to "0".
* @param childLevel
* amount of subcategory levels rooted at baseID category
* @return the root Category (Classification)
* @see #getParents(MCRCategoryID)
* @see #getCategory(MCRCategoryID, int)
*/
MCRCategory getRootCategory(MCRCategoryID baseID, int childLevel);
/**
* Tells if a given category contains subcategories.
*
* @param id
* ID of Category
* @return true if subcategories are present
*/
boolean hasChildren(MCRCategoryID id);
/**
* Moves a Category from one subtree in a classification to a new parent.
*
* All subcategories remain children of the moved category.
*
* @param id
* ID of the Category which should be moved
* @param newParentID
* ID of the new parent
*/
void moveCategory(MCRCategoryID id, MCRCategoryID newParentID);
/**
* Moves a Category from one subtree in a classification to a new parent as
* the <code>index</code>th child.
*
* @param id
* ID of the Category which should be moved
* @param newParentID
* ID of the new parent
* @param index
* insert category at index in the list of children
*/
void moveCategory(MCRCategoryID id, MCRCategoryID newParentID, int index);
/**
* Removes a label from a Category.
*
* @param id
* ID of the category
* @param lang
* which language should be removed?
* @return category where the label was removed
*/
MCRCategory removeLabel(MCRCategoryID id, String lang);
/**
* Replaces a <code>MCRCategory</code> by a new version of the same
* category.
*
* This replacment includes all subcategories and labels. So former
* subcategories and labels not present in <code>newCategory</code> will
* be removed while new ones will be inserted.
*
* If you can use the other methods defined by this interface as they ought
* to be more optimized.
*
* @param newCategory
* new version of MCRCategory
* @throws IllegalArgumentException
* if old version of MCRCategory does not exist
* @return collection of replaced categories
*/
Collection<? extends MCRCategory> replaceCategory(MCRCategory newCategory)
throws IllegalArgumentException;
/**
* Sets or updates a label from a Category.
*
* @param id
* ID of the category
* @param label
* to be set or updated
* @return category where the label was set
*/
MCRCategory setLabel(MCRCategoryID id, MCRLabel label);
/**
* Sets a new set of labels from a Category.
*
* @param id
* ID of the category
* @param labels
* to be set
* @return category where the labels was set
*/
MCRCategory setLabels(MCRCategoryID id, SortedSet<MCRLabel> labels);
/**
* Sets or updates the URI from a Category.
*
* @param id
* ID of the category
* @param uri
* to be set or updated
* @return category where the uri was set
*/
MCRCategory setURI(MCRCategoryID id, URI uri);
/**
* allows to determine when the last change was made to the categories.
* @return either the last change time or the init time of the DAO class
*/
long getLastModified();
/**
* Gets the last modified timestamp for the given root id. If there is no timestamp at the moment -1 is returned.
*
* @param root ID of root category
*
* @return the last modified timestamp (if any) or -1
*/
long getLastModified(String root);
}
| 8,610 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategLinkService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategLinkService.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.datamodel.classifications2;
import java.util.Collection;
import java.util.Map;
/**
*
* @author Thomas Scheffler (yagee)
* @since 2.0
*/
public interface MCRCategLinkService {
/**
* Checks if a categories id refered by objects.
*
* @param category
* a subtree rooted at a MCRCategory for which links should be counted
* @return true if the classification is used
*/
Map<MCRCategoryID, Boolean> hasLinks(MCRCategory category);
/**
* Checks if the category with the given id is liked with an object
*
* @return
* true if is linked otherwise false
*/
boolean hasLink(MCRCategory classif);
/**
* Counts links to a collection of categories.
*
* @param category
* a subtree rooted at a MCRCategory for which links should be counted
* @param childrenOnly
* if only direct children of category should be queried (query may be more optimized)
* @return a Map with MCRCategoryID as key and the number of links as value
*/
Map<MCRCategoryID, Number> countLinks(MCRCategory category, boolean childrenOnly);
/**
* Counts links to a collection of categories.
*
* @param category
* a subtree rooted at a MCRCategory for which links should be counted
* @param type
* restrict links that refer to object of this type
* @param childrenOnly
* if only direct children of category should be queried (query may be more optimized)
* @return a Map with MCRCategoryID as key and the number of links as value
*/
Map<MCRCategoryID, Number> countLinksForType(MCRCategory category, String type, boolean childrenOnly);
/**
* Delete all links that refer to the given {@link MCRCategLinkReference}.
*
* @param id
* an Object ID
* @see #deleteLinks(Collection)
*/
void deleteLink(MCRCategLinkReference id);
/**
* Delete all links that refer to the given collection of category links.
*
* @param ids
* a collection of {@link MCRCategLinkReference}
* @see #deleteLink(MCRCategLinkReference)
*/
void deleteLinks(Collection<MCRCategLinkReference> ids);
/**
* Returns a list of linked Object IDs.
*
* @param id
* ID of the category
* @return Collection of Object IDs, empty Collection when no links exist
*/
Collection<String> getLinksFromCategory(MCRCategoryID id);
/**
* Checks if a given reference is in a specific category.
*
* @param reference
* reference, e.g. to a MCRObject
* @return true if the reference is in the category
*/
boolean isInCategory(MCRCategLinkReference reference, MCRCategoryID id);
/**
* Returns a list of linked Object IDs restricted by the specified type.
*
* @param id
* ID of the category
* @param type
* restrict links that refer to object of this type
* @return Collection of Object IDs
*/
Collection<String> getLinksFromCategoryForType(MCRCategoryID id, String type);
/**
* Returns a list of linked categories.
*
* @param reference
* reference, e.g. to a MCRObject
* @return list of MCRCategoryID of linked categories
*/
Collection<MCRCategoryID> getLinksFromReference(MCRCategLinkReference reference);
/**
* Return a collection of all category link references for the given type
*/
Collection<MCRCategLinkReference> getReferences(String type);
/**
* Return a collection of all link types.
*
*/
Collection<String> getTypes();
/**
* Returns a collection of all links for the given type.
*
*/
Collection<MCRCategoryLink> getLinks(String type);
/**
* Add links between categories and Objects.
*
* Implementors must assure that ancestor (parent) axis categories are
* implicit linked by this method.
*
* @param objectReference
* reference to a Object
* @param categories
* a collection of categoryIDs to be linked to
* @see #countLinks(MCRCategory, boolean)
* @see #countLinksForType(MCRCategory, String, boolean)
*/
void setLinks(MCRCategLinkReference objectReference, Collection<MCRCategoryID> categories);
}
| 5,201 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUnmappedCategoryRemover.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRUnmappedCategoryRemover.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.datamodel.classifications2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Removes Categories which can not be mapped from a other classification.
*/
public class MCRUnmappedCategoryRemover {
private static final Logger LOGGER = LogManager.getLogger();
private final String classificationID;
// contains mappings like mir_genres:article -> marcgt:article
private HashMap<MCRCategoryID, MCRCategoryID> toFromMapping;
private ArrayList<MCRCategoryID> filtered;
/**
* @param classificationID of the classification to filter
*/
public MCRUnmappedCategoryRemover(String classificationID) {
this.classificationID = classificationID;
this.initializeMapping();
}
public void filter() {
filtered = new ArrayList<>();
final MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance();
final MCRCategory category = dao
.getCategory(MCRCategoryID.fromString(classificationID), -1);
collectRemovableCategories(category);
filtered.forEach(categoryToDelete -> {
LOGGER.info("Delete Category {}", categoryToDelete);
dao.deleteCategory(categoryToDelete);
});
}
private boolean collectRemovableCategories(MCRCategory category) {
final MCRCategoryID categoryID = category.getId();
LOGGER.info("Filter Category: {}", categoryID);
boolean hasMapping = toFromMapping.containsKey(categoryID);
final List<MCRCategory> children = category.getChildren();
for (MCRCategory child : children) {
hasMapping = collectRemovableCategories(child) || hasMapping;
}
if (!hasMapping) {
filtered.add(categoryID);
// remove children from deleted list so we have only one delete operation for this category
children.stream()
.map(MCRCategory::getId)
.forEach(filtered::remove);
}
return hasMapping;
}
private void initializeMapping() {
toFromMapping = new HashMap<>();
final MCRCategoryDAO dao = MCRCategoryDAOFactory
.getInstance();
final List<MCRCategory> rootCategories = dao
.getRootCategories()
.stream()
.map(category -> dao.getRootCategory(category.getId(), -1))
.collect(Collectors.toList());
for (MCRCategory rootCategory : rootCategories) {
initializeMapping(rootCategory);
}
}
private void initializeMapping(MCRCategory category) {
final Optional<MCRLabel> mapping = category.getLabel("x-mapping");
LOGGER.info("Find mappings for category: {}", category.getId());
mapping.ifPresent(label -> {
final String[] mappingTargets = label.text.split(" ");
for (String mappingTarget : mappingTargets) {
final String[] kv = mappingTarget.split(":");
String clazz = kv[0];
if (classificationID.equals(clazz)) {
LOGGER.info("Found mapping from {} to {}", category.getId(), mappingTarget);
toFromMapping.put(MCRCategoryID.fromString(mappingTarget), category.getId());
}
}
});
category.getChildren().forEach(this::initializeMapping);
}
}
| 4,263 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategLinkServiceFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategLinkServiceFactory.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.datamodel.classifications2;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl;
/**
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public class MCRCategLinkServiceFactory {
private static MCRCategLinkService instance = MCRConfiguration2
.<MCRCategLinkService>getInstanceOf("MCR.Category.LinkService")
.orElseGet(MCRCategLinkServiceImpl::new);
/**
* Returns an instance of a MCRCategoryDAO implementator.
*/
public static MCRCategLinkService getInstance() {
return instance;
}
}
| 1,363 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLabel.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRLabel.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.datamodel.classifications2;
import java.io.Serializable;
import java.util.Locale;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* This class represents a label of a MCRCategory.
*
* @author Thomas Scheffler (yagee)
* @since 2.0
*/
@XmlRootElement(
name = "label")
@XmlAccessorType(XmlAccessType.FIELD)
@Embeddable
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
public class MCRLabel implements Cloneable, Serializable, Comparable<MCRLabel> {
private static final long serialVersionUID = -843799854929361194L;
@XmlAttribute(
namespace = "http://www.w3.org/XML/1998/namespace")
String lang;
@XmlAttribute
String text;
@XmlAttribute
String description;
public MCRLabel() {
}
/**
* @param lang see {@link #setLang(String)}
* @param text see {@link #setText(String)}
* @param description see {@link #setDescription(String)}
* @throws NullPointerException if lang or text is null
* @throws IllegalArgumentException if lang or text is invalid
*/
public MCRLabel(String lang, String text, String description)
throws NullPointerException, IllegalArgumentException {
super();
setLang(lang);
setText(text);
setDescription(description);
}
@Column
public String getLang() {
return lang;
}
/**
* @param lang language tag in RFC4646 form
* @throws NullPointerException if lang is null
* @throws IllegalArgumentException if lang is somehow invalid (empty or 'und')
*/
public void setLang(String lang) {
Objects.requireNonNull(lang, "'lang' of label may not be null.");
if (lang.trim().isEmpty()) {
throw new IllegalArgumentException("'lang' of label may not be empty.");
}
Locale locale = Locale.forLanguageTag(lang);
String languageTag = locale.toLanguageTag();
if (Objects.equals(languageTag, "und")) {
throw new IllegalArgumentException("'lang' of label is not valid language tag (RFC4646):" + lang);
}
this.lang = languageTag;
}
@Column(length = 4096)
public String getText() {
return text;
}
/**
* @param text required attribute of label
* @throws NullPointerException if text is null
* @throws IllegalArgumentException if text is empty
*/
public void setText(String text) {
Objects.requireNonNull(text, "'text' of label('" + lang + "') may not be null.");
if (text.trim().isEmpty()) {
throw new IllegalArgumentException("'text' of label('" + lang + "') may not be empty.");
}
this.text = text;
}
@Column(length = 4096)
public String getDescription() {
if (description == null) {
return "";
}
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public MCRLabel clone() {
MCRLabel clone = null;
try {
clone = (MCRLabel) super.clone();
} catch (CloneNotSupportedException ce) {
// Can not happen
}
return clone;
}
@Override
public String toString() {
return getLang() + '(' + getText() + ')';
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getDescription().hashCode();
result = prime * result + (lang == null ? 0 : lang.hashCode());
result = prime * result + (text == null ? 0 : text.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MCRLabel other = (MCRLabel) obj;
if (lang == null) {
if (other.lang != null) {
return false;
}
} else if (!lang.equals(other.lang)) {
return false;
}
if (text == null) {
if (other.text != null) {
return false;
}
} else if (!text.equals(other.text)) {
return false;
}
return getDescription().equals(other.getDescription());
}
@Override
public int compareTo(MCRLabel other) {
if (other == null) {
return 1;
}
//both are not null
if (this.getLang() == other.getLang()) { // this intentionally uses == to allow for both null
return 0;
}
if (this.getLang() == null) {
return -1;
}
if (other.getLang() == null) {
return 1;
}
return this.getLang().compareTo(other.getLang());
}
}
| 6,127 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategLinkReference.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRCategLinkReference.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.datamodel.classifications2;
import java.io.Serializable;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
/**
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
@Embeddable
public class MCRCategLinkReference implements Serializable {
private static final long serialVersionUID = -6457722746147666860L;
@Basic
private String objectID;
@Basic
@Column(name = "objectType", length = 128)
private String type;
public MCRCategLinkReference() {
}
public MCRCategLinkReference(MCRObjectID objectID) {
this(objectID.toString(), objectID.getTypeId());
}
public MCRCategLinkReference(String objectID, String type) {
setObjectID(objectID);
setType(type);
}
public MCRCategLinkReference(MCRPath path) {
this('/' + path.subpathComplete().toString(), path.getOwner());
}
public String getObjectID() {
return objectID;
}
public void setObjectID(String objectID) {
this.objectID = objectID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (objectID == null ? 0 : objectID.hashCode());
result = prime * result + (type == null ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MCRCategLinkReference other = (MCRCategLinkReference) obj;
if (objectID == null) {
if (other.objectID != null) {
return false;
}
} else if (!objectID.equals(other.objectID)) {
return false;
}
if (type == null) {
return other.type == null;
} else {
return type.equals(other.type);
}
}
@Override
public String toString() {
return "MCRCategLinkReference [objectID=" + objectID + ", type=" + type + "]";
}
}
| 3,150 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClassificationUpdateType.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/MCRClassificationUpdateType.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.datamodel.classifications2;
/**
* Update Types used in classification event handlers.
*
* @author Robert Stephan
*
*/
public enum MCRClassificationUpdateType {
REPLACE, MOVE;
/**
* Key to use in event properties
*/
public static final String KEY = "type";
}
| 1,034 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryMapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/mapper/MCRCategoryMapper.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.datamodel.classifications2.mapper;
import java.util.List;
import org.mycore.common.MCRException;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
/**
* @author Frank Lützenkirchen
*/
public class MCRCategoryMapper extends MCRCategoryMapperBase {
private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance();
protected String getMappingRule(MCRCategoryID categoryID) {
MCRCategory category = DAO.getCategory(categoryID, 0);
//"x-mapper" was used in previous versions of mycore
MCRLabel label = category.getLabel("x-mapping").orElse(category.getLabel("x-mapper")
.orElseThrow(() -> new MCRException("Category " + category + " does not hav a label for 'x-mapping'.")));
return label.getText();
}
protected void addParentsToList(MCRCategoryID childID, List<MCRCategoryID> list) {
for (MCRCategory parent : DAO.getParents(childID)) {
if (parent.isCategory()) {
list.add(parent.getId());
}
}
}
}
| 2,035 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/mapper/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Automatically maps classification categories that have been set manually
* in object metadata to other classification categories */
package org.mycore.datamodel.classifications2.mapper;
| 923 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryMapperBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/mapper/MCRCategoryMapperBase.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.datamodel.classifications2.mapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.mycore.datamodel.classifications2.MCRCategoryID;
/**
* @author Frank Lützenkirchen
*/
public abstract class MCRCategoryMapperBase {
public Set<MCRCategoryID> map(Collection<MCRCategoryID> input) {
SortedSet<MCRCategoryID> output = new TreeSet<>();
for (MCRCategoryID categoryID : input) {
Set<MCRCategoryID> mapped = collectMappings(categoryID);
output.addAll(mapped);
}
return output;
}
private Set<MCRCategoryID> collectMappings(MCRCategoryID categoryID) {
Set<MCRCategoryID> mapped = new TreeSet<>();
for (MCRCategoryID parent : resolveParentOrSelf(categoryID)) {
for (MCRCategoryID mapping : getMappings(parent)) {
if (!alreadyContainsCategoryOfSameClassification(mapped, mapping)) {
mapped.add(mapping);
}
}
}
return mapped;
}
private boolean alreadyContainsCategoryOfSameClassification(Collection<MCRCategoryID> collection,
MCRCategoryID candidate) {
String classificationID = candidate.getRootID();
return collection.stream().map(MCRCategoryID::getRootID).anyMatch(classificationID::equals);
}
private List<MCRCategoryID> getMappings(MCRCategoryID categoryID) {
String mappingRule = getMappingRule(categoryID);
String[] mappings = mappingRule.split("\\s+");
return Arrays.stream(mappings).map(this::buildMappedID).collect(Collectors.toList());
}
private MCRCategoryID buildMappedID(String mapping) {
int pos = mapping.indexOf(":");
String mappedClassificationID = mapping.substring(0, pos);
String mappedCategoryID = mapping.substring(pos + 1);
return new MCRCategoryID(mappedClassificationID, mappedCategoryID);
}
private List<MCRCategoryID> resolveParentOrSelf(MCRCategoryID childID) {
List<MCRCategoryID> parentOrSelf = new ArrayList<>();
parentOrSelf.add(childID);
addParentsToList(childID, parentOrSelf);
return parentOrSelf;
}
protected abstract void addParentsToList(MCRCategoryID childID, List<MCRCategoryID> list);
protected abstract String getMappingRule(MCRCategoryID categoryID);
}
| 3,261 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryChildList.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryChildList.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.datamodel.classifications2.impl;
import java.util.ArrayList;
import java.util.Collection;
import org.mycore.datamodel.classifications2.MCRCategory;
class MCRCategoryChildList extends ArrayList<MCRCategory> {
private static final long serialVersionUID = 5844882597476033744L;
private MCRCategory root;
private MCRCategory thisCategory;
MCRCategoryChildList(MCRCategory root, MCRCategory thisCategory) {
super();
this.root = root;
this.thisCategory = thisCategory;
}
@Override
public void add(int index, MCRCategory element) {
super.add(index, MCRCategoryImpl.wrapCategory(element, thisCategory, root));
}
@Override
public boolean add(MCRCategory e) {
return super.add(MCRCategoryImpl.wrapCategory(e, thisCategory, root));
}
@Override
public boolean addAll(Collection<? extends MCRCategory> c) {
return super.addAll(MCRCategoryImpl.wrapCategories(c, thisCategory, root));
}
@Override
public boolean addAll(int index, Collection<? extends MCRCategory> c) {
return super.addAll(index, MCRCategoryImpl.wrapCategories(c, thisCategory, root));
}
@Override
public void clear() {
for (int i = 0; i < size(); i++) {
removeAncestorReferences(get(i));
}
super.clear();
}
@Override
public MCRCategory remove(int index) {
MCRCategory category = super.remove(index);
removeAncestorReferences(category);
return category;
}
@Override
public boolean remove(Object o) {
boolean removed = super.remove(o);
if (removed) {
removeAncestorReferences((MCRCategory) o);
}
return removed;
}
private void removeAncestorReferences(MCRCategory category) {
if (category instanceof MCRAbstractCategoryImpl catImpl) {
catImpl.parent = null;
catImpl.root = null;
}
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
for (int i = fromIndex; i < toIndex; i++) {
removeAncestorReferences(get(i));
}
super.removeRange(fromIndex, toIndex);
}
@Override
public MCRCategory set(int index, MCRCategory element) {
MCRCategory category = super.set(index, element);
if (category != element) {
removeAncestorReferences(category);
}
return category;
}
}
| 3,203 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryImpl.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.datamodel.classifications2.impl;
import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.annotations.SortNatural;
import org.mycore.backend.jpa.MCRURIConverter;
import org.mycore.common.MCRException;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import jakarta.persistence.Access;
import jakarta.persistence.AccessType;
import jakarta.persistence.CascadeType;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
import jakarta.persistence.UniqueConstraint;
/**
*
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
@Entity
@Table(name = "MCRCategory",
indexes = {
@Index(columnList = "ClassID, leftValue, rightValue", name = "ClassLeftRight"),
@Index(columnList = "leftValue", name = "ClassesRoot")
},
uniqueConstraints = {
@UniqueConstraint(columnNames = { "ClassID", "CategID" }, name = "ClassCategUnique"),
@UniqueConstraint(columnNames = { "ClassID", "leftValue" }, name = "ClassLeftUnique"),
@UniqueConstraint(columnNames = { "ClassID", "rightValue" }, name = "ClassRightUnique") })
@NamedQueries({
@NamedQuery(name = "MCRCategory.updateLeft",
query = "UPDATE MCRCategoryImpl cat SET cat.left=cat.left+:increment WHERE "
+ "cat.id.rootID= :classID AND cat.left >= :left"),
@NamedQuery(name = "MCRCategory.updateRight",
query = "UPDATE MCRCategoryImpl cat SET cat.right=cat.right+:increment WHERE "
+ "cat.id.rootID= :classID AND cat.right >= :left"),
@NamedQuery(name = "MCRCategory.commonAncestor",
query = "FROM MCRCategoryImpl as cat WHERE "
+ "cat.id.rootID=:rootID AND cat.left < :left AND cat.right > :right "
+ "ORDER BY cat.left DESC"),
@NamedQuery(name = "MCRCategory.byNaturalId",
query = "FROM MCRCategoryImpl as cat WHERE "
+ "cat.id.rootID=:classID and (cat.id.id=:categID OR cat.id.id IS NULL AND :categID IS NULL)"),
@NamedQuery(name = "MCRCategory.byLabelInClass",
query = "FROM MCRCategoryImpl as cat "
+ "INNER JOIN cat.labels as label "
+ " WHERE cat.id.rootID=:rootID AND "
+ " cat.left BETWEEN :left and :right AND "
+ " label.lang=:lang AND "
+ " label.text=:text"),
@NamedQuery(name = "MCRCategory.byLabel",
query = "FROM MCRCategoryImpl as cat "
+ " INNER JOIN cat.labels as label "
+ " WHERE label.lang=:lang AND "
+ " label.text=:text"),
@NamedQuery(name = "MCRCategory.prefetchClassQuery",
query = MCRCategoryDTO.SELECT
+ " WHERE cat.id.rootID=:classID ORDER BY cat.left"),
@NamedQuery(name = "MCRCategory.prefetchClassLevelQuery",
query = MCRCategoryDTO.SELECT
+ " WHERE cat.id.rootID=:classID AND cat.level <= :endlevel ORDER BY cat.left"),
@NamedQuery(name = "MCRCategory.prefetchCategQuery",
query = MCRCategoryDTO.SELECT
+ " WHERE cat.id.rootID=:classID AND (cat.left BETWEEN :left AND :right OR cat.left=0) ORDER BY cat.left"),
@NamedQuery(name = "MCRCategory.prefetchCategLevelQuery",
query = MCRCategoryDTO.SELECT
+ " WHERE cat.id.rootID=:classID AND (cat.left BETWEEN :left AND :right OR cat.left=0) AND "
+ "cat.level <= :endlevel ORDER BY cat.left"),
@NamedQuery(name = "MCRCategory.leftRightLevelQuery",
query = MCRCategoryDTO.LRL_SELECT
+ " WHERE cat.id=:categID "),
@NamedQuery(name = "MCRCategory.parentQuery",
query = MCRCategoryDTO.SELECT
+ " WHERE cat.id.rootID=:classID AND (cat.left < :left AND cat.right > :right OR cat.id.id=:categID) "
+ "ORDER BY cat.left"),
@NamedQuery(name = "MCRCategory.rootCategs",
query = MCRCategoryDTO.SELECT
+ " WHERE cat.left = 0 ORDER BY cat.id.rootID"),
@NamedQuery(name = "MCRCategory.rootIds", query = "SELECT cat.id FROM MCRCategoryImpl cat WHERE cat.left = 0"),
@NamedQuery(name = "MCRCategory.childCount",
query = "SELECT CAST(count(*) AS integer) FROM MCRCategoryImpl children WHERE "
+ "children.parent.internalID=(SELECT cat.internalID FROM MCRCategoryImpl cat WHERE "
+ "cat.id.rootID=:classID and (cat.id.id=:categID OR cat.id.id IS NULL AND :categID IS NULL))"),
})
@Access(AccessType.PROPERTY)
public class MCRCategoryImpl extends MCRAbstractCategoryImpl implements Serializable {
private static final long serialVersionUID = -7431317191711000317L;
private static Logger LOGGER = LogManager.getLogger(MCRCategoryImpl.class);
private int left, right, internalID;
int level;
public MCRCategoryImpl() {
}
//Mapping definition
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getInternalID() {
return internalID;
}
@Column(name = "leftValue")
public int getLeft() {
return left;
}
@Column(name = "rightValue")
public int getRight() {
return right;
}
@Column
public int getLevel() {
return level;
}
@Transient
int getPositionInParent() {
LOGGER.debug("getposition called for {}", getId());
if (parent == null) {
LOGGER.debug("getposition called with no parent set.");
return -1;
}
try {
int position = getParent().getChildren().indexOf(this);
if (position == -1) {
// sometimes indexOf does not find this instance so we need to
// check for the ID here to
position = getPositionInParentByID();
}
return position;
} catch (RuntimeException e) {
LOGGER.error("Cannot use parent.getChildren() here", e);
throw e;
}
}
// @NaturalId
@Override
@Embedded
public MCRCategoryID getId() {
return super.getId();
}
@Override
@OneToMany(targetEntity = MCRCategoryImpl.class,
cascade = {
CascadeType.ALL },
mappedBy = "parent")
@OrderColumn(name = "positionInParent")
@Access(AccessType.FIELD)
public List<MCRCategory> getChildren() {
return super.getChildren();
}
@Override
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "MCRCategoryLabels",
joinColumns = @JoinColumn(name = "category"),
uniqueConstraints = {
@UniqueConstraint(columnNames = { "category", "lang" }) })
@SortNatural
public SortedSet<MCRLabel> getLabels() {
return super.getLabels();
}
@Override
@Column
@Convert(converter = MCRURIConverter.class)
public URI getURI() {
return super.getURI();
}
@ManyToOne(targetEntity = MCRCategoryImpl.class)
@JoinColumn(name = "parentID")
@Access(AccessType.FIELD)
public MCRCategory getParent() {
return super.getParent();
}
//End of Mapping
@Override
public boolean hasChildren() {
//if children is initialized and has objects use it and don't depend on db values
if (children != null && children.size() > 0) {
return true;
}
if (right != left) {
return right - left > 1;
}
return super.hasChildren();
}
@Transient
private int getPositionInParentByID() {
int position = 0;
for (MCRCategory sibling : parent.getChildren()) {
if (getId().equals(sibling.getId())) {
return position;
}
position++;
}
if (LOGGER.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("List of children of parent: ");
sb.append(parent.getId()).append('\n');
for (MCRCategory sibling : parent.getChildren()) {
sb.append(sibling.getId()).append('\n');
}
LOGGER.debug(sb.toString());
}
throw new IndexOutOfBoundsException(
"Position -1 is not valid: " + getId() + " parent:" + parent.getId() + " children: " + parent
.getChildren()
.stream()
.map(MCRCategory::getId)
.map(MCRCategoryID::getId)
.collect(Collectors.joining(", ")));
}
/**
* @param children
* the children to set
*/
public void setChildren(List<MCRCategory> children) {
LOGGER.debug("Set children called for {}list'{}': {}", getId(), children.getClass().getName(), children);
childGuard.write(() -> setChildrenUnlocked(children));
}
@Override
protected void setChildrenUnlocked(List<MCRCategory> children) {
MCRCategoryChildList newChildren = new MCRCategoryChildList(root, this);
newChildren.addAll(children);
this.children = newChildren;
}
/**
* @param labels
* the labels to set
*/
public void setLabels(SortedSet<MCRLabel> labels) {
this.labels = labels;
}
/**
* @param left
* the left to set
*/
public void setLeft(int left) {
this.left = left;
}
public void setLevel(int level) {
this.level = level;
}
/**
* @param right
* the right to set
*/
public void setRight(int right) {
this.right = right;
}
/*
* (non-Javadoc)
*
* @see org.mycore.datamodel.classifications2.MCRCategory#setRoot(org.mycore.datamodel.classifications2.MCRClassificationObject)
*/
public void setRoot(MCRCategory root) {
this.root = root;
if (children != null) {
setChildren(children);
}
}
static Collection<MCRCategoryImpl> wrapCategories(Collection<? extends MCRCategory> categories, MCRCategory parent,
MCRCategory root) {
List<MCRCategoryImpl> list = new ArrayList<>(categories.size());
for (MCRCategory category : categories) {
list.add(wrapCategory(category, parent, root));
}
return list;
}
static MCRCategoryImpl wrapCategory(MCRCategory category, MCRCategory parent, MCRCategory root) {
if (category.getParent() != null && category.getParent() != parent) {
throw new MCRException("MCRCategory is already attached to a different parent.");
}
if (category instanceof MCRCategoryImpl catImpl) {
// don't use setParent() as it call add() from ChildList
catImpl.parent = parent;
if (root == null) {
root = catImpl;
}
catImpl.setRoot(root);
if (parent != null) {
catImpl.level = parent.getLevel() + 1;
} else if (category.isCategory()) {
LOGGER.warn("Something went wrong here, category has no parent and is no root category: {}",
category.getId());
}
// copy children to temporary list
List<MCRCategory> children = new ArrayList<>(catImpl.getChildren().size());
children.addAll(catImpl.getChildren());
// remove old children
catImpl.getChildren().clear();
// add new wrapped children
catImpl.getChildren().addAll(children);
return catImpl;
}
LOGGER.debug("wrap Category: {}", category.getId());
MCRCategoryImpl catImpl = new MCRCategoryImpl();
catImpl.setId(category.getId());
catImpl.labels = category.getLabels();
catImpl.parent = parent;
if (root == null) {
root = catImpl;
}
catImpl.setRoot(root);
catImpl.level = parent.getLevel() + 1;
catImpl.children = new ArrayList<>(category.getChildren().size());
catImpl.getChildren().addAll(category.getChildren());
return catImpl;
}
@Transient
MCRCategoryImpl getLeftSiblingOrOfAncestor() {
int index = getPositionInParent();
MCRCategoryImpl parent = (MCRCategoryImpl) getParent();
if (index > 0) {
// has left sibling
return (MCRCategoryImpl) parent.getChildren().get(index - 1);
}
if (parent.getParent() != null) {
// recursive call to get left sibling of parent
return parent.getLeftSiblingOrOfAncestor();
}
return parent;// is root
}
@Transient
MCRCategoryImpl getLeftSiblingOrParent() {
int index = getPositionInParent();
MCRCategoryImpl parent = (MCRCategoryImpl) getParent();
if (index == 0) {
return parent;
}
return (MCRCategoryImpl) parent.getChildren().get(index - 1);
}
@Transient
MCRCategoryImpl getRightSiblingOrOfAncestor() {
int index = getPositionInParent();
MCRCategoryImpl parent = (MCRCategoryImpl) getParent();
if (index + 1 < parent.getChildren().size()) {
// has right sibling
return (MCRCategoryImpl) parent.getChildren().get(index + 1);
}
if (parent.getParent() != null) {
// recursive call to get right sibling of parent
return parent.getRightSiblingOrOfAncestor();
}
return parent;// is root
}
@Transient
MCRCategoryImpl getRightSiblingOrParent() {
int index = getPositionInParent();
MCRCategoryImpl parent = (MCRCategoryImpl) getParent();
if (index + 1 == parent.getChildren().size()) {
return parent;
}
// get Element at index that would be at index+1 after insert
return (MCRCategoryImpl) parent.getChildren().get(index + 1);
}
/**
* calculates left and right value throug the subtree rooted at
* <code>co</code>.
*
* @param leftStart
* this.left will be set to this value
* @param levelStart
* this.getLevel() will return this value
* @return this.right
*/
public int calculateLeftRightAndLevel(int leftStart, int levelStart) {
int curValue = leftStart;
final int nextLevel = levelStart + 1;
setLeft(leftStart);
setLevel(levelStart);
for (MCRCategory child : getChildren()) {
LOGGER.debug(child.getId());
curValue = ((MCRCategoryImpl) child).calculateLeftRightAndLevel(++curValue, nextLevel);
}
setRight(++curValue);
return curValue;
}
/**
* @param internalID
* the internalID to set
*/
public void setInternalID(int internalID) {
this.internalID = internalID;
}
public void setRootID(String rootID) {
if (getId() == null) {
setId(MCRCategoryID.rootID(rootID));
} else if (!getId().getRootID().equals(rootID)) {
setId(new MCRCategoryID(rootID, getId().getId()));
}
}
public void setCategID(String categID) {
if (getId() == null) {
setId(new MCRCategoryID(null, categID));
} else if (!getId().getId().equals(categID)) {
setId(new MCRCategoryID(getId().getRootID(), categID));
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + internalID;
result = prime * result + left;
result = prime * result + level;
result = prime * result + right;
result = prime * result + getId().hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MCRCategoryImpl other = (MCRCategoryImpl) obj;
if (internalID != other.internalID) {
return false;
}
if (left != other.left) {
return false;
}
if (level != other.level) {
return false;
}
return right == other.right;
}
@Transient
public String getRootID() {
return getId().getRootID();
}
}
| 17,968 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryDAOImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryDAOImpl.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.datamodel.classifications2.impl;
import java.net.URI;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.SortedSet;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
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.MCRPersistenceException;
import org.mycore.common.MCRStreamUtils;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.FlushModeType;
import jakarta.persistence.NoResultException;
import jakarta.persistence.Query;
import jakarta.persistence.TypedQuery;
/**
*
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public class MCRCategoryDAOImpl implements MCRCategoryDAO {
private static final int LEVEL_START_VALUE = 0;
private static final int LEFT_START_VALUE = 0;
private static long LAST_MODIFIED = System.currentTimeMillis();
private static final Logger LOGGER = LogManager.getLogger();
private static final String NAMED_QUERY_NAMESPACE = "MCRCategory.";
private static HashMap<String, Long> LAST_MODIFIED_MAP = new HashMap<>();
@Override
public MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category) {
int position = -1;
if (category instanceof MCRCategoryImpl catImpl) {
position = catImpl.getPositionInParent();
}
return addCategory(parentID, category, position);
}
@Override
public MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category, int position) {
if (exist(category.getId())) {
throw new MCRException("Cannot add category. A category with ID " + category.getId() + " already exists");
}
return withoutFlush(MCREntityManagerProvider.getCurrentEntityManager(), false, entityManager -> {
//we do direct DB manipulation, so flush and clear session first
entityManager.flush();
entityManager.clear();
int leftStart = LEFT_START_VALUE;
int levelStart = LEVEL_START_VALUE;
MCRCategoryImpl parent = null;
if (parentID != null) {
parent = getByNaturalID(entityManager, parentID);
levelStart = parent.getLevel() + 1;
leftStart = parent.getRight();
if (position > parent.getChildren().size()) {
throw new IndexOutOfBoundsException(
"Cannot add category as child #" + position + ", when there are only "
+ parent.getChildren().size() + " children.");
}
}
LOGGER.debug("Calculating LEFT,RIGHT and LEVEL attributes...");
final MCRCategoryImpl wrapCategory = MCRCategoryImpl.wrapCategory(category, parent,
parent == null ? category.getRoot() : parent.getRoot());
wrapCategory.calculateLeftRightAndLevel(leftStart, levelStart);
// always add +1 for the current node
int nodes = 1 + (wrapCategory.getRight() - wrapCategory.getLeft()) / 2;
LOGGER.debug("Calculating LEFT,RIGHT and LEVEL attributes. Done! Nodes: {}", nodes);
if (parentID != null) {
final int increment = nodes * 2;
int parentLeft = parent.getLeft();
updateLeftRightValue(entityManager, parentID.getRootID(), leftStart, increment);
entityManager.flush();
if (position < 0) {
parent.getChildren().add(category);
} else {
parent.getChildren().add(position, category);
}
parent.calculateLeftRightAndLevel(Integer.MAX_VALUE / 2, parent.getLevel());
entityManager.flush();
parent.calculateLeftRightAndLevel(parentLeft, parent.getLevel());
}
entityManager.persist(category);
LOGGER.info("Category {} saved.", category.getId());
updateTimeStamp();
updateLastModified(category.getRoot().getId().toString());
return parent;
});
}
@Override
public void deleteCategory(MCRCategoryID id) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
LOGGER.debug("Will get: {}", id);
MCRCategoryImpl category = getByNaturalID(entityManager, id);
try {
entityManager.refresh(category); //for MCR-1863
} catch (EntityNotFoundException e) {
//required since hibernate 5.3 if category is deleted within same transaction.
//junit: testLicenses()
}
if (category == null) {
throw new MCRPersistenceException("Category " + id + " was not found. Delete aborted.");
}
LOGGER.debug("Will delete: {}", category.getId());
MCRCategory parent = category.parent;
category.detachFromParent();
entityManager.remove(category);
if (parent != null) {
entityManager.flush();
LOGGER.debug("Left: {} Right: {}", category.getLeft(), category.getRight());
// always add +1 for the currentNode
int nodes = 1 + (category.getRight() - category.getLeft()) / 2;
final int increment = nodes * -2;
// decrement left and right values by nodes
updateLeftRightValue(entityManager, category.getRootID(), category.getLeft(), increment);
}
updateTimeStamp();
updateLastModified(category.getRootID());
}
/*
* (non-Javadoc)
*
* @see org.mycore.datamodel.classifications2.MCRCategoryDAO#exist(org.mycore.datamodel.classifications2.MCRCategoryID)
*/
@Override
public boolean exist(MCRCategoryID id) {
return getLeftRightLevelValues(MCREntityManagerProvider.getCurrentEntityManager(), id) != null;
}
@Override
public List<MCRCategory> getCategoriesByLabel(final String lang, final String text) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
return cast(entityManager.createNamedQuery(NAMED_QUERY_NAMESPACE + "byLabel", MCRCategoryImpl.class)
.setParameter("lang", lang)
.setParameter("text", text)
.getResultList());
}
@Override
public List<MCRCategory> getCategoriesByLabel(MCRCategoryID baseID, String lang, String text) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRCategoryDTO leftRight = getLeftRightLevelValues(entityManager, baseID);
return cast(entityManager
.createNamedQuery(NAMED_QUERY_NAMESPACE + "byLabelInClass", MCRCategoryImpl.class)
.setParameter("rootID", baseID.getRootID())
.setParameter("left", leftRight.leftValue)
.setParameter("right", leftRight.rightValue)
.setParameter("lang", lang)
.setParameter("text", text)
.getResultList());
}
@Override
@SuppressWarnings("unchecked")
public MCRCategory getCategory(MCRCategoryID id, int childLevel) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
final boolean fetchAllChildren = childLevel < 0;
Query q;
if (id.isRootID()) {
q = entityManager.createNamedQuery(NAMED_QUERY_NAMESPACE
+ (fetchAllChildren ? "prefetchClassQuery" : "prefetchClassLevelQuery"));
if (!fetchAllChildren) {
q.setParameter("endlevel", childLevel);
}
q.setParameter("classID", id.getRootID());
} else {
//normal category
MCRCategoryDTO leftRightLevel = getLeftRightLevelValues(entityManager, id);
if (leftRightLevel == null) {
return null;
}
q = entityManager.createNamedQuery(NAMED_QUERY_NAMESPACE
+ (fetchAllChildren ? "prefetchCategQuery" : "prefetchCategLevelQuery"));
if (!fetchAllChildren) {
q.setParameter("endlevel", leftRightLevel.level + childLevel);
}
q.setParameter("classID", id.getRootID());
q.setParameter("left", leftRightLevel.leftValue);
q.setParameter("right", leftRightLevel.rightValue);
}
List<MCRCategoryDTO> result = q.getResultList();
if (result.isEmpty()) {
LOGGER.warn("Could not load category: {}", id);
return null;
}
return buildCategoryFromPrefetchedList(result, id);
}
/*
* (non-Javadoc)
*
* @see org.mycore.datamodel.classifications2.MCRClassificationService#getChildren(org.mycore.datamodel.classifications2.MCRCategoryID)
*/
@Override
public List<MCRCategory> getChildren(MCRCategoryID cid) {
LOGGER.debug("Get children of category: {}", cid);
return Optional.ofNullable(cid)
.map(id -> getCategory(id, 1))
.map(MCRCategory::getChildren)
.map(l -> l
.parallelStream()
.collect(Collectors.toList()) //temporary copy for detachFromParent
.parallelStream()
.map(MCRCategoryImpl.class::cast)
.peek(MCRCategoryImpl::detachFromParent)
.map(MCRCategory.class::cast)
.collect(Collectors.toList()))
.orElse(new MCRCategoryChildList(null, null));
}
@Override
public List<MCRCategory> getParents(MCRCategoryID id) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRCategoryDTO leftRight = getLeftRightLevelValues(entityManager, id);
if (leftRight == null) {
return null;
}
Query parentQuery = entityManager
.createNamedQuery(NAMED_QUERY_NAMESPACE + "parentQuery")
.setParameter("classID", id.getRootID())
.setParameter("categID", id.getId())
.setParameter("left", leftRight.leftValue)
.setParameter("right", leftRight.rightValue);
@SuppressWarnings("unchecked")
List<MCRCategoryDTO> resultList = parentQuery.getResultList();
MCRCategory category = buildCategoryFromPrefetchedList(resultList, id);
List<MCRCategory> parents = new ArrayList<>();
while (category.getParent() != null) {
category = category.getParent();
parents.add(category);
}
return parents;
}
@Override
@SuppressWarnings("unchecked")
public List<MCRCategoryID> getRootCategoryIDs() {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
return entityManager.createNamedQuery(NAMED_QUERY_NAMESPACE + "rootIds").getResultList();
}
@Override
@SuppressWarnings("unchecked")
public List<MCRCategory> getRootCategories() {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
List<MCRCategoryDTO> resultList = entityManager.createNamedQuery(NAMED_QUERY_NAMESPACE + "rootCategs")
.getResultList();
BiConsumer<List<MCRCategory>, MCRCategoryImpl> merge = (l, c) -> {
MCRCategoryImpl last = (MCRCategoryImpl) l.get(l.size() - 1);
if (last.getInternalID() != c.getInternalID()) {
l.add(c);
} else {
last.getLabels().addAll(c.getLabels());
}
};
return resultList.parallelStream()
.map(c -> c.merge(null))
.collect(Collector.of(ArrayList::new,
(ArrayList<MCRCategory> l, MCRCategoryImpl c) -> {
if (l.isEmpty()) {
l.add(c);
} else {
merge.accept(l, c);
}
}, (l, r) -> {
if (l.isEmpty()) {
return r;
}
if (r.isEmpty()) {
return l;
}
MCRCategoryImpl first = (MCRCategoryImpl) r.get(0);
merge.accept(l, first);
l.addAll(r.subList(1, r.size()));
return l;
}));
}
@Override
public MCRCategory getRootCategory(MCRCategoryID baseID, int childLevel) {
return Optional.ofNullable(getCategory(baseID, childLevel))
.map(c -> {
if (baseID.isRootID()) {
return c;
}
List<MCRCategory> parents = getParents(baseID);
MCRCategory parent = parents.get(0);
c.getChildren()
.stream()
.collect(Collectors.toList())
.stream()
.map(MCRCategoryImpl.class::cast)
.peek(MCRCategoryImpl::detachFromParent)
.forEachOrdered(parent.getChildren()::add);
// return root node
return parents.get(parents.size() - 1);
})
.orElse(null);
}
/*
* (non-Javadoc)
*
* @see org.mycore.datamodel.classifications2.MCRClassificationService#hasChildren(org.mycore.datamodel.classifications2.MCRCategoryID)
*/
@Override
public boolean hasChildren(MCRCategoryID cid) {
// SELECT * FROM MCRCATEGORY WHERE PARENTID=(SELECT INTERNALID FROM
// MCRCATEGORY WHERE rootID=cid.getRootID() and ID...);
return getNumberOfChildren(MCREntityManagerProvider.getCurrentEntityManager(), cid) > 0;
}
@Override
public void moveCategory(MCRCategoryID id, MCRCategoryID newParentID) {
int index = getNumberOfChildren(MCREntityManagerProvider.getCurrentEntityManager(), newParentID);
moveCategory(id, newParentID, index);
}
private MCRCategoryImpl getCommonAncestor(EntityManager entityManager, MCRCategoryImpl node1,
MCRCategoryImpl node2) {
if (!node1.getRootID().equals(node2.getRootID())) {
return null;
}
if (node1.getLeft() == 0) {
return node1;
}
if (node2.getLeft() == 0) {
return node2;
}
int left = Math.min(node1.getLeft(), node2.getLeft());
int right = Math.max(node1.getRight(), node2.getRight());
Query q = entityManager.createNamedQuery(NAMED_QUERY_NAMESPACE + "commonAncestor")
.setMaxResults(1)
.setParameter("left", left)
.setParameter("right", right)
.setParameter("rootID", node1.getRootID());
return getSingleResult(q);
}
@Override
public void moveCategory(MCRCategoryID id, MCRCategoryID newParentID, int index) {
withoutFlush(MCREntityManagerProvider.getCurrentEntityManager(), true, e -> {
MCRCategoryImpl subTree = getByNaturalID(MCREntityManagerProvider.getCurrentEntityManager(), id);
MCRCategoryImpl oldParent = (MCRCategoryImpl) subTree.getParent();
MCRCategoryImpl newParent = getByNaturalID(MCREntityManagerProvider.getCurrentEntityManager(), newParentID);
MCRCategoryImpl commonAncestor = getCommonAncestor(MCREntityManagerProvider.getCurrentEntityManager(),
oldParent, newParent);
subTree.detachFromParent();
LOGGER.debug("Add subtree to new Parent at index: {}", index);
newParent.getChildren().add(index, subTree);
subTree.parent = newParent;
MCREntityManagerProvider.getCurrentEntityManager().flush();
int left = commonAncestor.getLeft();
commonAncestor.calculateLeftRightAndLevel(Integer.MAX_VALUE / 2, commonAncestor.getLevel());
e.flush();
commonAncestor.calculateLeftRightAndLevel(left, commonAncestor.getLevel());
updateTimeStamp();
updateLastModified(id.getRootID());
});
}
@Override
public MCRCategory removeLabel(MCRCategoryID id, String lang) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRCategoryImpl category = getByNaturalID(entityManager, id);
category.getLabel(lang).ifPresent(oldLabel -> {
category.getLabels().remove(oldLabel);
updateTimeStamp();
updateLastModified(category.getRootID());
});
return category;
}
@Override
public Collection<MCRCategoryImpl> replaceCategory(MCRCategory newCategory) throws IllegalArgumentException {
if (!exist(newCategory.getId())) {
throw new IllegalArgumentException(
"MCRCategory can not be replaced. MCRCategoryID '" + newCategory.getId() + "' is unknown.");
}
return withoutFlush(MCREntityManagerProvider.getCurrentEntityManager(), true, em -> {
MCRCategoryImpl oldCategory = getByNaturalID(MCREntityManagerProvider.getCurrentEntityManager(),
newCategory.getId());
int oldLevel = oldCategory.getLevel();
int oldLeft = oldCategory.getLeft();
// old Map with all Categories referenced by ID
Map<MCRCategoryID, MCRCategoryImpl> oldMap = toMap(oldCategory);
final MCRCategoryImpl copyDeepImpl = copyDeep(newCategory, -1);
MCRCategoryImpl newCategoryImpl = MCRCategoryImpl.wrapCategory(copyDeepImpl, oldCategory.getParent(),
oldCategory.getRoot());
// new Map with all Categories referenced by ID
Map<MCRCategoryID, MCRCategoryImpl> newMap = toMap(newCategoryImpl);
//remove;
oldMap
.entrySet()
.stream()
.filter(c -> !newMap.containsKey(c.getKey()))
.map(Map.Entry::getValue)
.peek(MCRCategoryDAOImpl::remove)
.forEach(c -> LOGGER.info("remove category: {}", c.getId()));
oldMap.clear();
oldMap.putAll(toMap(oldCategory));
//sync labels/uris;
MCRStreamUtils
.flatten(oldCategory, MCRCategory::getChildren, Collection::stream)
.filter(c -> newMap.containsKey(c.getId()))
.map(MCRCategoryImpl.class::cast)
.map(c -> new AbstractMap.SimpleEntry<>(c, newMap.get(c.getId())))
// key: category of old version, value: category of new version
.peek(e -> syncLabels(e.getValue(), e.getKey())) //sync from new to old version
.forEach(e -> e.getKey().setURI(e.getValue().getURI()));
//detach all categories, we will rebuild tree structure later
oldMap
.values()
.stream()
.filter(c -> c.getInternalID() != oldCategory.getInternalID()) //do not detach root of subtree
.forEach(MCRCategoryImpl::detachFromParent);
//rebuild
MCRStreamUtils
.flatten(newCategoryImpl, MCRCategory::getChildren, Collection::stream)
.forEachOrdered(c -> {
MCRCategoryImpl oldC = oldMap.get(c.getId());
oldC.setChildren(
c
.getChildren()
.stream()
.map(cc -> {
//to categories of stored version or copy from new version
MCRCategoryImpl oldCC = oldMap.get(cc.getId());
if (oldCC == null) {
oldCC = new MCRCategoryImpl();
oldCC.setId(cc.getId());
oldCC.setURI(cc.getURI());
oldCC.getLabels().addAll(cc.getLabels());
oldMap.put(oldCC.getId(), oldCC);
}
return oldCC;
})
.collect(Collectors.toList()));
});
oldCategory.calculateLeftRightAndLevel(Integer.MAX_VALUE / 2, oldLevel);
em.flush();
oldCategory.calculateLeftRightAndLevel(oldLeft, oldLevel);
updateTimeStamp();
updateLastModified(newCategory.getId().getRootID());
return newMap.values();
});
}
private static Map<MCRCategoryID, MCRCategoryImpl> toMap(MCRCategoryImpl oldCategory) {
return MCRStreamUtils
.flatten(oldCategory, MCRCategory::getChildren, Collection::stream)
.collect(Collectors.toMap(MCRCategory::getId, MCRCategoryImpl.class::cast));
}
private static void remove(MCRCategoryImpl category) {
if (category.hasChildren()) {
int parentPos = category.getPositionInParent();
MCRCategoryImpl parent = (MCRCategoryImpl) category.getParent();
@SuppressWarnings("unchecked")
ArrayList<MCRCategoryImpl> copy = new ArrayList(category.children);
copy.forEach(MCRCategoryImpl::detachFromParent);
parent.children.addAll(parentPos, copy);
copy.forEach(c -> c.parent = parent); //fixes MCR-1963
}
category.detachFromParent();
MCREntityManagerProvider.getCurrentEntityManager().remove(category);
}
@Override
public MCRCategory setLabel(MCRCategoryID id, MCRLabel label) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRCategoryImpl category = getByNaturalID(entityManager, id);
category.getLabel(label.getLang()).ifPresent(category.getLabels()::remove);
category.getLabels().add(label);
updateTimeStamp();
updateLastModified(category.getRootID());
return category;
}
@Override
public MCRCategory setLabels(MCRCategoryID id, SortedSet<MCRLabel> labels) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRCategoryImpl category = getByNaturalID(entityManager, id);
category.setLabels(labels);
updateTimeStamp();
updateLastModified(category.getRootID());
return category;
}
@Override
public MCRCategory setURI(MCRCategoryID id, URI uri) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRCategoryImpl category = getByNaturalID(entityManager, id);
category.setURI(uri);
updateTimeStamp();
updateLastModified(category.getRootID());
return category;
}
public void repairLeftRightValue(String classID) {
final MCRCategoryID rootID = MCRCategoryID.rootID(classID);
withoutFlush(MCREntityManagerProvider.getCurrentEntityManager(), true, entityManager -> {
MCRCategoryImpl classification = MCRCategoryDAOImpl.getByNaturalID(entityManager, rootID);
classification.calculateLeftRightAndLevel(Integer.MAX_VALUE / 2, LEVEL_START_VALUE);
entityManager.flush();
classification.calculateLeftRightAndLevel(LEFT_START_VALUE, LEVEL_START_VALUE);
});
}
@Override
public long getLastModified() {
return LAST_MODIFIED;
}
private static void updateTimeStamp() {
LAST_MODIFIED = System.currentTimeMillis();
}
private static MCRCategoryImpl buildCategoryFromPrefetchedList(List<MCRCategoryDTO> list, MCRCategoryID returnID) {
LOGGER.debug(() -> "using prefetched list: " + list);
MCRCategoryImpl predecessor = null;
for (MCRCategoryDTO entry : list) {
predecessor = entry.merge(predecessor);
}
return MCRStreamUtils.flatten(predecessor.getRoot(), MCRCategory::getChildren, Collection::parallelStream)
.filter(c -> c.getId().equals(returnID))
.findFirst()
.map(MCRCategoryImpl.class::cast)
.orElseThrow(() -> new MCRException("Could not find " + returnID + " in database result."));
}
private static MCRCategoryImpl copyDeep(MCRCategory category, int level) {
if (category == null) {
return null;
}
MCRCategoryImpl newCateg = new MCRCategoryImpl();
int childAmount;
try {
childAmount = level != 0 ? category.getChildren().size() : 0;
} catch (RuntimeException e) {
LOGGER.error("Cannot get children size for category: {}", category.getId(), e);
throw e;
}
newCateg.setChildren(new ArrayList<>(childAmount));
newCateg.setId(category.getId());
newCateg.setLabels(category.getLabels());
newCateg.setRoot(category.getRoot());
newCateg.setURI(category.getURI());
newCateg.setLevel(category.getLevel());
if (category instanceof MCRCategoryImpl catImpl) {
//to allow optimized hasChildren() to work without db query
newCateg.setLeft(catImpl.getLeft());
newCateg.setRight(catImpl.getRight());
newCateg.setInternalID(catImpl.getInternalID());
}
if (childAmount > 0) {
for (MCRCategory child : category.getChildren()) {
newCateg.getChildren().add(copyDeep(child, level - 1));
}
}
return newCateg;
}
/**
* returns database backed MCRCategoryImpl
*
* every change to the returned MCRCategory is reflected in the database.
*/
public static MCRCategoryImpl getByNaturalID(EntityManager entityManager, MCRCategoryID id) {
TypedQuery<MCRCategoryImpl> naturalIDQuery = entityManager
.createNamedQuery(NAMED_QUERY_NAMESPACE + "byNaturalId", MCRCategoryImpl.class)
.setParameter("classID", id.getRootID())
.setParameter("categID", id.getId());
return getSingleResult(naturalIDQuery);
}
private static void syncLabels(MCRCategoryImpl source, MCRCategoryImpl target) {
for (MCRLabel newLabel : source.getLabels()) {
Optional<MCRLabel> label = target.getLabel(newLabel.getLang());
if (!label.isPresent()) {
// copy new label
target.getLabels().add(newLabel);
}
label.ifPresent(oldLabel -> {
if (!oldLabel.getText().equals(newLabel.getText())) {
oldLabel.setText(newLabel.getText());
}
if (!oldLabel.getDescription().equals(newLabel.getDescription())) {
oldLabel.setDescription(newLabel.getDescription());
}
});
}
// remove labels that are not present in new version
target.getLabels().removeIf(mcrLabel -> !source.getLabel(mcrLabel.getLang()).isPresent());
}
private static MCRCategoryDTO getLeftRightLevelValues(EntityManager entityManager, MCRCategoryID id) {
return getSingleResult(entityManager
.createNamedQuery(NAMED_QUERY_NAMESPACE + "leftRightLevelQuery")
.setParameter("categID", id));
}
private static int getNumberOfChildren(EntityManager entityManager, MCRCategoryID id) {
return getSingleResult(entityManager
.createNamedQuery(NAMED_QUERY_NAMESPACE + "childCount")
.setParameter("classID", id.getRootID())
.setParameter("categID", id.getId()));
}
private static void updateLeftRightValue(EntityManager entityManager, String classID, int left,
final int increment) {
withoutFlush(entityManager, true, e -> {
LOGGER.debug("LEFT AND RIGHT values need updates. Left={}, increment by: {}", left, increment);
Query leftQuery = e
.createNamedQuery(NAMED_QUERY_NAMESPACE + "updateLeft")
.setParameter("left", left)
.setParameter("increment", increment)
.setParameter("classID", classID);
int leftChanges = leftQuery.executeUpdate();
Query rightQuery = e
.createNamedQuery(NAMED_QUERY_NAMESPACE + "updateRight")
.setParameter("left", left)
.setParameter("increment", increment)
.setParameter("classID", classID);
int rightChanges = rightQuery.executeUpdate();
LOGGER.debug("Updated {} left and {} right values.", leftChanges, rightChanges);
});
}
/**
* Method updates the last modified timestamp, for the given root id.
*
*/
protected synchronized void updateLastModified(String root) {
LAST_MODIFIED_MAP.put(root, System.currentTimeMillis());
}
/**
* Gets the timestamp for the given root id. If there is not timestamp at the moment -1 is returned.
*
* @return the last modified timestamp (if any) or -1
*/
@Override
public long getLastModified(String root) {
Long long1 = LAST_MODIFIED_MAP.get(root);
if (long1 != null) {
return long1;
}
return -1;
}
@SuppressWarnings("unchecked")
private static <T> T getSingleResult(Query query) {
try {
return (T) query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
private static List<MCRCategory> cast(List<MCRCategoryImpl> list) {
@SuppressWarnings({ "unchecked", "rawtypes" })
List<MCRCategory> temp = (List) list;
return temp;
}
private static <T> T withoutFlush(EntityManager entityManager, boolean flushAtEnd,
Function<EntityManager, T> task) {
FlushModeType fm = entityManager.getFlushMode();
entityManager.setFlushMode(FlushModeType.COMMIT);
try {
T result = task.apply(entityManager);
if (flushAtEnd) {
entityManager.flush();
}
return result;
} catch (RuntimeException e) {
throw e;
} finally {
entityManager.setFlushMode(fm);
}
}
private static void withoutFlush(EntityManager entityManager, boolean flushAtEnd, Consumer<EntityManager> task) {
withoutFlush(entityManager, flushAtEnd, e -> {
task.accept(e);
return null;
});
}
}
| 31,762 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREventedCategoryDAOImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCREventedCategoryDAOImpl.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.datamodel.classifications2.impl;
import java.net.URI;
import java.util.Collection;
import java.util.SortedSet;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventManager;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRClassificationUpdateType;
import org.mycore.datamodel.classifications2.MCRLabel;
/**
* Category DAO Implementation with Event Handlers
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCREventedCategoryDAOImpl extends MCRCategoryDAOImpl {
@Override
public MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category, int position) {
MCRCategory rv = super.addCategory(parentID, category, position);
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.CREATE);
evt.put(MCREvent.CLASS_KEY, category);
if (parentID != null) {
evt.put("parent", super.getCategory(parentID, -1));
}
MCREventManager.instance().handleEvent(evt);
return rv;
}
@Override
public void deleteCategory(MCRCategoryID id) {
MCRCategory category = super.getCategory(id, -1);
if (category == null) {
throw new MCRPersistenceException("Category " + id + " was not found. Delete aborted.");
}
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.DELETE);
evt.put(MCREvent.CLASS_KEY, category);
MCREventManager.instance().handleEvent(evt, MCREventManager.BACKWARD);
super.deleteCategory(id);
}
@Override
public void moveCategory(MCRCategoryID id, MCRCategoryID newParentID, int index) {
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.UPDATE);
evt.put(MCREvent.CLASS_KEY, super.getCategory(id, -1));
evt.put("parent", super.getCategory(newParentID, -1));
// "type" is used for specifying a special update operation
evt.put(MCRClassificationUpdateType.KEY, MCRClassificationUpdateType.MOVE);
MCREventManager.instance().handleEvent(evt);
super.moveCategory(id, newParentID, index);
}
@Override
public MCRCategory removeLabel(MCRCategoryID id, String lang) {
MCRCategory rv = super.removeLabel(id, lang);
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.UPDATE);
evt.put(MCREvent.CLASS_KEY, super.getCategory(id, -1));
MCREventManager.instance().handleEvent(evt);
return rv;
}
@Override
public Collection<MCRCategoryImpl> replaceCategory(MCRCategory newCategory) throws IllegalArgumentException {
Collection<MCRCategoryImpl> rv = super.replaceCategory(newCategory);
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.UPDATE);
evt.put(MCREvent.CLASS_KEY, newCategory);
evt.put(MCRClassificationUpdateType.KEY, MCRClassificationUpdateType.REPLACE);
evt.put("replaced", rv);
MCREventManager.instance().handleEvent(evt);
return rv;
}
@Override
public MCRCategory setLabel(MCRCategoryID id, MCRLabel label) {
MCRCategory rv = super.setLabel(id, label);
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.UPDATE);
evt.put(MCREvent.CLASS_KEY, super.getCategory(id, -1));
MCREventManager.instance().handleEvent(evt);
return rv;
}
@Override
public MCRCategory setLabels(MCRCategoryID id, SortedSet<MCRLabel> labels) {
MCRCategory rv = super.setLabels(id, labels);
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.UPDATE);
evt.put(MCREvent.CLASS_KEY, super.getCategory(id, -1));
MCREventManager.instance().handleEvent(evt);
return rv;
}
@Override
public MCRCategory setURI(MCRCategoryID id, URI uri) {
MCRCategory rv = super.setURI(id, uri);
MCREvent evt = new MCREvent(MCREvent.ObjectType.CLASS, MCREvent.EventType.UPDATE);
evt.put(MCREvent.CLASS_KEY, super.getCategory(id, -1));
MCREventManager.instance().handleEvent(evt);
return rv;
}
}
| 5,053 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractCategoryImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRAbstractCategoryImpl.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.datamodel.classifications2.impl;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.util.concurrent.MCRReadWriteGuard;
/**
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public abstract class MCRAbstractCategoryImpl implements MCRCategory {
protected final MCRReadWriteGuard childGuard = new MCRReadWriteGuard();
protected MCRCategory root;
protected MCRCategory parent;
protected SortedSet<MCRLabel> labels;
protected List<MCRCategory> children;
private MCRCategoryID id;
private URI uri;
private String defaultLang;
private static HashSet<String> LANGUAGES;
static {
LANGUAGES = new HashSet<>(MCRConfiguration2.getString("MCR.Metadata.Languages")
.map(MCRConfiguration2::splitValue)
.map(s -> s.collect(Collectors.toList()))
.orElseGet(Collections::emptyList));
}
public MCRAbstractCategoryImpl() {
super();
if (defaultLang == null) {
defaultLang = MCRConfiguration2.getString("MCR.Metadata.DefaultLang").orElse(MCRConstants.DEFAULT_LANG);
}
labels = new TreeSet<>();
}
public List<MCRCategory> getChildren() {
return childGuard.lazyLoad(this::childrenNotHere, this::initChildren, () -> children);
}
private boolean childrenNotHere() {
return children == null;
}
private void initChildren() {
setChildrenUnlocked(MCRCategoryDAOFactory.getInstance().getChildren(id));
}
protected abstract void setChildrenUnlocked(List<MCRCategory> children);
public MCRCategoryID getId() {
return id;
}
public void setId(MCRCategoryID id) {
this.id = id;
}
public SortedSet<MCRLabel> getLabels() {
return labels;
}
public MCRCategory getRoot() {
if (getId().isRootID()) {
return this;
}
if (root == null && getParent() != null) {
root = getParent().getRoot();
}
return root;
}
public URI getURI() {
return uri;
}
public void setURI(URI uri) {
this.uri = uri;
}
public boolean hasChildren() {
return childGuard
.read(() -> Optional.ofNullable(children).map(c -> !c.isEmpty()))
.orElse(MCRCategoryDAOFactory.getInstance().hasChildren(id));
}
public final boolean isCategory() {
return !isClassification();
}
public final boolean isClassification() {
return getId().isRootID();
}
public MCRCategory getParent() {
return parent;
}
public void setParent(MCRCategory parent) {
if (this.parent == parent) {
return;
}
detachFromParent();
this.parent = parent;
if (parent != null) {
parent.getChildren().add(this);
}
}
void detachFromParent() {
if (parent != null) {
// remove this from current parent
parent.getChildren().remove(this);
parent = null;
}
}
public Optional<MCRLabel> getCurrentLabel() {
if (labels.isEmpty()) {
return Optional.empty();
}
return Optional.of(
getLabel(MCRSessionMgr.getCurrentSession().getCurrentLanguage())
.orElseGet(() -> getLabel(defaultLang)
.orElseGet(() -> labels.stream().filter(l -> LANGUAGES.contains(l.getLang())).findFirst()
.orElseGet(() -> labels.stream().filter(l -> !l.getLang().startsWith("x-")).findFirst()
.orElseGet(() -> labels.iterator().next())))));
}
public Optional<MCRLabel> getLabel(String lang) {
String languageTag = Locale.forLanguageTag(lang).toLanguageTag();
for (MCRLabel label : labels) {
if (label.getLang().equals(languageTag)) {
return Optional.of(label);
}
}
return Optional.empty();
}
public String toString() {
return Optional.ofNullable(id).map(MCRCategoryID::toString).orElse(null);
}
}
| 5,417 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategLinkServiceImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategLinkServiceImpl.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.datamodel.classifications2.impl;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.jpa.AvailableHints;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRStreamUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkReference_;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRCategoryLink;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Root;
/**
*
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public class MCRCategLinkServiceImpl implements MCRCategLinkService {
private static Logger LOGGER = LogManager.getLogger();
private static Class<MCRCategoryLinkImpl> LINK_CLASS = MCRCategoryLinkImpl.class;
private static final String NAMED_QUERY_NAMESPACE = "MCRCategoryLink.";
private static MCRCache<MCRCategoryID, MCRCategory> categCache = new MCRCache<>(
MCRConfiguration2.getInt("MCR.Classifications.LinkServiceImpl.CategCache.Size").orElse(1000),
"MCRCategLinkService category cache");
private static MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance();
@Override
public Map<MCRCategoryID, Number> countLinks(MCRCategory parent, boolean childrenOnly) {
return countLinksForType(parent, null, childrenOnly);
}
@Override
public Map<MCRCategoryID, Number> countLinksForType(MCRCategory parent, String type, boolean childrenOnly) {
boolean restrictedByType = type != null;
String queryName;
if (childrenOnly) {
queryName = restrictedByType ? "NumberByTypePerChildOfParentID" : "NumberPerChildOfParentID";
} else {
queryName = restrictedByType ? "NumberByTypePerClassID" : "NumberPerClassID";
}
Map<MCRCategoryID, Number> countLinks = new HashMap<>();
Collection<MCRCategoryID> ids = childrenOnly ? getAllChildIDs(parent) : getAllCategIDs(parent);
for (MCRCategoryID id : ids) {
// initialize all categIDs with link count of zero
countLinks.put(id, 0);
}
//have to use rootID here if childrenOnly=false
//old classification browser/editor could not determine links correctly otherwise
final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
if (!childrenOnly) {
parent = parent.getRoot();
} else if (!(parent instanceof MCRCategoryImpl) || ((MCRCategoryImpl) parent).getInternalID() == 0) {
parent = MCRCategoryDAOImpl.getByNaturalID(em, parent.getId());
}
LOGGER.info("parentID:{}", parent.getId());
String classID = parent.getId().getRootID();
TypedQuery<Object[]> q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + queryName, Object[].class);
// query can take long time, please cache result
setCacheable(q);
setReadOnly(q);
q.setParameter("classID", classID);
if (childrenOnly) {
q.setParameter("parentID", ((MCRCategoryImpl) parent).getInternalID());
}
if (restrictedByType) {
q.setParameter("type", type);
}
// get object count for every category (not accumulated)
List<Object[]> result = q.getResultList();
for (Object[] sr : result) {
MCRCategoryID key = new MCRCategoryID(classID, sr[0].toString());
Number value = (Number) sr[1];
countLinks.put(key, value);
}
return countLinks;
}
@Override
public void deleteLink(MCRCategLinkReference reference) {
final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
Query q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "deleteByObjectID");
q.setParameter("id", reference.getObjectID());
q.setParameter("type", reference.getType());
int deleted = q.executeUpdate();
LOGGER.debug("Number of Links deleted: {}", deleted);
}
@Override
public void deleteLinks(final Collection<MCRCategLinkReference> ids) {
if (ids.isEmpty()) {
return;
}
HashMap<String, Collection<String>> typeMap = new HashMap<>();
//prepare
Collection<String> objectIds = new ArrayList<>();
String currentType = ids.iterator().next().getType();
typeMap.put(currentType, objectIds);
//collect per type
for (MCRCategLinkReference ref : ids) {
if (!currentType.equals(ref.getType())) {
currentType = ref.getType();
objectIds = typeMap.computeIfAbsent(ref.getType(), k -> new ArrayList<>());
}
objectIds.add(ref.getObjectID());
}
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
jakarta.persistence.Query q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "deleteByObjectCollection");
int deleted = 0;
for (Map.Entry<String, Collection<String>> entry : typeMap.entrySet()) {
q.setParameter("ids", entry.getValue());
q.setParameter("type", entry.getKey());
deleted += q.executeUpdate();
}
LOGGER.debug("Number of Links deleted: {}", deleted);
}
@Override
public Collection<String> getLinksFromCategory(MCRCategoryID id) {
final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<String> q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "ObjectIDByCategory", String.class);
setCacheable(q);
q.setParameter("id", id);
setReadOnly(q);
return q.getResultList();
}
@Override
public Collection<String> getLinksFromCategoryForType(MCRCategoryID id, String type) {
final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<String> q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "ObjectIDByCategoryAndType", String.class);
setCacheable(q);
q.setParameter("id", id);
q.setParameter("type", type);
setReadOnly(q);
return q.getResultList();
}
@Override
public Collection<MCRCategoryID> getLinksFromReference(MCRCategLinkReference reference) {
final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRCategoryID> q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "categoriesByObjectID",
MCRCategoryID.class);
setCacheable(q);
q.setParameter("id", reference.getObjectID());
q.setParameter("type", reference.getType());
setReadOnly(q);
return q.getResultList();
}
@Override
public void setLinks(MCRCategLinkReference objectReference, Collection<MCRCategoryID> categories) {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
categories
.stream()
.distinct()
.forEach(categID -> {
final MCRCategory category = getMCRCategory(entityManager, categID);
if (category == null) {
throw new MCRPersistenceException("Could not link to unknown category " + categID);
}
MCRCategoryLinkImpl link = new MCRCategoryLinkImpl(category, objectReference);
if (LOGGER.isDebugEnabled()) {
MCRCategory linkedCategory = link.getCategory();
StringBuilder debugMessage = new StringBuilder("Adding Link from ").append(linkedCategory.getId());
if (linkedCategory instanceof MCRCategoryImpl) {
debugMessage.append('(').append(((MCRCategoryImpl) linkedCategory).getInternalID())
.append(") ");
}
debugMessage.append("to ").append(objectReference);
LOGGER.debug(debugMessage.toString());
}
entityManager.persist(link);
LOGGER.debug("===DONE: {}", link.id);
});
}
private static MCRCategory getMCRCategory(EntityManager entityManager, MCRCategoryID categID) {
MCRCategory categ = categCache.getIfUpToDate(categID, DAO.getLastModified());
if (categ != null) {
return categ;
}
categ = MCRCategoryDAOImpl.getByNaturalID(entityManager, categID);
if (categ == null) {
return null;
}
categCache.put(categID, categ);
return categ;
}
@Override
public Map<MCRCategoryID, Boolean> hasLinks(MCRCategory category) {
if (category == null) {
return hasLinksForClassifications();
}
MCRCategoryImpl rootImpl = (MCRCategoryImpl) MCRCategoryDAOFactory.getInstance()
.getCategory(category.getRoot().getId(), -1);
if (rootImpl == null) {
//Category does not exist, so it has no links
return getNoLinksMap(category);
}
HashMap<MCRCategoryID, Boolean> boolMap = new HashMap<>();
final BitSet linkedInternalIds = getLinkedInternalIds();
storeHasLinkValues(boolMap, linkedInternalIds, rootImpl);
return boolMap;
}
private Map<MCRCategoryID, Boolean> hasLinksForClassifications() {
HashMap<MCRCategoryID, Boolean> boolMap = new HashMap<>() {
private static final long serialVersionUID = 1L;
@Override
public Boolean get(Object key) {
return Optional.ofNullable(super.get(key)).orElse(Boolean.FALSE);
}
};
final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<String> linkedClassifications = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "linkedClassifications",
String.class);
setReadOnly(linkedClassifications);
linkedClassifications.getResultList()
.stream().map(MCRCategoryID::rootID)
.forEach(id -> boolMap.put(id, true));
return boolMap;
}
private Map<MCRCategoryID, Boolean> getNoLinksMap(MCRCategory category) {
HashMap<MCRCategoryID, Boolean> boolMap = new HashMap<>();
for (MCRCategoryID categID : getAllCategIDs(category)) {
boolMap.put(categID, false);
}
return boolMap;
}
private void storeHasLinkValues(HashMap<MCRCategoryID, Boolean> boolMap, BitSet internalIds,
MCRCategoryImpl parent) {
final int internalID = parent.getInternalID();
if (internalID < internalIds.size() && internalIds.get(internalID)) {
addParentHasValues(boolMap, parent);
} else {
boolMap.put(parent.getId(), false);
}
for (MCRCategory child : parent.getChildren()) {
storeHasLinkValues(boolMap, internalIds, (MCRCategoryImpl) child);
}
}
private void addParentHasValues(HashMap<MCRCategoryID, Boolean> boolMap, MCRCategory parent) {
boolMap.put(parent.getId(), true);
if (parent.isCategory() && !Optional.ofNullable(boolMap.get(parent.getParent().getId())).orElse(false)) {
addParentHasValues(boolMap, parent.getParent());
}
}
private BitSet getLinkedInternalIds() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Number> query = cb.createQuery(Number.class);
Root<MCRCategoryLinkImpl> li = query.from(LINK_CLASS);
Path<Integer> internalId = li.get(MCRCategoryLinkImpl_.category).get(MCRCategoryImpl_.internalID);
List<Number> result = em
.createQuery(
query.select(internalId)
.orderBy(cb.desc(internalId)))
.getResultList();
int maxSize = result.size() == 0 ? 1 : result.get(0).intValue() + 1;
BitSet linkSet = new BitSet(maxSize);
for (Number internalID : result) {
linkSet.set(internalID.intValue(), true);
}
return linkSet;
}
private static Collection<MCRCategoryID> getAllCategIDs(MCRCategory category) {
return MCRStreamUtils.flatten(category, MCRCategory::getChildren, Collection::parallelStream)
.map(MCRCategory::getId)
.collect(Collectors.toCollection(HashSet::new));
}
private static Collection<MCRCategoryID> getAllChildIDs(MCRCategory category) {
return category.getChildren()
.stream()
.map(MCRCategory::getId)
.collect(Collectors.toCollection(HashSet::new));
}
@Override
public boolean hasLink(MCRCategory mcrCategory) {
return !hasLinks(mcrCategory).isEmpty();
}
@Override
public boolean isInCategory(MCRCategLinkReference reference, MCRCategoryID id) {
final EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
Query q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "CategoryAndObjectID");
setCacheable(q);
setReadOnly(q);
q.setParameter("rootID", id.getRootID());
q.setParameter("categID", id.getId());
q.setParameter("objectID", reference.getObjectID());
q.setParameter("type", reference.getType());
return !q.getResultList().isEmpty();
}
@Override
public Collection<MCRCategLinkReference> getReferences(String type) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRCategLinkReference> query = cb.createQuery(MCRCategLinkReference.class);
Root<MCRCategoryLinkImpl> li = query.from(LINK_CLASS);
Path<MCRCategLinkReference> objectReferencePath = li.get(MCRCategoryLinkImpl_.objectReference);
return em
.createQuery(
query.select(objectReferencePath)
.where(cb.equal(objectReferencePath.get(MCRCategLinkReference_.type), type)))
.setHint(AvailableHints.HINT_READ_ONLY, "true")
.getResultList();
}
@Override
public Collection<String> getTypes() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<String> q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "types", String.class);
return q.getResultList();
}
@Override
public Collection<MCRCategoryLink> getLinks(String type) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRCategoryLink> q = em.createNamedQuery(NAMED_QUERY_NAMESPACE + "links", MCRCategoryLink.class);
q.setParameter("type", type);
return q.getResultList();
}
private static void setReadOnly(Query query) {
query.setHint("org.hibernate.readOnly", Boolean.TRUE);
}
private static void setCacheable(Query query) {
query.setHint("org.hibernate.cacheable", Boolean.TRUE);
}
}
| 16,667 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryDTO.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryDTO.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.datamodel.classifications2.impl;
import java.net.URI;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Optional;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
/**
* Used for specific JPA queries only. Do not use directly!
* @author Thomas Scheffler (yagee)
* @since 2016.04
*/
public class MCRCategoryDTO {
public static final String SELECT = "select new org.mycore.datamodel.classifications2.impl.MCRCategoryDTO"
+ "(cat.internalID, cat.URI, cat.id, cat.left, cat.right, cat.level, labels.lang, labels.text,"
+ " labels.description) from MCRCategoryImpl cat LEFT OUTER JOIN cat.labels labels";
public static final String CAT_SELECT = "select new org.mycore.datamodel.classifications2.impl.MCRCategoryDTO"
+ "(cat.internalID, cat.URI, cat.id, cat.left, cat.right, cat.level) from MCRCategoryImpl cat";
public static final String LRL_SELECT = "select new org.mycore.datamodel.classifications2.impl.MCRCategoryDTO"
+ "(cat.left, cat.right, cat.level) from MCRCategoryImpl cat";
int internalID;
URI uri;
MCRCategoryID id;
int leftValue, level, rightValue;
String lang, text, description;
public MCRCategoryDTO(int internalID, URI uri, MCRCategoryID id, int leftValue, int rightValue,
int level, String lang, String text, String description) {
this(internalID, uri, id, leftValue, rightValue, level);
this.lang = lang;
this.text = text;
this.description = description;
}
public MCRCategoryDTO(int internalID, URI uri, MCRCategoryID id, int leftValue, int rightValue,
int level) {
this(leftValue, rightValue, level);
this.internalID = internalID;
this.uri = uri;
this.id = id;
}
public MCRCategoryDTO(int leftValue, int rightValue, int level) {
this.leftValue = leftValue;
this.rightValue = rightValue;
this.level = level;
}
public MCRCategoryImpl merge(MCRCategoryImpl predecessor) {
if (predecessor == null) {
return toCategory();
}
if (predecessor.getInternalID() == internalID) {
//only add label
return appendLabel(predecessor);
}
MCRCategoryImpl cat = toCategory();
MCRCategory parent = predecessor;
while (parent.getLevel() >= level) {
parent = parent.getParent();
}
parent.getChildren().add(cat);
cat.setLevel(level); //is reset to parent.level+1 in step before
return cat;
}
private MCRCategoryImpl toCategory() {
MCRCategoryImpl cat = new MCRCategoryImpl();
cat.setInternalID(internalID);
cat.setURI(uri);
cat.setId(id);
if (cat.getId().isRootID()) {
cat.setRoot(cat);
}
cat.setLeft(leftValue);
cat.setRight(rightValue);
cat.setLevel(level);
cat.setChildren(new ArrayList<>());
return appendLabel(cat);
}
private MCRCategoryImpl appendLabel(MCRCategoryImpl cat) {
if (lang != null) {
MCRLabel label = new MCRLabel(lang, text,
Optional.ofNullable(description).filter(s -> !s.isEmpty()).orElse(null));
cat.getLabels().add(label);
}
return cat;
}
@Override
public String toString() {
return String.format(Locale.ROOT,
"MCRCategoryDTO [internalID=%s, id=%s, uri=%s, leftValue=%s, level=%s, "
+ "rightValue=%s, lang=%s, text=%s, description=%s]",
internalID, id, uri, leftValue, level, rightValue, lang, text, description);
}
public int getInternalID() {
return internalID;
}
}
| 4,587 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryLinkImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/impl/MCRCategoryLinkImpl.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.datamodel.classifications2.impl;
import org.hibernate.jpa.AvailableHints;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryLink;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.QueryHint;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
/**
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
@Entity
@Table(name = "MCRCategoryLink",
uniqueConstraints = { @UniqueConstraint(columnNames = { "category", "objectID", "objectType" }) },
indexes = { @Index(columnList = "objectID, objectType", name = "ObjectIDType") })
@NamedQueries({
@NamedQuery(name = "MCRCategoryLink.ObjectIDByCategory",
query = "SELECT objectReference.objectID FROM MCRCategoryLinkImpl WHERE category.id=:id"),
@NamedQuery(name = "MCRCategoryLink.deleteByObjectCollection",
query = "DELETE FROM MCRCategoryLinkImpl WHERE "
+ "objectReference.objectID IN (:ids) and objectReference.type=:type"),
@NamedQuery(name = "MCRCategoryLink.NumberPerClassID",
query = "SELECT cat.id.id, count(distinct link.objectReference.objectID) as num"
+ " FROM MCRCategoryLinkImpl link, MCRCategoryImpl cat, MCRCategoryImpl cattree"
+ " WHERE cattree.internalID = link.category.internalID"
+ " AND cattree.id.rootID=:classID"
+ " AND cat.id.rootID=:classID"
+ " AND cattree.left BETWEEN cat.left AND cat.right"
+ " GROUP BY cat.id.id"),
@NamedQuery(name = "MCRCategoryLink.NumberPerChildOfParentID",
query = "SELECT cat.id.id, count(distinct link.objectReference.objectID) as num"
+ " FROM MCRCategoryLinkImpl link, MCRCategoryImpl cat, MCRCategoryImpl cattree"
+ " WHERE cattree.internalID = link.category.internalID"
+ " AND cattree.id.rootID=:classID"
+ " AND cat.parent.internalID=:parentID"
+ " AND cattree.left BETWEEN cat.left AND cat.right"
+ " GROUP BY cat.id.id"),
@NamedQuery(name = "MCRCategoryLink.categoriesByObjectID",
query = "SELECT category.id FROM MCRCategoryLinkImpl WHERE "
+ "objectReference.objectID=:id and objectReference.type=:type"),
@NamedQuery(name = "MCRCategoryLink.ObjectIDByCategoryAndType",
query = "SELECT objectReference.objectID FROM MCRCategoryLinkImpl WHERE "
+ "category.id=:id and objectReference.type=:type"),
@NamedQuery(name = "MCRCategoryLink.NumberByTypePerClassID",
query = "SELECT cat.id.id, count(distinct link.objectReference.objectID) as num"
+ " FROM MCRCategoryLinkImpl link, MCRCategoryImpl cat, MCRCategoryImpl cattree"
+ " WHERE cattree.internalID = link.category.internalID"
+ " AND link.objectReference.type=:type"
+ " AND cattree.id.rootID=:classID"
+ " AND cat.id.rootID=:classID"
+ " AND cattree.left BETWEEN cat.left AND cat.right"
+ " GROUP BY cat.id.id"),
@NamedQuery(name = "MCRCategoryLink.NumberByTypePerChildOfParentID",
query = "SELECT cat.id.id, count(distinct link.objectReference.objectID) as num"
+ " FROM MCRCategoryLinkImpl link, MCRCategoryImpl cat, MCRCategoryImpl cattree"
+ " WHERE cattree.internalID = link.category.internalID"
+ " AND link.objectReference.type=:type"
+ " AND cattree.id.rootID=:classID"
+ " AND cat.parent.internalID=:parentID"
+ " AND cattree.left BETWEEN cat.left AND cat.right"
+ " GROUP BY cat.id.id"),
@NamedQuery(name = "MCRCategoryLink.deleteByObjectID",
query = "DELETE FROM MCRCategoryLinkImpl WHERE objectReference.objectID=:id and objectReference.type=:type"),
@NamedQuery(name = "MCRCategoryLink.CategoryAndObjectID",
query = "SELECT link.objectReference.objectID"
+ " FROM MCRCategoryLinkImpl link, MCRCategoryImpl cat, MCRCategoryImpl cattree"
+ " WHERE cattree.internalID = link.category.internalID"
+ " AND link.objectReference.objectID=:objectID"
+ " AND link.objectReference.type=:type"
+ " AND cattree.id.rootID=:rootID"
+ " AND cat.id.rootID=:rootID"
+ " AND cat.id.id=:categID"
+ " AND cattree.left BETWEEN cat.left AND cat.right",
hints = { @QueryHint(name = AvailableHints.HINT_READ_ONLY, value = "true") }),
@NamedQuery(name = "MCRCategoryLink.linkedClassifications",
query = "SELECT distinct node.id.rootID from MCRCategoryImpl as node, MCRCategoryLinkImpl as link "
+ "where node.internalID = link.category.internalID"),
@NamedQuery(name = "MCRCategoryLink.types",
query = "SELECT DISTINCT(objectReference.type) FROM MCRCategoryLinkImpl"),
@NamedQuery(name = "MCRCategoryLink.links",
query = "FROM MCRCategoryLinkImpl WHERE objectReference.type=:type")
})
public class MCRCategoryLinkImpl implements MCRCategoryLink {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
@ManyToOne(targetEntity = MCRCategoryImpl.class)
@JoinColumn(name = "category")
private MCRCategory category;
@Embedded
private MCRCategLinkReference objectReference;
public MCRCategoryLinkImpl() {
this(null, null);
}
MCRCategoryLinkImpl(MCRCategory category, MCRCategLinkReference objectReference) {
this.category = category;
this.objectReference = objectReference;
}
@Override
public MCRCategory getCategory() {
return category;
}
public void setCategory(MCRCategoryImpl category) {
this.category = category;
}
@Override
public MCRCategLinkReference getObjectReference() {
return objectReference;
}
public void setObjectReference(MCRCategLinkReference objectReference) {
this.objectReference = objectReference;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (category == null ? 0 : category.hashCode());
result = prime * result + (objectReference == null ? 0 : objectReference.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MCRCategoryLinkImpl other)) {
return false;
}
if (category == null) {
if (other.category != null) {
return false;
}
} else if (!category.equals(other.category)) {
return false;
}
if (objectReference == null) {
return other.objectReference == null;
} else {
return objectReference.equals(other.objectReference);
}
}
}
| 8,174 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCRCategoryTransformer.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.datamodel.classifications2.utils;
import static org.jdom2.Namespace.XML_NAMESPACE;
import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
import static org.mycore.common.MCRConstants.XSI_NAMESPACE;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jdom2.Document;
import org.jdom2.Element;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
/**
*
* @author Thomas Scheffler (yagee)
*
*/
public class MCRCategoryTransformer {
private static final String STANDARD_LABEL = "{text}";
/**
* transforms a <code>MCRCategory</code> into a JDOM Document.
*
* The Document will have a root tag with name "mycoreclass".
*
* @param cl
* Classification
*/
public static Document getMetaDataDocument(MCRCategory cl, boolean withCounter) {
Map<MCRCategoryID, Number> countMap = null;
if (withCounter) {
countMap = MCRCategLinkServiceFactory.getInstance().countLinks(cl, false);
}
return MetaDataElementFactory.getDocument(cl, countMap);
}
/**
* transforms a <code>MCRCategory</code> into a JDOM Element.
*
* The element will have the tag name "category".
*
* @param category
* a category of a classification
*/
public static Element getMetaDataElement(MCRCategory category, boolean withCounter) {
Map<MCRCategoryID, Number> countMap = null;
if (withCounter) {
countMap = MCRCategLinkServiceFactory.getInstance().countLinks(category, false);
}
return MetaDataElementFactory.getElement(category, countMap);
}
/**
* transforms a <code>Classification</code> into a MCR Editor definition (
* <code><items></code>).
*
* @param cl
* Classification
* @param sort
* if true, sort items
* @param emptyLeaves
* if true, also include empty leaves
* @param completeId
* if true, category ID is given in form {classID}':'{categID}
*/
public static Element getEditorItems(MCRCategory cl, boolean sort, boolean emptyLeaves, boolean completeId) {
return new ItemElementFactory(cl, STANDARD_LABEL, sort, emptyLeaves, completeId).getResult();
}
/**
* transforms a <code>Classification</code> into a MCR Editor definition (<code><items></code>).
*
* This method allows you to specify how the labels will look like.
* <code>labelFormat</code> is simply a String that is parsed for a few
* key words, that will be replaced by a dynamic value. The following
* keywords can be used at the moment:
* <ul>
* <li>{id}</li>
* <li>{text}</li>
* <li>{description}</li>
* <li>{count}</li>
* </ul>
*
* @param cl
* Classification
* @param labelFormat
* format String as specified above
* @param sort
* if true, sort items
* @param emptyLeaves
* if true, also include empty leaves
*/
public static Element getEditorItems(MCRCategory cl, String labelFormat, boolean sort, boolean emptyLeaves,
boolean completeId) {
return new ItemElementFactory(cl, labelFormat, sort, emptyLeaves, completeId).getResult();
}
static class MetaDataElementFactory {
static Document getDocument(MCRCategory cl, Map<MCRCategoryID, Number> countMap) {
Document cd = new Document(new Element("mycoreclass"));
cd.getRootElement().setAttribute("noNamespaceSchemaLocation", "MCRClassification.xsd", XSI_NAMESPACE);
cd.getRootElement().setAttribute("ID", cl.getId().getRootID());
cd.getRootElement().addNamespaceDeclaration(XLINK_NAMESPACE);
MCRCategory root = cl.isClassification() ? cl : cl.getRoot();
for (MCRLabel label : root.getLabels()) {
cd.getRootElement().addContent(MCRLabelTransformer.getElement(label));
}
if (root.getURI() != null) {
cd.getRootElement().addContent(getElement(root.getURI()));
}
Element categories = new Element("categories");
cd.getRootElement().addContent(categories);
if (cl.isClassification()) {
for (MCRCategory category : cl.getChildren()) {
categories.addContent(getElement(category, countMap));
}
} else {
categories.addContent(getElement(cl, countMap));
}
return cd;
}
static Element getElement(MCRCategory category, Map<MCRCategoryID, Number> countMap) {
Element ce = new Element("category");
ce.setAttribute("ID", category.getId().getId());
Number number = countMap == null ? null : countMap.get(category.getId());
if (number != null) {
ce.setAttribute("counter", Integer.toString(number.intValue()));
}
for (MCRLabel label : category.getLabels()) {
ce.addContent(MCRLabelTransformer.getElement(label));
}
if (category.getURI() != null) {
URI link = category.getURI();
ce.addContent(getElement(link));
}
for (MCRCategory cat : category.getChildren()) {
ce.addContent(getElement(cat, countMap));
}
return ce;
}
static Element getElement(URI link) {
Element le = new Element("url");
le.setAttribute("href", link.toString(), XLINK_NAMESPACE);
// TODO: Have to check url here: any samples?
le.setAttribute("type", "locator", XLINK_NAMESPACE);
return le;
}
static boolean stringNotEmpty(String test) {
return test != null && test.length() > 0;
}
}
private static class ItemElementFactory {
private static final Pattern TEXT_PATTERN = Pattern.compile("\\{text\\}");
private static final Pattern ID_PATTERN = Pattern.compile("\\{id\\}");
private static final Pattern DESCR_PATTERN = Pattern.compile("\\{description\\}");
private static final Pattern COUNT_PATTERN = Pattern.compile("\\{count(:([^\\)]+))?\\}");
private String labelFormat;
private boolean emptyLeaves, completeId;
private Map<MCRCategoryID, Number> countMap = null;
private Map<MCRCategoryID, Boolean> linkedMap = null;
private Element root;
ItemElementFactory(MCRCategory cl, String labelFormat, boolean sort, boolean emptyLeaves, boolean completeId) {
this.labelFormat = labelFormat;
this.emptyLeaves = emptyLeaves;
this.completeId = completeId;
Matcher countMatcher = COUNT_PATTERN.matcher(labelFormat);
/*
* countMatcher.group(0) is the whole expression string like
* {count:document} countMatcher.group(1) is first inner expression
* string like :document countMatcher.group(2) is most inner
* expression string like document
*/
if (countMatcher.find()) {
if (countMatcher.group(1) == null) {
countMap = MCRCategLinkServiceFactory.getInstance().countLinks(cl, false);
} else {
// group(2) contains objectType
String objectType = countMatcher.group(2);
countMap = MCRCategLinkServiceFactory.getInstance().countLinksForType(cl, objectType, false);
}
}
if (!emptyLeaves) {
linkedMap = MCRCategLinkServiceFactory.getInstance().hasLinks(cl);
}
root = new Element("items");
for (MCRCategory category : cl.getChildren()) {
addChildren(root, category);
}
if (sort) {
final List<Element> items = root.getChildren("item");
sortItems(items);
}
}
Element getResult() {
return root;
}
void addChildren(Element parent, MCRCategory category) {
if (!emptyLeaves && !linkedMap.get(category.getId())) {
return;
}
Element ce = new Element("item");
ce.setAttribute("value", completeId ? category.getId().toString() : category.getId().getId());
parent.addContent(ce);
for (MCRLabel label : category.getLabels()) {
addLabel(ce, label, category);
addDescription(ce, label);
}
for (MCRCategory cat : category.getChildren()) {
addChildren(ce, cat);
}
}
void addLabel(Element item, MCRLabel label, MCRCategory cat) {
Element le = new Element("label");
item.addContent(le);
if (label.getLang() != null && label.getLang().length() > 0) {
le.setAttribute("lang", label.getLang(), XML_NAMESPACE);
}
String labtext = label.getText() != null ? label.getText() : "";
String text;
try {
text = TEXT_PATTERN.matcher(labelFormat).replaceAll(labtext);
} catch (RuntimeException e) {
throw new RuntimeException("Error while inserting '" + labtext + "' into: " + labelFormat, e);
}
text = ID_PATTERN.matcher(text).replaceAll(cat.getId().getId());
text = DESCR_PATTERN.matcher(text)
.replaceAll(label.getDescription().replace("\\", "\\\\").replace("$", "\\$"));
int num = countMap == null ? -1 : countMap.get(cat.getId()).intValue();
if (num >= 0) {
text = COUNT_PATTERN.matcher(text).replaceAll(String.valueOf(num));
}
le.setText(text);
}
void addDescription(Element item, MCRLabel label) {
if (label.getDescription() == null || label.getDescription().length() == 0) {
return;
}
Element desc = new Element("description");
desc.setAttribute("lang", label.getLang(), XML_NAMESPACE);
desc.setText(label.getDescription());
item.addContent(desc);
}
private void sortItems(List<Element> items) {
sort(items, MCREditorItemComparator.getCurrentLangComperator());
for (Element item : items) {
List<Element> children = item.getChildren("item");
if (children.size() > 0) {
sortItems(children);
}
}
}
private void sort(List<Element> list, Comparator<Element> c) {
Element[] a = list.toArray(Element[]::new);
Arrays.sort(a, c);
for (Element element : a) {
element.detach();
}
Collections.addAll(list, a);
}
}
}
| 12,153 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSkosTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCRSkosTransformer.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.datamodel.classifications2.utils;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.mycore.common.MCRConstants;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.frontend.MCRFrontendUtil;
/**
* Transforms MyCoRe classification and category objects into SKOS resources
*
* @author Robert Stephan
*
*/
public class MCRSkosTransformer {
/**
* return a classification tree as SKOS XML
*
* @param categ - an extract of the classification that should be returned via SKOS
* currently this is the hierarchy from the requested category to the root category
* @param current - the MCRCategoryID of the requested category
*/
public static Document getSkosInRDFXML(MCRCategory categ, MCRCategoryID current) {
Element eRDF = new Element("RDF", MCRConstants.RDF_NAMESPACE);
eRDF.addNamespaceDeclaration(MCRConstants.SKOS_NAMESPACE);
if (categ.isClassification()) {
createSkosConceptScheme(categ, current, eRDF);
}
if (categ.isCategory()) {
createSkosConcept(categ, current, eRDF);
}
return new Document(eRDF);
}
/**
* creates a rdf element skos:Concept and its XML structure with attributes and child elements
* @param categ - the MyCoRe category object
* @param eRDF the RDF root elements which collects all concepts
*/
private static void createSkosConceptScheme(MCRCategory categ, MCRCategoryID current, Element eRDF) {
if (categ != null) {
Element eConcept = new Element("ConceptScheme", MCRConstants.SKOS_NAMESPACE);
eRDF.addContent(eConcept);
eConcept.setAttribute("about", retrieveURI(categ), MCRConstants.RDF_NAMESPACE);
convertLabelsAndDescriptions(categ, eConcept);
for (MCRCategory child : categ.getChildren()) {
eConcept.addContent(new Element("hasTopConcept", MCRConstants.SKOS_NAMESPACE)
.setAttribute("resource", retrieveURI(child), MCRConstants.RDF_NAMESPACE));
createSkosConcept(child, current, eRDF);
}
}
}
/**
* creates a rdf element skos:Concept and its XML structure with attributes and child elements
* @param categ - the MyCoRe category object
* @param eRDF the RDF root elements which collects all concepts
*/
private static void createSkosConcept(MCRCategory categ, MCRCategoryID current, Element eRDF) {
if (categ != null) {
Element eConcept = new Element("Concept", MCRConstants.SKOS_NAMESPACE);
eRDF.addContent(eConcept);
eConcept.setAttribute("about", retrieveURI(categ), MCRConstants.RDF_NAMESPACE);
convertLabelsAndDescriptions(categ, eConcept);
if (categ.getParent() != null) {
if (categ.getParent().isClassification()) {
// skos:topConceptOf is a sub-property of skos:inScheme.
eConcept.addContent(new Element("isTopConceptOf", MCRConstants.SKOS_NAMESPACE)
.setAttribute("resource", retrieveURI(categ.getParent()), MCRConstants.RDF_NAMESPACE));
}
if (categ.getParent().isCategory()) {
eConcept.addContent(new Element("broader", MCRConstants.SKOS_NAMESPACE)
.setAttribute("resource", retrieveURI(categ.getParent()), MCRConstants.RDF_NAMESPACE));
eConcept.addContent(new Element("inScheme", MCRConstants.SKOS_NAMESPACE)
.setAttribute("resource", retrieveURI(categ.getRoot()), MCRConstants.RDF_NAMESPACE));
}
}
for (MCRCategory child : categ.getChildren()) {
eConcept.addContent(new Element("narrower", MCRConstants.SKOS_NAMESPACE)
.setAttribute("resource", retrieveURI(child), MCRConstants.RDF_NAMESPACE));
createSkosConcept(child, current, eRDF);
}
// on reimplementation / consolidation we could try to integrate this additional query
// into the main query
if (categ.getId().equals(current)) {
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
for (MCRCategory c : categoryDAO.getChildren(current)) {
eConcept.addContent(new Element("narrower", MCRConstants.SKOS_NAMESPACE)
.setAttribute("resource", retrieveURI(c), MCRConstants.RDF_NAMESPACE));
}
}
}
}
/**
* converts classification labels and descriptions to skos:preferedLabels
*/
private static void convertLabelsAndDescriptions(MCRCategory categ, Element eConcept) {
for (MCRLabel lbl : categ.getLabels()) {
if (!lbl.getLang().startsWith("x-")) {
eConcept.addContent(new Element("prefLabel", MCRConstants.SKOS_NAMESPACE)
.setAttribute("lang", lbl.getLang(), MCRConstants.XML_NAMESPACE)
.setText(lbl.getText()));
}
}
for (MCRLabel lbl : categ.getLabels()) {
if (!lbl.getLang().startsWith("x-") && StringUtils.isNotEmpty(lbl.getDescription())) {
eConcept.addContent(new Element("definition", MCRConstants.SKOS_NAMESPACE)
.setAttribute("lang", lbl.getLang(), MCRConstants.XML_NAMESPACE)
.setText(lbl.getDescription()));
}
}
categ.getLabel("x-skos-exact").ifPresent(x -> {
for (String uri : x.getText().split("\\s")) {
eConcept.addContent(new Element("exactMatch", MCRConstants.SKOS_NAMESPACE)
.setAttribute("resource", uri, MCRConstants.RDF_NAMESPACE));
}
});
}
/**
* retrieves the URI for the SKOS Concept or Concept Scheme
*
* There is no consistent use of URI and x-uri attributes in MyCoRe
* Furthermore we need to define a new endpoint /entities for Linked Data output
*
* Details of the implementation needs to be discussed within the community
*
* @param categ the MCRCategory object
*
* @return the URI as String
*/
private static String retrieveURI(MCRCategory categ) {
/*
* The use of URI or x-URI label is not standardized in MyCoRe
* It needs to be discussed in the Community
*
if (categ.getURI() != null) {
return categ.getURI().toString();
}
if (categ.getLabel("x-uri").isPresent()) {
return categ.getLabel("x-uri").get().getText();
}
*/
if (categ.isClassification()) {
return MCRFrontendUtil.getBaseURL() + "open-data/classification/" + categ.getId().getRootID();
}
return MCRFrontendUtil.getBaseURL() + "open-data/classification/" + categ.getId().getRootID() + "/"
+ categ.getId().getId();
}
}
| 8,052 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStringTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCRStringTransformer.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.datamodel.classifications2.utils;
import java.util.Collection;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRLabel;
public class MCRStringTransformer {
public static String getString(MCRCategory category) {
StringBuilder sb = new StringBuilder(1024);
printCatgory(category, sb);
return sb.toString();
}
private static void printCatgory(MCRCategory category, StringBuilder sb) {
sb.append(" ".repeat(category.getLevel()));
sb.append(category.getId());
sb.append('[');
printLabels(category.getLabels(), sb);
sb.append(']');
sb.append('\n');
for (MCRCategory child : category.getChildren()) {
printCatgory(child, sb);
}
}
private static void printLabels(Collection<MCRLabel> labels, StringBuilder sb) {
for (MCRLabel label : labels) {
sb.append(label);
sb.append(',');
}
if (labels.size() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
}
}
| 1,838 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCRXMLTransformer.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.datamodel.classifications2.utils;
import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRException;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl;
public class MCRXMLTransformer {
public static MCRCategory getCategory(Document xml) throws URISyntaxException {
MCRCategoryImpl category = new MCRCategoryImpl();
category.setRoot(category);
final String classID = xml.getRootElement().getAttributeValue("ID");
category.setLevel(0);
category.setId(MCRCategoryID.rootID(classID));
setURL(xml.getRootElement(), category);
//setChildren has to be called before setParent (below) can be called without
//database access see: org.mycore.datamodel.classifications2.impl.MCRAbstractCategoryImpl.getChildren()
category.setChildren(new ArrayList<>());
buildChildCategories(classID, xml.getRootElement().getChild("categories").getChildren("category"), category);
try {
category.setLabels(getLabels(xml.getRootElement().getChildren("label")));
} catch (NullPointerException | IllegalArgumentException ex) {
throw new MCRException("Error while adding labels to classification: " + classID, ex);
}
return category;
}
public static MCRCategory buildCategory(String classID, Element e, MCRCategory parent) throws URISyntaxException {
MCRCategoryImpl category = new MCRCategoryImpl();
//setId must be called before setParent (info important)
category.setId(new MCRCategoryID(classID, e.getAttributeValue("ID")));
category.setRoot(parent.getRoot());
category.setChildren(new ArrayList<>());
category.setParent(parent);
try {
category.setLabels(getLabels(e.getChildren("label")));
} catch (NullPointerException | IllegalArgumentException ex) {
throw new MCRException("Error while adding labels to category: " + category.getId(), ex);
}
category.setLevel(parent.getLevel() + 1);
setURL(e, category);
buildChildCategories(classID, e.getChildren("category"), category);
return category;
}
private static List<MCRCategory> buildChildCategories(String classID, List<Element> elements, MCRCategory parent)
throws URISyntaxException {
List<MCRCategory> children = new ArrayList<>(elements.size());
for (Object o : elements) {
children.add(buildCategory(classID, (Element) o, parent));
}
return children;
}
public static SortedSet<MCRLabel> getLabels(List<Element> elements)
throws NullPointerException, IllegalArgumentException {
SortedSet<MCRLabel> labels = new TreeSet<>();
for (Element labelElement : elements) {
MCRLabel label = getLabel(labelElement);
labels.add(label);
}
return labels;
}
public static MCRLabel getLabel(Element labelElement) throws NullPointerException, IllegalArgumentException {
String lang = labelElement.getAttributeValue("lang", Namespace.XML_NAMESPACE);
return new MCRLabel(lang, labelElement.getAttributeValue("text"),
labelElement.getAttributeValue("description"));
}
private static void setURL(Element e, MCRCategory category) throws URISyntaxException {
if (e.getChild("url") != null) {
final String uri = e.getChild("url").getAttributeValue("href", XLINK_NAMESPACE);
if (uri != null) {
category.setURI(new URI(uri));
}
}
}
}
| 4,783 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREditorItemComparator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCREditorItemComparator.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.datamodel.classifications2.utils;
import java.text.Collator;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRSessionMgr;
public class MCREditorItemComparator implements Comparator<Element> {
private static final HashMap<String, MCREditorItemComparator> MY_COLLATORS = new HashMap<>();
private Collator myCollator;
private String language;
private MCREditorItemComparator(Collator myCollator, String language) {
super();
this.myCollator = myCollator;
this.language = language;
}
public int compare(Element o1, Element o2) {
if (!(o1.getName().equals("item") && o2.getName().equals("item"))) {
//NO Editor Items
return 0;
}
return myCollator.compare(getCurrentLangLabel(o1, language), getCurrentLangLabel(o2, language));
}
private static String getCurrentLangLabel(Element item, String language) {
List<Element> labels = item.getChildren("label");
for (Element label : labels) {
if (label.getAttributeValue("lang", Namespace.XML_NAMESPACE).equals(language)) {
return label.getText();
}
}
if (labels.size() > 0) {
//fallback to first label if currentLang label is not found
return labels.get(0).getText();
}
return "";
}
private static MCREditorItemComparator getLangCollator(String lang) {
MCREditorItemComparator comperator = MY_COLLATORS.get(lang);
if (comperator == null) {
Locale l = Locale.forLanguageTag(lang);
Collator collator = Collator.getInstance(l);
collator.setStrength(Collator.SECONDARY);
comperator = new MCREditorItemComparator(collator, lang);
MY_COLLATORS.put(lang, comperator);
}
return comperator;
}
public static Comparator<Element> getCurrentLangComperator() {
String currentLanguage = MCRSessionMgr.getCurrentSession().getCurrentLanguage();
return getLangCollator(currentLanguage);
}
}
| 2,947 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLabelTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCRLabelTransformer.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.datamodel.classifications2.utils;
import static org.jdom2.Namespace.XML_NAMESPACE;
import org.jdom2.Element;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.datamodel.classifications2.utils.MCRCategoryTransformer.MetaDataElementFactory;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRLabelTransformer {
public static Element getElement(MCRLabel label) {
Element le = new Element("label");
if (MetaDataElementFactory.stringNotEmpty(label.getLang())) {
le.setAttribute("lang", label.getLang(), XML_NAMESPACE);
}
le.setAttribute("text", label.getText() != null ? label.getText() : "");
if (MetaDataElementFactory.stringNotEmpty(label.getDescription())) {
le.setAttribute("description", label.getDescription());
}
return le;
}
}
| 1,604 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClassificationUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/utils/MCRClassificationUtils.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.datamodel.classifications2.utils;
import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.access.MCRAccessException;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRException;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
/**
* This class contains helper methods to handle mycore classifications.
*
* @author Matthias Eichner
*/
public class MCRClassificationUtils {
public static final String CREATE_CLASS_PERMISSION = "create-class";
/**
* Returns the classification as string. Returns null if the
* classification does not exists.
*
* @param classId the classification root id
* @return the classification as string
*/
public static String asString(String classId) {
Document xml = asDocument(classId);
return new XMLOutputter(Format.getPrettyFormat()).outputString(xml);
}
/**
* Returns the classification as a jdom document. Returns null if the
* classification does not exists.
*
* @param classId the classification root id
* @return the classification as jdom document
*/
public static Document asDocument(String classId) {
MCRCategoryID categoryId = MCRCategoryID.rootID(classId);
MCRCategory classification = MCRCategoryDAOFactory.getInstance().getRootCategory(categoryId, -1);
if (classification == null) {
return null;
}
return MCRCategoryTransformer.getMetaDataDocument(classification, false);
}
/**
* Imports a classification from the given path. If the classification
* already exists, it will be replaced.
*
* @param pathToClassification path to the classification
* @throws IOException could not read from file
* @throws MCRException xml parsing went wrong
* @throws URISyntaxException unable to transform the xml to a {@link MCRCategory}
* @throws MCRAccessException you are not allowed to import the classification
*/
public static void fromPath(Path pathToClassification)
throws IOException, MCRException, MCRAccessException, URISyntaxException {
InputStream inputStream = Files.newInputStream(pathToClassification);
fromStream(inputStream);
}
/**
* Imports a classification from the given input stream. If the classification
* already exists, it will be replaced.
*
* @param inputStream the classification stream
* @throws MCRException xml parsing went wrong
* @throws URISyntaxException unable to transform the xml to a {@link MCRCategory}
* @throws MCRAccessException you are not allowed to import the classification
*/
public static void fromStream(InputStream inputStream)
throws MCRException, URISyntaxException, MCRAccessException, IOException {
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
Document jdom = null;
try {
jdom = MCRXMLParserFactory.getParser().parseXML(new MCRStreamContent(inputStream));
} catch (JDOMException e) {
throw new MCRException(e);
}
MCRCategory classification = MCRXMLTransformer.getCategory(jdom);
if (categoryDAO.exist(classification.getId())) {
if (!MCRAccessManager.checkPermission(classification.getId().getRootID(), PERMISSION_WRITE)) {
throw MCRAccessException.missingPermission(
"update classification " + classification.getId().getRootID(), classification.getId().getRootID(),
PERMISSION_WRITE);
}
categoryDAO.replaceCategory(classification);
} else {
if (!MCRAccessManager.checkPermission(CREATE_CLASS_PERMISSION)) {
throw MCRAccessException.missingPermission(
"create classification " + classification.getId().getRootID(), classification.getId().getRootID(),
CREATE_CLASS_PERMISSION);
}
categoryDAO.addCategory(null, classification);
}
}
}
| 5,397 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/model/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
@XmlSchema(
xmlns = @XmlNs(prefix = "xlink", namespaceURI = "http://www.w3.org/1999/xlink"))
package org.mycore.datamodel.classifications2.model;
import jakarta.xml.bind.annotation.XmlNs;
import jakarta.xml.bind.annotation.XmlSchema;
| 966 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClass.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/model/MCRClass.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.datamodel.classifications2.model;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementWrapper;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlSeeAlso;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.NormalizedStringAdapter;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name = "mycoreclass")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MCRClass",
propOrder = {
"label",
"url",
"categories"
})
@XmlSeeAlso({ MCRClassCategory.class, MCRClassURL.class, MCRLabel.class })
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder({ "ID", "url", "labels", "categories" })
public class MCRClass {
@XmlElement(required = true)
protected List<MCRLabel> label;
protected MCRClassURL url;
@XmlElementWrapper(name = "categories")
@XmlElement(name = "category")
protected List<MCRClassCategory> categories;
@XmlAttribute(name = "ID", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String id;
@JsonGetter("labels")
public List<MCRLabel> getLabel() {
if (label == null) {
label = new ArrayList<>();
}
return this.label;
}
public MCRClassURL getUrl() {
return url;
}
public void setUrl(MCRClassURL value) {
this.url = value;
}
@JsonGetter("categories")
public List<MCRClassCategory> getCategories() {
return categories;
}
public void setCategories(List<MCRClassCategory> value) {
this.categories = value;
}
@JsonGetter
public String getID() {
return id;
}
public void setID(String value) {
this.id = value;
}
public static MCRClass getClassification(MCRCategory rootCategory) {
if (!rootCategory.getId().isRootID()) {
throw new IllegalArgumentException("Not a root category");
}
MCRClass mcrClass = new MCRClass();
mcrClass.setID(rootCategory.getId().getRootID());
mcrClass.setUrl(MCRClassURL.getInstance(rootCategory.getURI()));
mcrClass.getLabel()
.addAll(
rootCategory.getLabels()
.stream()
.map(MCRLabel::clone)
.collect(Collectors.toList()));
mcrClass.setCategories(MCRClassCategory.getInstance(rootCategory.getChildren()));
return mcrClass;
}
public MCRCategory toCategory() {
MCRCategoryImpl category = new MCRCategoryImpl();
category.setId(MCRCategoryID.rootID(getID()));
category.setLevel(0);
URI uri = Optional.ofNullable(getUrl())
.map(MCRClassURL::getHref)
.map(URI::create)
.orElse(null);
category.setURI(uri);
category.getLabels()
.addAll(getLabel().stream()
.map(MCRLabel::clone)
.collect(Collectors.toList()));
return category;
}
public static MCRCategory buildCategory(String classID, MCRClassCategory e, MCRCategory parent) {
MCRCategoryImpl category = new MCRCategoryImpl();
//setId must be called before setParent (info important)
category.setId(new MCRCategoryID(classID, e.getID()));
category.setRoot(parent.getRoot());
category.setChildren(new ArrayList<>());
category.setParent(parent);
category.getLabels()
.addAll(e.getLabel().stream()
.map(MCRLabel::clone)
.collect(Collectors.toList()));
category.setLevel(parent.getLevel() + 1);
URI uri = Optional.ofNullable(e.getUrl())
.map(MCRClassURL::getHref)
.map(URI::create)
.orElse(null);
category.setURI(uri);
for (MCRClassCategory child : e.getCategory()) {
buildCategory(classID, child, category);
}
return category;
}
}
| 5,488 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClassURL.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/model/MCRClassURL.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.datamodel.classifications2.model;
import java.net.URI;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonValue;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlSchemaType;
import jakarta.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MCRClassURL")
@JsonFormat(shape = JsonFormat.Shape.STRING)
public class MCRClassURL {
@XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink")
protected static final String TYPE = "locator";
@XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String href;
@JsonValue
public String getHref() {
return href;
}
public void setHref(String value) {
this.href = value;
}
@JsonCreator
public static MCRClassURL getInstance(URI uri) {
if (uri == null) {
return null;
}
MCRClassURL url = new MCRClassURL();
url.setHref(uri.toASCIIString());
return url;
}
}
| 2,015 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClassCategory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/classifications2/model/MCRClassCategory.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.datamodel.classifications2.model;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlSeeAlso;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.NormalizedStringAdapter;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MCRClassCategory",
propOrder = {
"label",
"url",
"category"
})
@XmlSeeAlso({ MCRLabel.class, MCRClassURL.class })
@XmlRootElement(name = "category")
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
@JsonPropertyOrder({ "ID", "url", "labels", "categories" })
public class MCRClassCategory {
@XmlElement(required = true)
protected List<MCRLabel> label;
protected MCRClassURL url;
protected List<MCRClassCategory> category;
@XmlAttribute(name = "ID", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String id;
@JsonGetter("labels")
public List<MCRLabel> getLabel() {
if (label == null) {
label = new ArrayList<>();
}
return this.label;
}
public MCRClassURL getUrl() {
return url;
}
public void setUrl(MCRClassURL value) {
this.url = value;
}
@JsonGetter("categories")
public List<MCRClassCategory> getCategory() {
if (category == null) {
category = new ArrayList<>();
}
return this.category;
}
@JsonGetter
public String getID() {
return id;
}
public void setID(String value) {
this.id = value;
}
public static MCRClassCategory getInstance(MCRCategory from) {
MCRClassCategory categ = new MCRClassCategory();
MCRCategoryID categoryID = from.getId();
categ.setID(categoryID.isRootID() ? categoryID.getRootID() : categoryID.getId());
categ.setUrl(MCRClassURL.getInstance(from.getURI()));
categ.getCategory()
.addAll(getInstance(from.getChildren()));
categ.getLabel()
.addAll(
from.getLabels()
.stream()
.map(MCRLabel::clone)
.collect(Collectors.toList()));
return categ;
}
public static List<MCRClassCategory> getInstance(List<MCRCategory> children) {
return children
.stream()
.map(MCRClassCategory::getInstance)
.collect(Collectors.toList());
}
}
| 3,866 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfo.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/objectinfo/MCRObjectInfo.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.datamodel.objectinfo;
import java.time.Instant;
import org.mycore.datamodel.metadata.MCRObjectID;
public interface MCRObjectInfo {
/**
* @return the object id
*/
MCRObjectID getId();
/**
* @return the project encoded in the object id
*/
String getObjectProject();
/**
* @return the type encoded in the object id
*/
String getObjectType();
/**
* @return the number encoded in the object id
*/
int getObjectNumber();
/**
* @return the creation date of the object
*/
Instant getCreateDate();
/**
* @return the last modify date of the object
*/
Instant getModifyDate();
/**
* @return the user which last modified the object
*/
String getModifiedBy();
/**
* @return returns the user which created the object.
*/
String getCreatedBy();
/**
* @return returns the user which deleted the object.
*/
String getDeletedBy();
/**
* @return the state classification category id e.G. state:submitted
*/
String getState();
/**
* @return the date when the object was deleted.
*/
Instant getDeleteDate();
}
| 1,946 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfoCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/objectinfo/MCRObjectInfoCommands.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.datamodel.objectinfo;
import java.io.IOException;
import java.util.List;
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.Document;
import org.jdom2.JDOMException;
import org.mycore.backend.jpa.objectinfo.MCRObjectInfoEntityManager;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
@MCRCommandGroup(name = "Object Info Commands")
public class MCRObjectInfoCommands {
private static final Logger LOGGER = LogManager.getLogger();
@MCRCommand(syntax = "remove all objectinfo",
help = "deletes the objectinfo for all objects")
public static void deleteAllObjectInfo() {
MCRObjectInfoEntityManager.removeAll();
}
@MCRCommand(syntax = "create all objectinfo",
help = "reads all objects and creates the corresponding objectinfo",
order = 10)
public static List<String> createAllObjectInfo() {
MCRXMLMetadataManager mm = MCRXMLMetadataManager.instance();
return mm.getObjectBaseIds()
.stream().filter(b -> !b.endsWith("derivate"))
.map(b -> "create objectinfo for base " + b)
.collect(Collectors.toList());
}
@MCRCommand(syntax = "create objectinfo for base {0}",
help = "reads all objects with base id {0} and creates the corresponding objectinfo")
public static List<String> createObjectInfoForBase(String baseId) {
String[] idParts = baseId.split("_");
MCRXMLMetadataManager mm = MCRXMLMetadataManager.instance();
if (idParts[1].equals("derivate")) {
return List.of();
}
int maxID = mm.getHighestStoredID(idParts[0], idParts[1]);
return IntStream.rangeClosed(1, maxID)
.mapToObj(n -> MCRObjectID.formatID(baseId, n))
.map(id -> "create objectinfo for object " + id)
.collect(Collectors.toList());
}
@MCRCommand(syntax = "create objectinfo for object {0}",
help = "creates the corresponding objectinfo for MCRObject {0}")
public static void createObjectInfoForObject(String idStr) {
MCRObjectID id = MCRObjectID.getInstance(idStr);
LogManager.getLogger().info("create objectinfo for object " + idStr);
if (id.getTypeId().equals("derivate")) {
return;
}
try {
if (MCRMetadataManager.exists(id)) {
MCRObjectInfoEntityManager.update(MCRMetadataManager.retrieveMCRObject(id));
LogManager.getLogger().info("objectinfo for object " + idStr + " created.");
} else {
List<? extends MCRAbstractMetadataVersion<?>> versions = MCRXMLMetadataManager.instance()
.listRevisions(id);
if (versions == null || versions.isEmpty()) {
// we do not know if the object ever existed
LOGGER.warn("Could not determine what happened to " + id);
} else {
MCRAbstractMetadataVersion<?> deleted = versions.get(versions.size() - 1);
MCRAbstractMetadataVersion<?> lastExisting = versions.get(versions.size() - 2);
try {
Document doc = lastExisting.retrieve().asXML();
MCRObject obj = new MCRObject(doc);
MCRObjectInfoEntityManager.update(obj);
MCRObjectInfoEntityManager.delete(obj,
deleted.getDate().toInstant(), deleted.getUser());
LogManager.getLogger().info("objectinfo for object " + idStr + " created.");
} catch (JDOMException e) {
LOGGER.warn("Could not determine what happened to " + id, e);
}
}
}
} catch (IOException e) {
LOGGER.error("Error while getting history of {}", id);
}
}
}
| 5,068 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfoEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/objectinfo/MCRObjectInfoEventHandler.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.datamodel.objectinfo;
import java.time.Instant;
import org.mycore.backend.jpa.objectinfo.MCRObjectInfoEntityManager;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRObject;
public class MCRObjectInfoEventHandler extends MCREventHandlerBase {
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
MCRObjectInfoEntityManager.update(obj);
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
MCRObjectInfoEntityManager.update(obj);
}
@Override
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
MCRObjectInfoEntityManager.remove(obj);
MCRObjectInfoEntityManager.create(obj);
}
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
MCRObjectInfoEntityManager.delete(obj, Instant.now(),
MCRSessionMgr.getCurrentSession().getUserInformation().getUserID());
}
}
| 1,821 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectQuery.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/objectinfo/MCRObjectQuery.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.datamodel.objectinfo;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* Used to Query a collection of mycore objects.
*/
public class MCRObjectQuery {
private MCRObjectID afterId = null;
private int offset = -1;
private int limit = -1;
private int numberGreater = -1;
private int numberLess = -1;
private String type = null;
private String project = null;
private String status = null;
private SortBy sortBy;
private SortOrder sortOrder;
private Instant modifiedBefore;
private Instant modifiedAfter;
private Instant createdBefore;
private Instant createdAfter;
private Instant deletedBefore;
private Instant deletedAfter;
private String createdBy;
private String modifiedBy;
private String deletedBy;
private final List<String> includeCategories = new ArrayList<>();
/**
* @return the id after which the listing starts
*/
public MCRObjectID afterId() {
return afterId;
}
/**
* modifies this query to only return object ids after lastId
* should not be used together with the {@link #sort(SortBy, SortOrder)} method
* @return this
*/
public MCRObjectQuery afterId(MCRObjectID lastId) {
this.afterId = lastId;
return this;
}
/**
* @return the amount of objects to skip from the start of the results
*/
public int offset() {
return offset;
}
/**
* modifies this query to skip the amount offset objects at the start of the results
* @param offset amount
* @return this
*/
public MCRObjectQuery offset(int offset) {
this.offset = offset;
return this;
}
/**
* @return the maximum amount of results
*/
public int limit() {
return limit;
}
/**
* modifies this query to limit the amount of results
* @param limit amount
* @return this
*/
public MCRObjectQuery limit(int limit) {
this.limit = limit;
return this;
}
/**
* @return the type restriction
*/
public String type() {
return type;
}
/**
* modifies this query to restrict the type of the objects
* @param type restriction
* @return this
*/
public MCRObjectQuery type(String type) {
this.type = type;
return this;
}
/**
* @return the project restriction
*/
public String project() {
return project;
}
/**
* modifies this query to restrict the project of the objects
* @param project restriction
* @return this
*/
public MCRObjectQuery project(String project) {
this.project = project;
return this;
}
/**
* @return the status restriction
*/
public String status() {
return status;
}
/**
* modifies this query to restrict the status of the objects. e.G. state:submitted
* @param status restriction
* @return this
*/
public MCRObjectQuery status(String status) {
this.status = status;
return this;
}
/**
* modifies this query to change the order of the resulting list
* @param sortBy the sort field
* @param sortOrder the sort direction
* @return this
*/
public MCRObjectQuery sort(SortBy sortBy, SortOrder sortOrder) {
this.sortOrder = sortOrder;
this.sortBy = sortBy;
return this;
}
/**
* @return the order field of the resulting list
*/
public SortBy sortBy() {
return sortBy;
}
/**
* @return the sort direction of the result list
*/
public SortOrder sortAsc() {
return sortOrder;
}
/**
* @return the upper bound limit of the modified date
*/
public Instant modifiedBefore() {
return modifiedBefore;
}
/**
* modifies this query to limit the upper bound of the modified date
* @param modifiedBefore the upper bound limit
* @return the same query
*/
public MCRObjectQuery modifiedBefore(Instant modifiedBefore) {
this.modifiedBefore = modifiedBefore;
return this;
}
/**
* @return the lower bound limit of the modifed date
*/
public Instant modifiedAfter() {
return modifiedAfter;
}
/**
* modifies this query to limit the lower bound of the modified date
* @param modifiedAfter the lower bound limit
* @return this
*/
public MCRObjectQuery modifiedAfter(Instant modifiedAfter) {
this.modifiedAfter = modifiedAfter;
return this;
}
/**
* @return the upper bound limit of the created date
*/
public Instant createdBefore() {
return createdBefore;
}
/**
* modifies this query to limit the upper bound of the created date
* @param createdBefore the upper bound limit
* @return this
*/
public MCRObjectQuery createdBefore(Instant createdBefore) {
this.createdBefore = createdBefore;
return this;
}
/**
* @return the lower bound limit of the created date
*/
public Instant createdAfter() {
return createdAfter;
}
/**
* modifies this query to limit the lower bound of the created date
* @param createdAfter the lower bound limit
* @return this
*/
public MCRObjectQuery createdAfter(Instant createdAfter) {
this.createdAfter = createdAfter;
return this;
}
/**
* @return the upper bound limit of the deleted date
*/
public Instant deletedBefore() {
return deletedBefore;
}
/**
* modifies this query to limit the upper bound of the deleted date
* @param deletedBefore the upper bound limit
* @return this
*/
public MCRObjectQuery deletedBefore(Instant deletedBefore) {
this.deletedBefore = deletedBefore;
return this;
}
/**
* @return the lower bound limit of the deleted date
*/
public Instant deletedAfter() {
return deletedAfter;
}
/**
* modifies this query to limit the lower bound of the deleted date
* @param deletedAfter the lower bound limit
* @return this
*/
public MCRObjectQuery deletedAfter(Instant deletedAfter) {
this.deletedAfter = deletedAfter;
return this;
}
/**
* @return the created by user restriction
*/
public String createdBy() {
return createdBy;
}
/**
* modifies this query to restrict the user which created the objects
* @param createdBy the user restriction
* @return this
*/
public MCRObjectQuery createdBy(String createdBy) {
this.createdBy = createdBy;
return this;
}
/**
* @return the modified by user restriction
*/
public String modifiedBy() {
return modifiedBy;
}
/**
* modifies this query to restrict the user which last modified the objects
* @param modifiedBy the user restriction
* @return this
*/
public MCRObjectQuery modifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
return this;
}
/**
* @return the deleted by user restriction
*/
public String deletedBy() {
return deletedBy;
}
/**
* modifies this query to restrict the user which deleted the objects
* @param deletedBy the user restriction
* @return this
*/
public MCRObjectQuery deletedBy(String deletedBy) {
this.deletedBy = deletedBy;
return this;
}
/**
* @return the lower bound limit to the object id number
*/
public int numberGreater() {
return numberGreater;
}
/**
* modifies this query to limit the lower bound of the object id number
* @param numberGreater the lower bound limit
* @return this
*/
public MCRObjectQuery numberGreater(int numberGreater) {
this.numberGreater = numberGreater;
return this;
}
/**
* @return the upper bound limit of the object id number
*/
public int numberLess() {
return numberLess;
}
/**
* modifies this query to limit the upper bound of the object id number
* @param numberLess the upper bound limit
* @return this
*/
public MCRObjectQuery numberLess(int numberLess) {
this.numberLess = numberLess;
return this;
}
/**
* @return a modifiable list of classification category ids. A result object need to be linked to all the
* categories.
*/
public List<String> getIncludeCategories() {
return includeCategories;
}
public enum SortBy {
id,
modified,
created
}
public enum SortOrder {
asc,
desc
}
@Override
public String toString() {
return "MCRObjectQuery{" +
"afterId=" + afterId +
", offset=" + offset +
", limit=" + limit +
", numberGreater=" + numberGreater +
", numberLess=" + numberLess +
", type='" + type + '\'' +
", project='" + project + '\'' +
", status='" + status + '\'' +
", sortBy=" + sortBy +
", sortOrder=" + sortOrder +
", modifiedBefore=" + modifiedBefore +
", modifiedAfter=" + modifiedAfter +
", createdBefore=" + createdBefore +
", createdAfter=" + createdAfter +
", deletedBefore=" + deletedBefore +
", deletedAfter=" + deletedAfter +
", createdBy='" + createdBy + '\'' +
", modifiedBy='" + modifiedBy + '\'' +
", deletedBy='" + deletedBy + '\'' +
", includeCategories=" + includeCategories +
'}';
}
}
| 10,688 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectQueryResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/objectinfo/MCRObjectQueryResolver.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.datamodel.objectinfo;
import java.util.List;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.common.MCRObjectIDDate;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* Allows to query objects using {@link MCRObjectQuery}.
*/
public interface MCRObjectQueryResolver {
/**
* Gets all object info which match the restrictions of the query
* @param objectQuery the query
* @return the ids of the objects
*/
List<MCRObjectID> getIds(MCRObjectQuery objectQuery);
/**
* Gets all the object info which match the restrictions of the query
* @param objectQuery the query
* @return the ids and dates of the object info
*/
List<MCRObjectIDDate> getIdDates(MCRObjectQuery objectQuery);
/**
* Gets all the object info which match the restrictions of the query
* @param objectQuery the query
* @return the info
*/
List<MCRObjectInfo> getInfos(MCRObjectQuery objectQuery);
/**
* Gets the count of object info which match the restrictions of query ignoring limit and offset
* @param objectQuery the query
* @return the count of the object info
*/
int count(MCRObjectQuery objectQuery);
static MCRObjectQueryResolver getInstance() {
return InstanceHolder.RESOLVER;
}
class InstanceHolder {
private static final String QUERY_RESOLVER_CLASS_PROPERTY = "MCR.Object.QueryResolver.Class";
private static final MCRObjectQueryResolver RESOLVER = MCRConfiguration2
.<MCRObjectQueryResolver>getSingleInstanceOf(QUERY_RESOLVER_CLASS_PROPERTY)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(QUERY_RESOLVER_CLASS_PROPERTY));
}
}
| 2,488 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRVersionedMetadata.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRVersionedMetadata.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.datamodel.ifs2;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.JDOMException;
import org.mycore.common.MCRUsageException;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.streams.MCRByteArrayOutputStream;
import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;
/**
* Represents an XML metadata document that is stored in a local filesystem
* store and in parallel in a Subversion repository to track and restore
* changes.
*
* @author Frank Lützenkirchen
*/
public class MCRVersionedMetadata extends MCRStoredMetadata {
/**
* The logger
*/
protected static final Logger LOGGER = LogManager.getLogger();
/**
* The revision number of the metadata version that is currently in the
* local filesystem store.
*/
protected Supplier<Optional<Long>> revision;
/**
* Creates a new metadata object both in the local store and in the SVN
* repository
*
* @param store
* the store this object is stored in
* @param fo
* the file storing the data in the local filesystem
* @param id
* the id of the metadata object
*/
MCRVersionedMetadata(MCRMetadataStore store, Path fo, int id, String docType, boolean deleted) {
super(store, fo, id, docType);
super.deleted = deleted;
revision = () -> {
try {
// 1. current revision, 2. deleted revision, empty()
return Optional.ofNullable(Optional.ofNullable(getStore().getRepository().info(getFilePath(), -1))
.map(SVNDirEntry::getRevision).orElseGet(this::getLastRevision));
} catch (SVNException e) {
LOGGER.error("Could not get last revision of {}_{}", getStore().getID(), id, e);
return Optional.empty();
}
};
}
@Override
public MCRVersioningMetadataStore getStore() {
return (MCRVersioningMetadataStore) store;
}
/**
* Stores a new metadata object first in the SVN repository, then
* additionally in the local store.
*
* @param xml
* the metadata document to store
* @throws JDOMException thrown by {@link MCRStoredMetadata#create(MCRContent)}
*/
@Override
void create(MCRContent xml) throws IOException, JDOMException {
super.create(xml);
commit("create");
}
/**
* Updates this metadata object, first in the SVN repository and then in the
* local store
*
* @param xml
* the new version of the document metadata
* @throws JDOMException thrown by {@link MCRStoredMetadata#create(MCRContent)}
*/
@Override
public void update(MCRContent xml) throws IOException, JDOMException {
if (isDeleted() || isDeletedInRepository()) {
create(xml);
} else {
super.update(xml);
commit("update");
}
}
void commit(String mode) throws IOException {
// Commit to SVN
SVNCommitInfo info;
try {
SVNRepository repository = getStore().getRepository();
// Check which paths already exist in SVN
String[] paths = store.getSlotPaths(id);
int existing = paths.length - 1;
for (; existing >= 0; existing--) {
if (!repository.checkPath(paths[existing], -1).equals(SVNNodeKind.NONE)) {
break;
}
}
existing += 1;
// Start commit editor
String commitMsg = mode + "d metadata object " + store.getID() + "_" + id + " in store";
ISVNEditor editor = repository.getCommitEditor(commitMsg, null);
editor.openRoot(-1);
// Create directories in SVN that do not exist yet
for (int i = existing; i < paths.length - 1; i++) {
LOGGER.debug("SVN create directory {}", paths[i]);
editor.addDir(paths[i], null, -1);
editor.closeDir();
}
// Commit file changes
String filePath = paths[paths.length - 1];
if (existing < paths.length) {
editor.addFile(filePath, null, -1);
} else {
editor.openFile(filePath, -1);
}
editor.applyTextDelta(filePath, null);
SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator();
String checksum;
try (InputStream in = Files.newInputStream(path)) {
checksum = deltaGenerator.sendDelta(filePath, in, editor, true);
}
if (store.shouldForceXML()) {
editor.changeFileProperty(filePath, SVNProperty.MIME_TYPE, SVNPropertyValue.create("text/xml"));
}
editor.closeFile(filePath, checksum);
editor.closeDir(); // root
info = editor.closeEdit();
} catch (SVNException e) {
throw new IOException(e);
}
revision = () -> Optional.of(info.getNewRevision());
LOGGER.info("SVN commit of {} finished, new revision {}", mode, getRevision());
if (MCRVersioningMetadataStore.shouldSyncLastModifiedOnSVNCommit()) {
setLastModified(info.getDate());
}
}
/**
* Deletes this metadata object in the SVN repository, and in the local
* store.
*/
@Override
public void delete() throws IOException {
if (isDeleted()) {
String msg = "You can not delete already deleted data: " + id;
throw new MCRUsageException(msg);
}
if (!store.exists(id)) {
throw new IOException("Does not exist: " + store.getID() + "_" + id);
}
getStore().delete(getID());
deleted = true;
}
public boolean isDeletedInRepository() throws IOException {
long rev = getRevision();
return rev >= 0 && getRevision(rev).getType() == MCRMetadataVersion.DELETED;
}
/**
* Updates the version stored in the local filesystem to the latest version
* from Subversion repository HEAD.
*/
public void update() throws Exception {
SVNRepository repository = getStore().getRepository();
MCRByteArrayOutputStream baos = new MCRByteArrayOutputStream();
long rev = repository.getFile(getFilePath(), -1, null, baos);
revision = () -> Optional.of(rev);
baos.close();
new MCRByteContent(baos.getBuffer(), 0, baos.size(), this.getLastModified().getTime()).sendTo(path);
}
/**
* Lists all versions of this metadata object available in the subversion
* repository
*
* @return all stored versions of this metadata object
*/
@SuppressWarnings("unchecked")
public List<MCRMetadataVersion> listVersions() throws IOException {
try {
List<MCRMetadataVersion> versions = new ArrayList<>();
SVNRepository repository = getStore().getRepository();
String path = getFilePath();
String dir = getDirectory();
Collection<SVNLogEntry> entries = null;
try {
entries = repository.log(new String[] { dir }, null, 0, repository.getLatestRevision(), true, true);
} catch (Exception ioex) {
LOGGER.error("Could not get versions", ioex);
return versions;
}
for (SVNLogEntry entry : entries) {
SVNLogEntryPath svnLogEntryPath = entry.getChangedPaths().get(path);
if (svnLogEntryPath != null) {
char type = svnLogEntryPath.getType();
versions.add(new MCRMetadataVersion(this, Long.toString(entry.getRevision()), entry.getAuthor(),
entry.getDate(), type));
}
}
return versions;
} catch (SVNException svnExc) {
throw new IOException(svnExc);
}
}
private String getFilePath() {
return "/" + store.getSlotPath(id);
}
private String getDirectory() {
String path = getFilePath();
return path.substring(0, path.lastIndexOf('/'));
}
public MCRMetadataVersion getRevision(long revision) throws IOException {
try {
if (revision < 0) {
revision = getLastPresentRevision();
if (revision < 0) {
LOGGER.warn("Metadata object {} in store {} has no last revision!", getID(), getStore().getID());
return null;
}
}
SVNRepository repository = getStore().getRepository();
String path = getFilePath();
String dir = getDirectory();
@SuppressWarnings("unchecked")
Collection<SVNLogEntry> log = repository.log(new String[] { dir }, null, revision, revision, true, true);
for (SVNLogEntry logEntry : log) {
SVNLogEntryPath svnLogEntryPath = logEntry.getChangedPaths().get(path);
if (svnLogEntryPath != null) {
char type = svnLogEntryPath.getType();
return new MCRMetadataVersion(this, Long.toString(logEntry.getRevision()), logEntry.getAuthor(),
logEntry.getDate(), type);
}
}
LOGGER.warn("Metadata object {} in store {} has no revision ''{}''!", getID(), getStore().getID(),
getRevision());
return null;
} catch (SVNException svnExc) {
throw new IOException(svnExc);
}
}
public long getLastPresentRevision() throws SVNException {
return getLastRevision(false);
}
private long getLastRevision(boolean deleted) throws SVNException {
SVNRepository repository = getStore().getRepository();
if (repository.getLatestRevision() == 0) {
//new repository cannot hold a revision yet (MCR-1196)
return -1;
}
final String path = getFilePath();
String dir = getDirectory();
LastRevisionLogHandler lastRevisionLogHandler = new LastRevisionLogHandler(path, deleted);
int limit = 0; //we stop through LastRevisionFoundException
try {
repository.log(new String[] { dir }, repository.getLatestRevision(), 0, true, true, limit, false, null,
lastRevisionLogHandler);
} catch (LastRevisionFoundException ignored) {
}
return lastRevisionLogHandler.getLastRevision();
}
private Long getLastRevision() {
try {
long lastRevision = getLastRevision(true);
return lastRevision < 0 ? null : lastRevision;
} catch (SVNException e) {
LOGGER.warn("Could not get last revision of: {}_{}", getStore(), id, e);
return null;
}
}
/**
* Returns the revision number of the version currently stored in the local
* filesystem store.
*
* @return the revision number of the local version
*/
public long getRevision() {
return revision.get().orElse(-1L);
}
/**
* Checks if the version in the local store is up to date with the latest
* version in SVN repository
*
* @return true, if the local version in store is the latest version
*/
public boolean isUpToDate() throws IOException {
SVNDirEntry entry;
try {
SVNRepository repository = getStore().getRepository();
entry = repository.info(getFilePath(), -1);
} catch (SVNException e) {
throw new IOException(e);
}
return entry.getRevision() <= getRevision();
}
private static final class LastRevisionFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
private static final class LastRevisionLogHandler implements ISVNLogEntryHandler {
private final String path;
long lastRevision = -1;
private boolean deleted;
private LastRevisionLogHandler(String path, boolean deleted) {
this.path = path;
this.deleted = deleted;
}
@Override
public void handleLogEntry(SVNLogEntry logEntry) {
SVNLogEntryPath svnLogEntryPath = logEntry.getChangedPaths().get(path);
if (svnLogEntryPath != null) {
char type = svnLogEntryPath.getType();
if (deleted || type != SVNLogEntryPath.TYPE_DELETED) {
lastRevision = logEntry.getRevision();
//no other way to stop svnkit from logging
throw new LastRevisionFoundException();
}
}
}
long getLastRevision() {
return lastRevision;
}
}
}
| 14,488 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRVirtualNode.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRVirtualNode.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.datamodel.ifs2;
import java.nio.file.Path;
/**
* A virtual node in a file collection, which may be a child node of a container
* file type like zip or tar. Such files can be browsed and read using this node
* type.
*
* @author Frank Lützenkirchen
*/
public class MCRVirtualNode extends MCRNode {
/**
* Creates a new virtual node
*
* @param parent
* the parent node containing this node
* @param fo
* the file object in Apache VFS representing this node
*/
protected MCRVirtualNode(MCRNode parent, Path fo) {
super(parent, fo);
}
/**
* Returns a virtual node that is a child of this virtual node.
*/
@Override
protected MCRVirtualNode buildChildNode(Path fo) {
return new MCRVirtualNode(this, fo);
}
}
| 1,570 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoreDefaultConfig.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRStoreDefaultConfig.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.datamodel.ifs2;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.ifs2.MCRStore.MCRStoreConfig;
class MCRStoreDefaultConfig implements MCRStoreConfig {
private String storeConfigPrefix;
private String id;
MCRStoreDefaultConfig(String id) {
this.id = id;
storeConfigPrefix = "MCR.IFS2.Store." + id + ".";
}
@Override
public String getBaseDir() {
return MCRConfiguration2.getStringOrThrow(storeConfigPrefix + "BaseDir");
}
@Override
public String getPrefix() {
return MCRConfiguration2.getString(storeConfigPrefix + "Prefix").orElse(id + "_");
}
@Override
public String getSlotLayout() {
return MCRConfiguration2.getStringOrThrow(storeConfigPrefix + "SlotLayout");
}
@Override
public String getID() {
return id;
}
}
| 1,610 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDirectory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRDirectory.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.datamodel.ifs2;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.stream.Stream;
import org.jdom2.Element;
/**
* Represents a directory stored in a file collection, which may contain other
* files and directories.
*
* @author Frank Lützenkirchen
*/
public class MCRDirectory extends MCRStoredNode {
/**
* Create MCRDirectory representing an existing, already stored directory.
*
* @param parent
* the parent directory of this directory
* @param fo
* the local directory in the store storing this directory
*/
protected MCRDirectory(MCRDirectory parent, Path fo, Element data) {
super(parent, fo, data);
}
/**
* Create a new MCRDirectory that does not exist yet
*
* @param parent
* the parent directory of this directory
* @param name
* the name of the new subdirectory to create
*/
protected MCRDirectory(MCRDirectory parent, String name) throws IOException {
super(parent, name, "dir");
Files.createDirectory(path);
getRoot().saveAdditionalData();
}
/**
* Creates a new subdirectory within this directory
*
* @param name
* the name of the new directory
*/
public MCRDirectory createDir(String name) throws IOException {
return new MCRDirectory(this, name);
}
/**
* Creates a new file within this directory
*
* @param name
* the name of the new file
*/
public MCRFile createFile(String name) throws IOException {
return new MCRFile(this, name);
}
@SuppressWarnings("unchecked")
private Element getChildData(String name) {
for (Element child : readData(Element::getChildren)) {
if (name.equals(child.getAttributeValue("name"))) {
return child;
}
}
Element childData = new Element("node");
childData.setAttribute("name", name);
writeData(e -> e.addContent(childData));
return childData;
}
/**
* Returns the MCRFile or MCRDirectory that is represented by the given
* FileObject, which is a direct child of the directory FileObject this
* MCRDirectory is stored in.
*
* @return an MCRFile or MCRDirectory child
*/
@Override
protected MCRStoredNode buildChildNode(Path fo) {
if (fo == null) {
return null;
}
if (!this.path.equals(fo.getParent())) {
throw new IllegalArgumentException(fo + " is not a direct child of " + this.path + ".");
}
BasicFileAttributes attrs;
try {
attrs = Files.readAttributes(fo, BasicFileAttributes.class);
} catch (IOException e) {
//does not exist
return null;
}
Element childData = getChildData(fo.getFileName().toString());
if (attrs.isRegularFile()) {
return new MCRFile(this, fo, childData);
} else {
return new MCRDirectory(this, fo, childData);
}
}
/**
* Repairs additional metadata of this directory and all its children
*/
@Override
@SuppressWarnings("unchecked")
void repairMetadata() throws IOException {
writeData(e -> {
e.setName("dir");
e.setAttribute("name", getName());
for (Element childEntry : e.getChildren()) {
childEntry.setName("node");
}
});
try (Stream<MCRNode> streamMCRNode = getChildren()) {
streamMCRNode.filter(MCRStoredNode.class::isInstance)
.map(MCRStoredNode.class::cast)
.sequential()
.forEach(mcrStoredNode -> {
try {
mcrStoredNode.repairMetadata();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
} catch (UncheckedIOException e) {
throw e.getCause();
}
writeData(e -> e.removeChildren("node"));
}
}
| 5,036 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRStore.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.datamodel.ifs2;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.StringTokenizer;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter;
/**
* Stores metadata files or file collections containing files and directories in
* a persistent store implemented using a local filesystem.
*
* For better filesystem performance, the store can build slot subdirectories
* (containing other subdirectories and so on) so that not all objects are
* stored in the same filesystem directory. Directories containing a very large
* number of files typically show bad performance.
*
* The slot layout of the store defines the usage of subdirectories within the
* base directory. A layout of "8" would mean no subdirectories will be used,
* the maximum ID size is 8 digits, and therefore up to 99999999 objects can be
* stored all in the same base directory. A layout of "2-2-4" would mean data is
* stored using two levels of subdirectories, where the first subdirectory
* contains up to 100 (00-99) subdirectories, the second subdirectory level
* below contains up to 100 subdirectories, too, and below the data is stored,
* with up to 10000 data objects in the subdirectory. Using this slot layout,
* the data of ID 10485 would be stored in the file object "/00/01/00010485",
* for example. Using layout "4-2-2", data would be stored in
* "/0001/04/00010485", and so on.
*
* The slot file name itself may optionally have a prefix and suffix. With
* prefix "derivate-", the slot name would be "derivate-00010485". With prefix
* "DocPortal_document_" and suffix ".xml", the slot name would be
* "DocPortal_document_00010485.xml" for example.
*
* MCR.IFS2.Store.ID.Class=org.mycore.datamodel.ifs2.MCRFileStore
* MCR.IFS2.Store.ID.BaseDir=/foo/bar
* MCR.IFS2.Store.ID.SlotLayout=4-2-2
*
* @author Frank Lützenkirchen
*/
public abstract class MCRStore {
/**
* Indicates ascending order when listing IDs
*/
public static final boolean ASCENDING = true;
/**
* Indicates descending order when listing IDs
*/
public static final boolean DESCENDING = false;
/** The ID of the store */
protected String id;
/** The base directory containing the stored data */
protected Path baseDirectory;
/** The maximum length of IDs **/
protected int idLength;
/**
* The slot subdirectory layout, which is the number of digits used at each
* subdirectory level to build the filename.
*/
protected int[] slotLength;
/** The prefix of slot names */
protected String prefix = "";
/** The suffix of slot names */
protected String suffix = "";
private MCRStoreConfig storeConfig;
private Function<String, String> toNativePath;
/**
* Offset to add to the maximum ID found in the store to build the new ID.
* This is normally 1, but initially higher to avoid reassigning the same ID
* after system restarts. Consider the following example:
*
* 1) User creates new document, ID assigned is 10. 2) User deletes document
* 10. 3) Web application is restarted. 4) User creates new document, ID
* assigned is 20. If offset would always be 1, ID assigned would have been
* 10 again, and that is not nice, because we can not distinguish the two
* creates easily.
*/
protected int offset = 11; // Sicherheitsabstand, initially 11, later 1
/**
* The last ID assigned by this store.
*/
protected int lastID = 0;
public static final Logger LOGGER = LogManager.getLogger();
/**
* Deletes the data stored under the given ID from the store
*
* @param id
* the ID of the document to be deleted
*/
public void delete(final int id) throws IOException {
delete(getSlot(id));
}
/**
* Returns true if data for the given ID is existing in the store.
*
* @param id
* the ID of the data
* @return true, if data for the given ID is existing in the store.
*/
public boolean exists(final int id) {
return Files.exists(getSlot(id));
}
public synchronized int getHighestStoredID() {
try {
String max = findMaxID(baseDirectory, 0);
if (max != null) {
return slot2id(max);
}
} catch (final IOException e) {
LOGGER.error("Error while getting highest stored ID in " + baseDirectory, e);
}
return 0;
}
/**
* Returns the ID of this store
*/
public String getID() {
return getStoreConfig().getID();
}
/**
* Returns the next free ID that can be used to store data. Call as late as
* possible to avoid that another process, for example from batch import, in
* the meantime already used that ID.
*
* @return the next free ID that can be used to store data
*/
public synchronized int getNextFreeID() {
lastID = Math.max(getHighestStoredID(), lastID);
lastID += lastID > 0 ? offset : 1;
offset = 1;
return lastID;
}
public boolean isEmpty() {
try (Stream<Path> streamBaseDirectory = Files.list(baseDirectory)) {
return streamBaseDirectory.findAny().isEmpty();
} catch (final IOException e) {
LOGGER.error("Error while checking if base directory is empty: " + baseDirectory, e);
return false;
}
}
/**
* @return all Ids of this store
*/
public IntStream getStoredIDs() {
int characteristics = Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED;
return StreamSupport
.stream(() -> Spliterators
.spliteratorUnknownSize(listIDs(ASCENDING), characteristics),
characteristics,
false)
.mapToInt(Integer::intValue);
}
/**
* Lists all IDs currently used in the store, in ascending or descending
* order
*
* @see #ASCENDING
* @see #DESCENDING
*
* @param order
* the order in which IDs should be returned.
* @return all IDs currently used in the store
*/
public Iterator<Integer> listIDs(final boolean order) {
return new Iterator<Integer>() {
/**
* List of files or directories in store not yet handled
*/
List<Path> files = new ArrayList<>();
/**
* The next ID to return, when 0, all IDs have been returned
*/
int nextID;
/**
* The last ID that was returned
*/
int lastID;
/**
* The order in which the IDs should be returned, ascending or
* descending
*/
boolean order;
@Override
public boolean hasNext() {
return nextID > 0;
}
@Override
public Integer next() {
if (nextID < 1) {
throw new NoSuchElementException();
}
lastID = nextID;
nextID = findNextID();
return lastID;
}
@Override
public void remove() {
if (lastID == 0) {
throw new IllegalStateException();
}
try {
MCRStore.this.delete(lastID);
} catch (final Exception ex) {
throw new MCRException("Could not delete " + MCRStore.this.getID() + " " + lastID, ex);
}
lastID = 0;
}
/**
* Initializes the enumeration and searches for the first ID to
* return
*
* @param order
* the return order, ascending or descending
*/
Iterator<Integer> init(final boolean order) {
this.order = order;
try {
addChildren(baseDirectory);
} catch (final IOException e) {
LOGGER.error("Error while iterating over children of " + baseDirectory, e);
}
nextID = findNextID();
return this;
}
/**
* Adds children of the given directory to the list of files to
* handle next. Depending on the return sort order, ascending or
* descending file name order is used.
*
* @param dir
* the directory thats children should be added
*/
private void addChildren(final Path dir) throws IOException {
if (Files.isDirectory(dir)) {
try (Stream<Path> steamDir = Files.list(dir)) {
final Path[] children = steamDir.toArray(Path[]::new);
Arrays.sort(children, new MCRPathComparator());
for (int i = 0; i < children.length; i++) {
files.add(order ? i : 0, children[i]);
}
}
}
}
/**
* Finds the next ID used in the store.
*
* @return the next ID, or 0 if there is no other ID any more
*/
private int findNextID() {
if (files.isEmpty()) {
return 0;
}
final Path first = files.remove(0);
// checks basename length against prefix (projectId_typeId), file suffix (.xml) and configured id length
// if they match it should be a parseable id
String fileName = first.getFileName().toString();
if (fileName.length() == idLength + prefix.length() + suffix.length()) {
return MCRStore.this.slot2id(fileName);
}
try {
addChildren(first);
} catch (final IOException e) {
LOGGER.error("Error while finding next id.", e);
}
return findNextID();
}
}.init(order);
}
/**
* Deletes the data stored in the given file object from the store
*
* @see <a href="https://stackoverflow.com/questions/39628328/trying-to-create-a-directory-immediately-after-a-successful-deleteifexists-throw">stackoverflow</a>
* @param path
* the file object to be deleted
*/
void delete(final Path path) throws IOException {
if (!path.startsWith(baseDirectory)) {
throw new IllegalArgumentException(path + " is not in the base directory " + baseDirectory);
}
Path current = path;
Path parent = path.getParent();
Files.walkFileTree(path, MCRRecursiveDeleter.instance());
while (!Files.isSameFile(baseDirectory, parent)) {
// Prevent access denied error in windows with closing the stream correctly
try (Stream<Path> streamParent = Files.list(parent)) {
if (streamParent.findAny().isPresent()) {
break;
}
current = parent;
parent = current.getParent();
Files.delete(current);
}
}
}
/**
* @return the absolute path of the local base directory
*/
public Path getBaseDirectory() {
return baseDirectory.toAbsolutePath();
}
/**
* Returns the absolute path of the local base directory
*
* @return the base directory storing the data
*/
String getBaseDirURI() {
return baseDirectory.toAbsolutePath().toUri().toString();
}
/** Returns the maximum length of any ID stored in this store */
int getIDLength() {
return idLength;
}
/**
* Returns the relative path used to store data for the given id within the
* store base directory
*
* @param id
* the id of the data
* @return the relative path storing that data
*/
String getSlotPath(final int id) {
final String[] paths = getSlotPaths(id);
return paths[paths.length - 1];
}
/**
* Returns the paths of all subdirectories and the slot itself used to store
* data for the given id relative to the store base directory
*
* @param id
* the id of the data
* @return the directory and file names of the relative path storing that
* data
*/
String[] getSlotPaths(final int id) {
final String paddedId = createIDWithLeadingZeros(id);
final String[] paths = new String[slotLength.length + 1];
final StringBuilder path = new StringBuilder();
int offset = 0;
for (int i = 0; i < paths.length - 1; i++) {
path.append(paddedId, offset, offset + slotLength[i]);
paths[i] = path.toString();
path.append('/');
offset += slotLength[i];
}
path.append(prefix).append(paddedId).append(suffix);
paths[paths.length - 1] = path.toString();
return paths;
}
/**
* Extracts the numerical ID contained in the slot filename.
*
* @param slot
* the file name of the slot containing the data
* @return the ID of that data
*/
int slot2id(String slot) {
slot = slot.substring(prefix.length());
slot = slot.substring(0, idLength);
return Integer.parseInt(slot);
}
/**
* Returns the slot file object used to store data for the given id. This
* may be a file or directory, depending on the subclass of MCRStore that is
* used.
*
* @param id
* the id of the data
* @return the file object storing that data
*/
protected Path getSlot(final int id) {
String slotPath = getSlotPath(id);
return baseDirectory.resolve(toNativePath.apply(slotPath));
}
protected MCRStoreConfig getStoreConfig() {
return storeConfig;
}
protected void init(final MCRStoreConfig config) {
setStoreConfig(config);
idLength = 0;
final StringTokenizer st = new StringTokenizer(getStoreConfig().getSlotLayout(), "-");
slotLength = new int[st.countTokens() - 1];
int i = 0;
while (st.countTokens() > 1) {
slotLength[i] = Integer.parseInt(st.nextToken());
idLength += slotLength[i++];
}
idLength += Integer.parseInt(st.nextToken());
prefix = config.getPrefix();
try {
try {
URI uri = new URI(getStoreConfig().getBaseDir());
if (uri.getScheme() != null) {
baseDirectory = Paths.get(uri);
}
} catch (URISyntaxException e) {
//not a uri, handle as relative path
}
if (baseDirectory == null) {
baseDirectory = Paths.get(getStoreConfig().getBaseDir());
}
String separator = baseDirectory.getFileSystem().getSeparator();
if (separator.equals("/")) {
toNativePath = s -> s;
} else {
toNativePath = s -> {
if (s.contains("/")) {
if (s.contains(separator)) {
throw new IllegalArgumentException(
s + " may not contain both '/' and '" + separator + "'.");
}
return s.replace("/", separator);
}
return s;
};
}
try {
BasicFileAttributes attrs = Files.readAttributes(baseDirectory, BasicFileAttributes.class);
if (!attrs.isDirectory()) {
final String msg = "Store " + getStoreConfig().getBaseDir() + " is not a directory";
throw new MCRConfigurationException(msg);
}
if (!Files.isReadable(baseDirectory)) {
final String msg = "Store directory " + getStoreConfig().getBaseDir() + " is not readable";
throw new MCRConfigurationException(msg);
}
} catch (IOException e) {
//does not exist;
Files.createDirectories(baseDirectory);
}
} catch (final IOException e) {
LOGGER.error("Could not initialize store " + config.getID() + " correctly.", e);
}
}
/**
* Initializes a new store instance
*/
protected void init(final String id) {
init(new MCRStoreDefaultConfig(id));
}
protected void setStoreConfig(final MCRStoreConfig storeConfig) {
this.storeConfig = storeConfig;
}
private String createIDWithLeadingZeros(final int id) {
final NumberFormat numWithLeadingZerosFormat = NumberFormat.getIntegerInstance(Locale.ROOT);
numWithLeadingZerosFormat.setMinimumIntegerDigits(idLength);
numWithLeadingZerosFormat.setGroupingUsed(false);
return numWithLeadingZerosFormat.format(id);
}
/**
* Recursively searches for the highest ID, which is the greatest slot file
* name currently used in the store.
*
* @param dir
* the directory to search
* @param depth
* the subdirectory depth level of the dir
* @return the highest slot file name / ID currently stored
*/
private String findMaxID(final Path dir, final int depth) throws IOException {
final Path[] children;
try (Stream<Path> streamDirectory = Files.list(dir)) {
children = streamDirectory.toArray(Path[]::new);
}
if (children.length == 0) {
return null;
}
Arrays.sort(children, new MCRPathComparator());
if (depth == slotLength.length) {
return children[children.length - 1].getFileName().toString();
}
for (int i = children.length - 1; i >= 0; i--) {
final Path child = children[i];
try (Stream<Path> streamChild = Files.list(child)) {
if (!Files.isDirectory(child) || streamChild.findAny().isEmpty()) {
continue;
}
}
final String found = findMaxID(child, depth + 1);
if (found != null) {
return found;
}
}
return null;
}
public interface MCRStoreConfig {
String getBaseDir();
String getID();
String getPrefix();
String getSlotLayout();
}
}
| 20,370 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoreManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRStoreManager.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.datamodel.ifs2;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.datamodel.ifs2.MCRStore.MCRStoreConfig;
public class MCRStoreManager {
private static final Logger LOGGER = LogManager.getLogger(MCRStoreManager.class);
public static <T extends MCRStore> T createStore(String id, Class<T> storeClass)
throws ReflectiveOperationException {
return createStore(new MCRStoreDefaultConfig(id), storeClass);
}
public static <T extends MCRStore> T createStore(MCRStoreConfig config, Class<T> storeClass)
throws ReflectiveOperationException {
T store = storeClass.getDeclaredConstructor().newInstance();
store.init(config);
try {
LOGGER.info("Adding instance of {} as MCRStore '{}'.", storeClass.getSimpleName(), store.getID());
MCRStoreCenter.instance().addStore(store.getID(), store);
} catch (Exception e) {
throw new MCRException("Could not create store with ID " + config.getID() + ", store allready exists");
}
return store;
}
/**
* Returns the store with the given id
*
* @param id
* the ID of the store
*/
public static <T extends MCRStore> T getStore(String id) {
return MCRStoreCenter.instance().getStore(id);
}
/**
* @deprecated use {@link #getStore(String)} instead
*/
@Deprecated
public static <T extends MCRStore> T getStore(String id, Class<T> storeClass) {
return MCRStoreCenter.instance().getStore(id, storeClass);
}
public static void removeStore(String id) {
LOGGER.info("Remove MCRStore '{}'.", id);
MCRStoreCenter.instance().removeStore(id);
}
}
| 2,546 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNode.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRNode.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.datamodel.ifs2;
import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.stream.Stream;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRPathContent;
/**
* Represents a file, directory or file collection within a file store. Files
* and directories can be either really stored, or virtually existing as a child
* node contained within a stored container file like zip or tar.
*
* @author Frank Lützenkirchen
*/
public abstract class MCRNode {
/**
* The path object representing this node in the underlying filesystem.
*/
protected Path path;
/**
* The parent node owning this file, a directory or container file
*/
protected MCRNode parent;
/**
* Creates a new node representing a child of the given parent
*
* @param parent
* the parent node
* @param path
* the file object representing this node in the underlying
* filesystem
*/
protected MCRNode(MCRNode parent, Path path) {
this.path = path;
this.parent = parent;
}
/**
* Returns the file or directory name
*
* @return the node's filename
*/
public String getName() {
return path.getFileName().toString();
}
/**
* Returns the complete path of this node up to the root file collection.
* Path always start with a slash, slash is used as directory delimiter.
*
* @return the absolute path of this node
*/
public String getPath() {
if (parent != null) {
if (parent.parent == null) {
return "/" + getName();
} else {
return parent.getPath() + "/" + getName();
}
} else {
return "/";
}
}
/**
* Returns the parent node containing this node
*
* @return the parent directory or container file
*/
public MCRNode getParent() {
return parent;
}
/**
* Returns the root file collection this node belongs to
*
* @return the root file collection
*/
public MCRFileCollection getRoot() {
return parent.getRoot();
}
/**
* Returns true if this node is a file
*
* @return true if this node is a file
*/
public boolean isFile() {
return Files.isRegularFile(path);
}
/**
* Returns true if this node is a directory
*
* @return true if this node is a directory
*/
public boolean isDirectory() {
return Files.isDirectory(path);
}
/**
* For file nodes, returns the file content size in bytes, otherwise returns
* 0.
*
* @return the file size in bytes
*/
public long getSize() throws IOException {
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
return attr.isRegularFile() ? attr.size() : 0;
}
/**
* Returns the time this node was last modified.
*
* @return the time this node was last modified
*/
public Date getLastModified() throws IOException {
return Date.from(Files.getLastModifiedTime(path).toInstant());
}
/**
* Returns true if this node has child nodes. Directories and container
* files like zip or tar may have child nodes.
*
* @return true if children exist
*/
public boolean hasChildren() throws IOException {
return !isFile() && Files.list(path).findAny().isPresent();
}
/**
* Returns the number of child nodes of this node.
*
* @return the number of child nodes of this node.
*/
public int getNumChildren() throws IOException {
if (isFile()) {
return 0;
}
try (Stream<Path> streamPath = Files.list(path)) {
return Math.toIntExact(streamPath.count());
}
}
/**
* Returns the children of this node.
*
* @return a List of child nodes, which may be empty, in undefined order
*/
public Stream<MCRNode> getChildren() throws IOException {
if (isFile()) {
return Stream.empty();
}
return Files.list(path)
.map(this::buildChildNode);
}
/**
* Creates a node instance for the given FileObject, which represents the
* child
*
* @param fo
* the FileObject representing the child in the underlying
* filesystem
* @return the child node or null, if the fo does not exists
* @throws IllegalArgumentException if fo is not valid path for a child of this
*/
protected abstract MCRNode buildChildNode(Path fo);
/**
* Returns the child node with the given filename, or null
*
* @param name
* the name of the child node
* @return the child node with that name, or null when no such file exists
*/
public MCRNode getChild(String name) {
Path child = path.resolve(name);
return buildChildNode(child);
}
/**
* Returns the node with the given relative or absolute path in the file
* collection this node belongs to. Slash is used as directory delimiter.
* When the path starts with a slash, it is an absolute path and resolving
* is startet at the root file collection. When the path is relative,
* resolving starts with the current node. One dot represents the current
* node, Two dots represent the parent node, like in paths used by typical
* real filesystems.
*
* @param path
* the absolute or relative path of the node to find, may contain
* . or ..
* @return the node at the given path, or null
*/
public MCRNode getNodeByPath(String path) {
MCRNode current = path.startsWith("/") ? getRoot() : this;
StringTokenizer st = new StringTokenizer(path, "/");
while (st.hasMoreTokens() && current != null) {
String name = st.nextToken();
if (name.equals(".")) {
continue;
}
if (name.equals("..")) {
current = current.getParent();
} else {
current = current.getChild(name);
}
}
return current;
}
/**
* Returns the content of this node for output. For a directory, it will
* return null.
*
* @return the content of the file
*/
public MCRContent getContent() throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return attrs.isRegularFile() ? doGetContent(attrs) : null;
}
private MCRPathContent doGetContent(BasicFileAttributes attrs) {
return new MCRPathContent(path, attrs);
}
/**
* Returns the content of this node for random access read. Be sure not to
* write to the node using the returned object, use just for reading! For a
* directory, it will return null.
*
* @return the content of this file, for random access
*/
public SeekableByteChannel getRandomAccessContent() throws IOException {
return isFile() ? Files.newByteChannel(path, StandardOpenOption.READ) : null;
}
}
| 8,251 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRVersioningMetadataStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRVersioningMetadataStore.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.datamodel.ifs2;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.Iterator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.JDOMException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRContent;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.BasicAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNUserNameAuthentication;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.admin.ISVNAdminEventHandler;
import org.tmatesoft.svn.core.wc.admin.SVNAdminClient;
import org.tmatesoft.svn.core.wc.admin.SVNAdminEvent;
/**
* Stores metadata objects both in a local filesystem structure and in a
* Subversion repository. Changes can be tracked and restored. To enable
* versioning, configure the repository URL, for example
*
* MCR.IFS2.Store.DocPortal_document.SVNRepositoryURL=file:///foo/svnroot/
*
* @author Frank Lützenkirchen
*/
public class MCRVersioningMetadataStore extends MCRMetadataStore {
protected static final Logger LOGGER = LogManager.getLogger(MCRVersioningMetadataStore.class);
protected SVNURL repURL;
protected static final boolean SYNC_LAST_MODIFIED_ON_SVN_COMMIT = MCRConfiguration2
.getBoolean("MCR.IFS2.SyncLastModifiedOnSVNCommit").orElse(true);
static {
FSRepositoryFactory.setup();
}
@Override
protected void init(String type) {
super.init(type);
setupSVN(type);
}
@Override
protected void init(MCRStoreConfig config) {
super.init(config);
setupSVN(config.getID());
}
private void setupSVN(String type) {
URI repositoryURI;
String repositoryURIString = MCRConfiguration2.getStringOrThrow("MCR.IFS2.Store." + type + ".SVNRepositoryURL");
try {
repositoryURI = new URI(repositoryURIString);
} catch (URISyntaxException e) {
String msg = "Syntax error in MCR.IFS2.Store." + type + ".SVNRepositoryURL property: "
+ repositoryURIString;
throw new MCRConfigurationException(msg, e);
}
try {
LOGGER.info("Versioning metadata store {} repository URL: {}", type, repositoryURI);
repURL = SVNURL.create(repositoryURI.getScheme(), repositoryURI.getUserInfo(), repositoryURI.getHost(),
repositoryURI.getPort(), repositoryURI.getPath(), true);
LOGGER.info("repURL: {}", repURL);
File dir = new File(repURL.getPath());
if (!dir.exists() || (dir.isDirectory() && dir.list().length == 0)) {
LOGGER.info("Repository does not exist, creating new SVN repository at {}", repositoryURI);
repURL = SVNRepositoryFactory.createLocalRepository(dir, true, false);
}
} catch (SVNException ex) {
String msg = "Error initializing SVN repository at URL " + repositoryURI;
throw new MCRConfigurationException(msg, ex);
}
}
/**
* When metadata is saved, this results in SVN commit. If the property
* MCR.IFS2.SyncLastModifiedOnSVNCommit=true (which is default), the
* last modified date of the metadata file in the store will be set to the exactly
* same timestamp as the SVN commit. Due to permission restrictions on Linux systems,
* this may fail, so you can disable that behaviour.
*
* @return true, if last modified of file should be same as timestamp of SVN commit
*/
public static boolean shouldSyncLastModifiedOnSVNCommit() {
return SYNC_LAST_MODIFIED_ON_SVN_COMMIT;
}
/**
* Returns the SVN repository used to manage metadata versions in this
* store.
*
* @return the SVN repository used to manage metadata versions in this
* store.
*/
SVNRepository getRepository() throws SVNException {
SVNRepository repository = SVNRepositoryFactory.create(repURL);
String user = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
SVNAuthentication[] auth = {
SVNUserNameAuthentication.newInstance(user, false, repURL, false) };
BasicAuthenticationManager authManager = new BasicAuthenticationManager(auth);
repository.setAuthenticationManager(authManager);
return repository;
}
/**
* Returns the URL of the SVN repository used to manage metadata versions in
* this store.
*
* @return the URL of the SVN repository used to manage metadata versions in
* this store.
*/
SVNURL getRepositoryURL() {
return repURL;
}
/**
* Checks to local SVN repository for errors
* @throws MCRPersistenceException if 'svn verify' fails
*/
public void verify() throws MCRPersistenceException {
String replURLStr = repURL.toString();
if (!repURL.getProtocol().equals("file")) {
LOGGER.warn("Cannot verify non local SVN repository '{}'.", replURLStr);
return;
}
try {
SVNRepository repository = getRepository();
long latestRevision = repository.getLatestRevision();
if (latestRevision == 0) {
LOGGER.warn("Cannot verify SVN repository '{}' with no revisions.", replURLStr);
}
ISVNAuthenticationManager authenticationManager = repository.getAuthenticationManager();
SVNAdminClient adminClient = new SVNAdminClient(authenticationManager, null);
File repositoryRoot = new File(URI.create(replURLStr));
adminClient.setEventHandler(new ISVNAdminEventHandler() {
//if more than batchSize revisions print progress
int batchSize = 100;
@Override
public void checkCancelled() {
//run till the end
}
@Override
public void handleEvent(SVNEvent event, double progress) {
//we do nothing, just browsing the history
}
@Override
public void handleAdminEvent(SVNAdminEvent event, double progress) {
if (event.getMessage() != null) {
if (event.getRevision() % batchSize != 0 || event.getRevision() == 0) {
LOGGER.debug(event::getMessage);
} else {
LOGGER.info("{} ({}% done)", event.getMessage(),
(int) (event.getRevision() * 100.0 / latestRevision));
}
}
}
});
adminClient.doVerify(repositoryRoot);
LOGGER.info("Verified SVN repository '{}'.", replURLStr);
} catch (Exception e) {
throw new MCRPersistenceException("SVN repository contains errors and could not be verified: " + replURLStr,
e);
}
}
@Override
public MCRVersionedMetadata create(MCRContent xml, int id) throws IOException, JDOMException {
return (MCRVersionedMetadata) super.create(xml, id);
}
@Override
public MCRVersionedMetadata create(MCRContent xml) throws IOException, JDOMException {
return (MCRVersionedMetadata) super.create(xml);
}
/**
* Returns the metadata stored under the given ID, or null. Note that this
* metadata may not exist currently in the store, it may be a deleted
* version, which can be restored then.
*
* @param id
* the ID of the XML document
* @return the metadata stored under that ID, or null when there is no such
* metadata object
*/
@Override
public MCRVersionedMetadata retrieve(int id) throws IOException {
MCRVersionedMetadata metadata = (MCRVersionedMetadata) super.retrieve(id);
if (metadata != null) {
return metadata;
}
return new MCRVersionedMetadata(this, getSlot(id), id, super.forceDocType, true);
}
/**
* Updates all stored metadata to the latest revision in SVN
*/
public void updateAll() throws Exception {
for (Iterator<Integer> ids = listIDs(true); ids.hasNext();) {
retrieve(ids.next()).update();
}
}
@Override
public void delete(int id) throws IOException {
String commitMsg = "Deleted metadata object " + getID() + "_" + id + " in store";
// Commit to SVN
SVNCommitInfo info;
try {
SVNRepository repository = getRepository();
ISVNEditor editor = repository.getCommitEditor(commitMsg, null);
editor.openRoot(-1);
editor.deleteEntry("/" + getSlotPath(id), -1);
editor.closeDir();
info = editor.closeEdit();
LOGGER.info("SVN commit of delete finished, new revision {}", info.getNewRevision());
} catch (SVNException e) {
LOGGER.error("Error while deleting {} in SVN ", id, e);
} finally {
super.delete(id);
}
}
@Override
protected MCRVersionedMetadata buildMetadataObject(Path fo, int id) {
return new MCRVersionedMetadata(this, fo, id, super.forceDocType, false);
}
}
| 10,733 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRMetadataStore.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.datamodel.ifs2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.JDOMException;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRContent;
/**
* Stores XML metadata documents (or optionally any other BLOB data) in a
* persistent filesystem structure
*
* For each object type, a store must be defined as follows:
*
* MCR.IFS2.Store.DocPortal_document.Class=org.mycore.datamodel.ifs2.MCRMetadataStore
* MCR.IFS2.Store.DocPortal_document.BaseDir=/foo/bar
* MCR.IFS2.Store.DocPortal_document.SlotLayout=4-2-2
* MCR.IFS2.Store.DocPortal_document.ForceXML=true (which is default)
*
* @author Frank Lützenkirchen
*/
public class MCRMetadataStore extends MCRStore {
public static final Logger LOGGER = LogManager.getLogger();
/**
* If true (which is default), store will enforce it gets
* XML to store, otherwise any binary content can be stored here.
*
* Override with MCR.IFS2.Store.<ObjectType>.ForceXML=true|false
*/
protected boolean forceXML = true;
protected String forceDocType;
/**
* Initializes a new metadata store instance.
*
* @param type
* the document type that is stored in this store
*/
@Override
protected void init(String type) {
super.init(type);
prefix = MCRConfiguration2.getString("MCR.IFS2.Store." + type + ".Prefix").orElse(type + "_");
suffix = ".xml";
forceXML = MCRConfiguration2.getBoolean("MCR.IFS2.Store." + type + ".ForceXML").orElse(true);
if (forceXML) {
forceDocType = MCRConfiguration2.getString("MCR.IFS2.Store." + type + ".ForceDocType").orElse(null);
LOGGER.debug("Set doctype for {} to {}", type, forceDocType);
}
}
/**
* Initializes a new metadata store instance.
*
* @param config
* the configuration for the store
*/
@Override
protected void init(MCRStoreConfig config) {
super.init(config);
prefix = Optional.ofNullable(config.getPrefix()).orElseGet(() -> config.getID() + "_");
suffix = ".xml";
forceXML = MCRConfiguration2.getBoolean("MCR.IFS2.Store." + config.getID() + ".ForceXML").orElse(true);
if (forceXML) {
forceDocType = MCRConfiguration2.getString("MCR.IFS2.Store." + config.getID() + ".ForceDocType")
.orElse(null);
LOGGER.debug("Set doctype for {} to {}", config.getID(), forceDocType);
}
}
protected boolean shouldForceXML() {
return forceXML;
}
/**
* Stores a newly created document, using the next free ID.
*
* @param xml
* the XML document to be stored
* @return the stored metadata object
*/
public MCRStoredMetadata create(MCRContent xml) throws IOException, JDOMException {
int id = getNextFreeID();
return create(xml, id);
}
/**
* Stores a newly created document under the given ID.
*
* @param xml
* the XML document to be stored
* @param id
* the ID under which the document should be stored
* @return the stored metadata object
*/
public MCRStoredMetadata create(MCRContent xml, int id) throws IOException, JDOMException {
if (id <= 0) {
throw new MCRException("ID of metadata object must be a positive integer");
}
Path path = getSlot(id);
if (Files.exists(path)) {
String msg = "Metadata object with ID " + id + " already exists in store";
throw new MCRException(msg);
}
if (!Files.exists(path.getParent())) {
Files.createDirectories(path.getParent());
}
MCRStoredMetadata meta = buildMetadataObject(path, id);
meta.create(xml);
return meta;
}
/**
* Returns the metadata stored under the given ID, or null
*
* @param id
* the ID of the XML document
* @return the metadata stored under that ID, or null when there is no such
* metadata object
*/
public MCRStoredMetadata retrieve(int id) throws IOException {
Path path = getSlot(id);
if (!Files.exists(path)) {
return null;
} else {
return buildMetadataObject(path, id);
}
}
/**
* Builds a new stored metadata object in this store
*
* @param fo
* the FileObject that stores the data
* @param id
* the ID of the metadata object
*/
protected MCRStoredMetadata buildMetadataObject(Path fo, int id) {
return new MCRStoredMetadata(this, fo, id, forceDocType);
}
}
| 5,688 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataVersion.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRMetadataVersion.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.datamodel.ifs2;
import java.io.IOException;
import java.util.Date;
import org.jdom2.JDOMException;
import org.mycore.common.MCRUsageException;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.streams.MCRByteArrayOutputStream;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.io.SVNRepository;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* Provides information about a stored version of metadata and allows to
* retrieve that version from SVN
*
* @author Frank Lützenkirchen
*/
@XmlRootElement(name = "revision")
@XmlAccessorType(XmlAccessType.FIELD)
public class MCRMetadataVersion extends MCRAbstractMetadataVersion<MCRVersionedMetadata> {
public MCRMetadataVersion(MCRVersionedMetadata vm, String revision, String user, Date date, char type) {
super(vm, revision, user, date, type);
}
/**
* Retrieves this version of the metadata
*
* @return the metadata document as it was in this version
* @throws MCRUsageException
* if this is a deleted version, which can not be retrieved
*/
@Override
public MCRContent retrieve() throws IOException {
if (getType() == DELETED) {
String msg = "You can not retrieve a deleted version, retrieve a previous version instead";
throw new MCRUsageException(msg);
}
try {
SVNRepository repository = vm.getStore().getRepository();
MCRByteArrayOutputStream baos = new MCRByteArrayOutputStream();
repository.getFile(vm.getStore().getSlotPath(vm.getID()), Long.parseLong(getRevision()), null, baos);
baos.close();
return new MCRByteContent(baos.getBuffer(), 0, baos.size(), getDate().getTime());
} catch (SVNException e) {
throw new IOException(e);
}
}
/**
* Replaces the current version of the metadata object with this version,
* which means that a new version is created that is identical to this old
* version. The stored metadata document is updated to this old version of
* the metadata.
*/
@Override
public void restore() throws IOException, JDOMException {
vm.update(retrieve());
}
}
| 3,219 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDFileSystemDate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRObjectIDFileSystemDate.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.datamodel.ifs2;
import java.io.IOException;
public class MCRObjectIDFileSystemDate extends MCRObjectIDDateImpl {
@SuppressWarnings("unused")
private MCRObjectIDFileSystemDate() {
//JAXB requirement
}
public MCRObjectIDFileSystemDate(MCRStoredMetadata sm, String id) throws IOException {
super(sm.getLastModified(), id);
}
}
| 1,110 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFile.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRFile.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.datamodel.ifs2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.streams.MCRDevNull;
import org.mycore.datamodel.ifs.MCRContentInputStream;
import org.mycore.datamodel.niofs.MCRFileAttributes;
/**
* Represents a file stored in a file collection. This is a file that is
* imported from outside the system, and may be updated and modified afterwards.
*
* @author Frank Lützenkirchen
*
*/
public class MCRFile extends MCRStoredNode {
private static final MCRDevNull DEV_NULL = new MCRDevNull();
private static final Logger LOGGER = LogManager.getLogger(MCRFile.class);
/**
* The md5 checksum of the empty file
*/
public static final String MD5_OF_EMPTY_FILE = "d41d8cd98f00b204e9800998ecf8427e";
/**
* Returns a MCRFile object representing an existing file already stored in
* the store.
*
* @param parent
* the parent directory containing this file
* @param fo
* the file in the local underlying filesystem storing this file
*/
protected MCRFile(MCRDirectory parent, Path fo, Element data) {
super(parent, fo, data);
}
/**
* Creates a new MCRFile that does not exist yet
*
* @param parent
* the parent directory
* @param name
* the file name
*/
protected MCRFile(MCRDirectory parent, String name) throws IOException {
super(parent, name, "file");
Files.createFile(path);
writeData(e -> e.setAttribute("md5", MCRFile.MD5_OF_EMPTY_FILE));
getRoot().saveAdditionalData();
}
/**
* Returns a MCRVirtualNode contained in this file as a child. A file that
* is a container, like zip or tar, may contain other files as children.
*/
@Override
protected MCRVirtualNode buildChildNode(Path fo) {
return null; //not implemented
}
/**
* Returns the md5 checksum of the file's content.
*
* @return the md5 checksum of the file's content.
*/
public String getMD5() {
return readData(e -> e.getAttributeValue("md5"));
}
/**
* Returns the file name extension, which is the part after the last dot in
* the filename.
*
* @return the file extension, or the empty string if the file name does not
* have an extension
*/
public String getExtension() {
String name = getName();
int pos = name.lastIndexOf(".");
return pos == -1 ? "" : name.substring(pos + 1);
}
/**
* Sets the content of this file.
*
* @param source
* the content to be read
* @return the MD5 checksum of the stored content
*/
public String setContent(MCRContent source) throws IOException {
try (MCRContentInputStream cis = source.getContentInputStream()) {
source.sendTo(path, StandardCopyOption.REPLACE_EXISTING);
String md5 = cis.getMD5String();
writeData(e -> e.setAttribute("md5", md5));
getRoot().saveAdditionalData();
return md5;
}
}
/**
* updates the MD5 sum of this file to the given value.
*
* Use only if you modified the content outside of {@link #setContent(MCRContent)}.
*/
public void setMD5(String md5) throws IOException {
writeData(e -> e.setAttribute("md5", md5));
getRoot().saveAdditionalData();
}
/**
* Repairs additional metadata of this file and all its children
*/
@Override
void repairMetadata() throws IOException {
MCRContentInputStream cis = getContent().getContentInputStream();
IOUtils.copy(cis, DEV_NULL);
cis.close();
String path = getPath();
writeData(e -> {
e.setName("file");
e.setAttribute("name", getName());
e.removeChildren("file");
e.removeChildren("directory");
String md5 = cis.getMD5String();
if (!md5.equals(e.getAttributeValue("md5"))) {
LOGGER.warn("Fixed MD5 of {} to {}", path, md5);
e.setAttribute("md5", md5);
}
});
}
@Override
public MCRFileAttributes<String> getBasicFileAttributes() throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return MCRFileAttributes.fromAttributes(attrs, getMD5());
}
}
| 5,531 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoreCenter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRStoreCenter.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.datamodel.ifs2;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
public class MCRStoreCenter {
private Map<String, MCRStore> storeHeap;
private static MCRStoreCenter instance = new MCRStoreCenter();
private MCRStoreCenter() {
this.storeHeap = new HashMap<>();
}
public static MCRStoreCenter instance() {
return instance;
}
/**
* Add a store to the store center
*
* @param store - Add this store to store center
* @throws MCRStoreAlreadyExistsException If with the same id already exists in the store center
*/
public void addStore(String id, MCRStore store) throws MCRStoreAlreadyExistsException {
if (storeHeap.putIfAbsent(id, store) != null) {
throw new MCRStoreAlreadyExistsException("Could not add store with ID " + id + ", store allready exists");
}
}
/**
* Get the MyCoRe Store with the given ID from store center.
*
* @param id - The id of the to retrieved store
* @param storeClass - The class type of the retrieved store
* @return The retrieved store or null if not exists
* @deprecated use {@link #getStore(String)} instead
*/
@Deprecated
@SuppressWarnings("unchecked")
public <T extends MCRStore> T getStore(String id, Class<T> storeClass) {
return (T) storeHeap.get(id);
}
/**
* Get the MyCoRe Store with the given ID from store center.
*
* @param id - The id of the to retrieved store
* @return The retrieved store or null if not exists
*/
public <T extends MCRStore> T getStore(String id) {
return (T) storeHeap.get(id);
}
/**
* @return a Stream of all {@link MCRStore}s that are an instance of <code><T></code>
*/
public <T extends MCRStore> Stream<T> getCurrentStores(Class<T> sClass) {
return storeHeap.values()
.stream()
.filter(sClass::isInstance)
.map(s -> (T) s)
.filter(Objects::nonNull);
}
/**
* Remove the store from store center
*
* @param id - Removed this store from store center
* @return true if successfully removed or false
*/
public boolean removeStore(String id) {
return storeHeap.remove(id) != null;
}
/**
* Remove all store from the store center
*/
public void clear() {
storeHeap.clear();
}
}
| 3,218 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPathComparator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRPathComparator.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.datamodel.ifs2;
import java.io.Serializable;
import java.nio.file.Path;
import java.util.Comparator;
class MCRPathComparator implements Comparator<Path>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int compare(Path o1, Path o2) {
String path1 = o1.getFileName().toString();
String path2 = o2.getFileName().toString();
return path1.compareTo(path2);
}
}
| 1,181 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoreAlreadyExistsException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRStoreAlreadyExistsException.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.datamodel.ifs2;
public class MCRStoreAlreadyExistsException extends Exception {
private static final long serialVersionUID = 1L;
public MCRStoreAlreadyExistsException(String msg) {
super(msg);
}
}
| 966 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoredNode.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRStoredNode.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.datamodel.ifs2;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Consumer;
import java.util.function.Function;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.niofs.MCRFileAttributes;
import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter;
/**
* A file or directory really stored by importing it from outside the system.
* Can be modified, updated and deleted, in contrast to virtual nodes.
*
* @author Frank Lützenkirchen
*/
public abstract class MCRStoredNode extends MCRNode {
private static final String LANG_ATT = "lang";
private static final String LABEL_ELEMENT = "label";
private static final String NAME_ATT = "name";
/**
* Any additional data of this node that is not stored in the file object
*/
private Element additionalData;
/**
* Returns a stored node instance that already exists
*
* @param parent
* the parent directory containing this node
* @param fo
* the file object in local filesystem representing this node
* @param data
* the additional data of this node that is not stored in the
* file object
*/
protected MCRStoredNode(MCRDirectory parent, Path fo, Element data) {
super(parent, fo);
this.additionalData = data;
}
/**
* Creates a new stored node
*
* @param parent
* the parent directory
* @param name
* the name of the node
* @param type
* the node type, dir or file
*/
protected MCRStoredNode(MCRDirectory parent, String name, String type) {
super(parent, parent.path.resolve(name));
additionalData = new Element(type);
additionalData.setAttribute(NAME_ATT, name);
parent.writeData(e -> e.addContent(additionalData));
}
/**
* Returns the local {@link File} representing this stored file or directory. Be careful
* to use this only for reading data, do never modify directly!
*
* @return the file in the local filesystem representing this file
* @deprecated use {@link #getLocalPath()} instead
*/
@Deprecated
public File getLocalFile() {
return path.toFile();
}
/**
* Returns the local {@link Path} representing this stored file or directory. Be careful
* to use this only for reading data, do never modify directly!
*
* @return the file in the local filesystem representing this file
*/
public Path getLocalPath() {
return path;
}
/**
* Deletes this node with all its data and children
*/
public void delete() throws IOException {
writeData(Element::detach);
if (Files.isDirectory(path)) {
Files.walkFileTree(path, MCRRecursiveDeleter.instance());
} else {
Files.deleteIfExists(path);
}
getRoot().saveAdditionalData();
}
/**
* Renames this node.
*
* @param name
* the new file name
*/
public void renameTo(String name) throws IOException {
Path oldPath = path;
Path newPath = path.resolveSibling(name);
Files.move(oldPath, newPath);
Files.setLastModifiedTime(newPath, FileTime.from(Instant.now()));
path = newPath;
writeData(e -> e.setAttribute(NAME_ATT, name));
getRoot().saveAdditionalData();
}
/**
* Sets last modification time of this file to a custom value.
*
* @param time
* the time to be stored as last modification time
*/
public void setLastModified(Date time) throws IOException {
Files.setLastModifiedTime(path, FileTime.from(time.toInstant()));
}
/**
* Sets a label for this node
*
* @param lang
* the xml:lang language ID
* @param label
* the label in this language
*/
public void setLabel(String lang, String label) throws IOException {
writeData(e -> e.getChildren(LABEL_ELEMENT)
.stream()
.filter(child -> lang.equals(child.getAttributeValue(LANG_ATT, Namespace.XML_NAMESPACE)))
.findAny()
.orElseGet(() -> {
Element newLabel = new Element(LABEL_ELEMENT).setAttribute(LANG_ATT, lang, Namespace.XML_NAMESPACE);
e.addContent(newLabel);
return newLabel;
})
.setText(label));
getRoot().saveAdditionalData();
}
/**
* Removes all labels set
*/
public void clearLabels() throws IOException {
writeData(e -> e.removeChildren(LABEL_ELEMENT));
getRoot().saveAdditionalData();
}
/**
* Returns a map of all labels, sorted by xml:lang, Key is xml:lang, value
* is the label for that language.
*/
public Map<String, String> getLabels() {
Map<String, String> labels = new TreeMap<>();
for (Element label : readData(e -> e.getChildren(LABEL_ELEMENT))) {
labels.put(label.getAttributeValue(LANG_ATT, Namespace.XML_NAMESPACE), label.getText());
}
return labels;
}
/**
* Returns the label in the given language
*
* @param lang
* the xml:lang language ID
* @return the label, or null if there is no label for that language
*/
public String getLabel(String lang) {
return readData(e -> e.getChildren(LABEL_ELEMENT)
.stream()
.filter(label -> lang.equals(
label.getAttributeValue(LANG_ATT, Namespace.XML_NAMESPACE)))
.findAny()
.map(Element::getText)
.orElse(null));
}
/**
* Returns the label in the current language, otherwise in default language,
* otherwise the first label defined, if any at all.
*
* @return the label
*/
public String getCurrentLabel() {
String currentLang = MCRSessionMgr.getCurrentSession().getCurrentLanguage();
String label = getLabel(currentLang);
if (label != null) {
return label;
}
String defaultLang = MCRConfiguration2.getString("MCR.Metadata.DefaultLang").orElse(MCRConstants.DEFAULT_LANG);
label = getLabel(defaultLang);
if (label != null) {
return label;
}
return readData(e -> e.getChildText(LABEL_ELEMENT));
}
/**
* Repairs additional metadata of this node
*/
abstract void repairMetadata() throws IOException;
protected <T> T readData(Function<Element, T> readOperation) {
return getRoot().getDataGuard().read(() -> readOperation.apply(additionalData));
}
protected <T> void writeData(Consumer<Element> writeOperation) {
getRoot().getDataGuard().write(() -> writeOperation.accept(additionalData));
}
public MCRFileAttributes<String> getBasicFileAttributes() throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return MCRFileAttributes.fromAttributes(attrs, null);
}
}
| 8,284 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDDateImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRObjectIDDateImpl.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.datamodel.ifs2;
import java.util.Date;
import org.mycore.datamodel.common.MCRObjectIDDate;
public class MCRObjectIDDateImpl implements MCRObjectIDDate {
protected Date lastModified;
protected String id;
protected MCRObjectIDDateImpl() {
super();
}
public MCRObjectIDDateImpl(Date lastModified, String id) {
super();
this.lastModified = lastModified;
this.id = id;
}
public Date getLastModified() {
return lastModified;
}
public String getId() {
return id;
}
protected void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
protected void setId(String id) {
this.id = id;
}
}
| 1,476 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIFS2Commands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRIFS2Commands.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.datamodel.ifs2;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.MessageFormat;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.cli.MCRAbstractCommands;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
@MCRCommandGroup(name = "IFS2 Commands")
public class MCRIFS2Commands extends MCRAbstractCommands {
public static final Logger LOGGER = LogManager.getLogger();
@MCRCommand(syntax = "list all current ifs2 stores",
help = "Lists all currently configured IFS2 MCRStore instances")
public static void listAllStores() throws IOException {
initStores();
final Stream<MCRStore> stores = MCRStoreCenter.instance().getCurrentStores(MCRStore.class);
stores.map(MCRIFS2Commands::toString)
.forEach(LOGGER::info);
}
@MCRCommand(syntax = "list all current ifs2 file stores",
help = "Lists all currently configured IFS2 MCRFileStore instances")
public static void listAllFileStores() {
initFileStores();
final Stream<MCRFileStore> stores = MCRStoreCenter.instance().getCurrentStores(MCRFileStore.class);
stores.map(MCRIFS2Commands::toString)
.forEach(LOGGER::info);
}
private static void initStores() {
initMetadataStores();
initFileStores();
}
private static void initFileStores() {
//FileSystems.getFileSystem(schemeURI) will not work in WebCLI
//Workaround is to go via MCRPath
final FileSystem defaultFileSystem = MCRPath.getRootPath("ignored").getFileSystem();
defaultFileSystem.getFileStores()
.forEach(FileStore::name);
}
private static void initMetadataStores() {
final MCRXMLMetadataManager metadataManager = MCRXMLMetadataManager.instance();
metadataManager.getObjectBaseIds().forEach(id -> {
final String[] parts = id.split("_");
metadataManager.getHighestStoredID(parts[0], parts[1]);
});
}
private static String toString(MCRStore store) {
final Map<String, String> configMap = MCRConfiguration2.getSubPropertiesMap(
"MCR.IFS2.Store." + store.getID() + ".");
final String config = configMap.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> ", " + e.getKey() + "=" + e.getValue())
.collect(Collectors.joining());
return store.getClass().getSimpleName() + "{" +
"id=" + store.getID() +
", baseDirectory=" + store.getBaseDirectory() +
", lastID=" + store.getHighestStoredID() +
config +
'}';
}
@MCRCommand(syntax = "generate ifs2 md5sum files in directory {0}",
help = "writes md5sum files for every ifs2 file store in directory {0}")
public static List<String> writeMD5SumsToDirectory(String directory) throws NotDirectoryException {
Path targetPath = Paths.get(directory);
if (!Files.isDirectory(targetPath)) {
throw new NotDirectoryException(targetPath.toString());
}
initFileStores();
return MCRStoreCenter.instance().getCurrentStores(MCRFileStore.class)
.sorted(Comparator.comparing(MCRStore::getID))
.map(s -> "generate md5sum file " + targetPath.resolve(s.getID() + ".md5") + " for ifs2 file store "
+ s.getID())
.collect(Collectors.toList());
}
@MCRCommand(syntax = "generate md5sum file {0} for ifs2 file store {1}",
help = "writes md5sum file {0} for every file in MCRFileStore with ID {1}")
public static void writeMD5SumFile(String targetFile, String ifsStoreId) throws IOException {
initFileStores();
final MCRStore store = MCRStoreCenter.instance().getStore(ifsStoreId);
if (!(store instanceof MCRFileStore)) {
throw new MCRException("Store " + ifsStoreId + " is not found or is not a file store.");
}
Path targetPath = Paths.get(targetFile);
if (!Files.isDirectory(targetPath.getParent())) {
throw new NotDirectoryException(targetPath.getParent().toString());
}
try (BufferedWriter bw = Files.newBufferedWriter(targetPath, StandardCharsets.UTF_8,
StandardOpenOption.CREATE)) {
final MessageFormat md5FileFormat = new MessageFormat("{0} {1}\n", Locale.ROOT);
MCRFileStore fileStore = (MCRFileStore) store;
fileStore.getStoredIDs()
.sorted()
.mapToObj(id -> {
//retrieve MCRFileCollection
return fileStore.retrieve(id);
})
.flatMap(fc -> {
//List every file in FileCollection
try {
return getAllFiles(fc.getLocalPath(), fc.getMetadata().getRootElement());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
})
.forEach(f -> {
//Write single line in md5sum file
try {
bw.write(md5FileFormat.format(new Object[] { f.md5, f.localPath }));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
private static Stream<FileInfo> getAllFiles(Path nodePath, Element node)
throws IOException {
Function<Element, String> getName = e -> e.getAttributeValue("name");
try {
return node.getChildren().stream()
.sorted(Comparator.comparing(getName))
.flatMap(n -> {
final String fileName = getName.apply(n);
if ("dir".equals(n.getName())) {
try {
return getAllFiles(nodePath.resolve(fileName), n);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return Stream.of(new FileInfo(nodePath.resolve(fileName), n.getAttributeValue("md5")));
});
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
@MCRCommand(syntax = "verify ifs2 versioning metadata store {0}",
help = "checks versioning metadata store {0} for errors")
public static void verifyVersioningMetadataStore(String storeId) {
initMetadataStores();
MCRVersioningMetadataStore store = MCRStoreCenter.instance().getStore(storeId);
if (store == null) {
throw new MCRException("MCRVersioningMetadataStore with id " + storeId + " was not found.");
}
store.verify();
}
@MCRCommand(syntax = "verify ifs2 versioning metadata stores",
help = "checks all versioning metadata stores for errors")
public static List<String> verifyVersioningMetadataStores() {
initMetadataStores();
return MCRStoreCenter.instance().getCurrentStores(MCRVersioningMetadataStore.class)
.map(s -> "verify versioning metadata store " + s.getID())
.collect(Collectors.toList());
}
@MCRCommand(syntax = "repair metadata for file collection {0,number} in ifs2 file store {1}",
help = "repairs checksums in file collection {0} of ifs2 file store {1}")
public static void repairMetaXML(int fileCollection, String storeId) throws IOException {
initFileStores();
MCRFileStore store = MCRStoreCenter.instance().getStore(storeId);
if (store == null) {
throw new MCRException("MCRFileStore with id " + storeId + " was not found.");
}
final MCRFileCollection fc = store.retrieve(fileCollection);
if (fc == null) {
throw new MCRException("File collection " + fileCollection + " not found in MCRFileStore " + storeId + ".");
}
fc.repairMetadata();
}
@MCRCommand(syntax = "repair ifs2 metadata for derivate {0}",
help = "repairs checksums for derivate {0}")
public static List<String> repairMetaXML(String mcrId) {
final MCRObjectID derivateId = MCRObjectID.getInstance(mcrId);
//works for derivate that use ifs2:// URIs
return List.of("repair metadata for file collection " + derivateId.getNumberAsInteger()
+ " in ifs2 file store IFS2_" + derivateId.getBase());
}
private record FileInfo(Path localPath, String md5) {
}
}
| 10,286 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRFileStore.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.datamodel.ifs2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* Stores file collections containing files and directories.
*
* For each store, properties must be defined, for example
*
* MCR.IFS2.Store.ID.Class=org.mycore.datamodel.ifs2.MCRFileStore
* MCR.IFS2.Store.ID.BaseDir=/foo/bar MCR.IFS2.Store.ID.SlotLayout=4-2-2
*
* @author Frank Lützenkirchen
*/
public class MCRFileStore extends MCRStore {
private final MCRFileStore thisInstance;
//MCR-1868: prevents parallel threads to read and write mcrmeta.xml concurrently on instantiation
LoadingCache<Integer, MCRFileCollection> collectionLoadingCache = CacheBuilder.newBuilder()
.weakValues()
.build(new CacheLoader<>() {
@Override
public MCRFileCollection load(Integer key) throws Exception {
return new MCRFileCollection(thisInstance, key);
}
});
public MCRFileStore() {
super();
thisInstance = this;
}
/**
* Creates and stores a new, empty file collection using the next free ID in
* the store.
*
* @return a newly created file collection
*/
public MCRFileCollection create() throws IOException {
int id = getNextFreeID();
return create(id);
}
/**
* Creates and stores a new, empty file collection with the given ID
*
* @param id
* the ID of the file collection
* @return a newly created file collection
* @throws IOException
* when a file collection with the given ID already exists
*/
public MCRFileCollection create(int id) throws IOException {
Path path = getSlot(id);
if (Files.exists(path)) {
String msg = "FileCollection with ID " + id + " already exists";
throw new IOException(msg);
}
return collectionLoadingCache.getUnchecked(id);
}
@Override
public void delete(int id) throws IOException {
Path path = getSlot(id);
if (Files.exists(path)) {
super.delete(path);
}
collectionLoadingCache.invalidate(id);
}
/**
* Returns the file collection stored under the given ID, or null when no
* collection is stored for the given ID.
*
* @param id
* the file collection's ID
* @return the file collection with the given ID, or null
*/
public MCRFileCollection retrieve(int id) {
Path path = getSlot(id);
if (!Files.exists(path)) {
return null;
} else {
return collectionLoadingCache.getUnchecked(id);
}
}
/**
* Repairs metadata of all file collections stored here
*
*/
public void repairAllMetadata() throws IOException {
for (Iterator<Integer> e = listIDs(MCRStore.ASCENDING); e.hasNext();) {
retrieve(e.next()).repairMetadata();
}
}
}
| 3,890 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileCollection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRFileCollection.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.datamodel.ifs2;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.MCRPathContent;
import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter;
import org.mycore.util.concurrent.MCRReadWriteGuard;
/**
* Represents a set of files and directories belonging together, that are stored
* in a persistent MCRFileStore. A FileCollection has a unique ID within the
* store, it is the root folder of all files and directories in the collection.
*
* @author Frank Lützenkirchen
*/
public class MCRFileCollection extends MCRDirectory {
/**
* The logger
*/
private static final Logger LOGGER = LogManager.getLogger(MCRFileCollection.class);
public static final String DATA_FILE = "mcrdata.xml";
/**
* The store this file collection is stored in.
*/
private MCRStore store;
/**
* The ID of this file collection
*/
private int id;
/**
* Guard for additional data
*
* MCR-1869
*/
private MCRReadWriteGuard dataGuard;
/**
* Creates a new file collection in the given store, or retrieves an
* existing one.
*
* @see MCRFileStore
*
* @param store
* the store this file collection is stored in
* @param id
* the ID of this file collection
*/
protected MCRFileCollection(MCRStore store, int id) throws IOException {
super(null, store.getSlot(id), new Element("collection"));
this.store = store;
this.id = id;
this.dataGuard = new MCRReadWriteGuard();
if (Files.exists(path)) {
readAdditionalData();
} else {
Files.createDirectories(path);
writeData(Document::new);
saveAdditionalData();
}
}
MCRReadWriteGuard getDataGuard() {
return dataGuard;
}
private void readAdditionalData() throws IOException {
Path src = path.resolve(DATA_FILE);
if (!Files.exists(src)) {
LOGGER.warn("Metadata file is missing, repairing metadata...");
writeData(e -> {
e.detach();
e.setName("collection");
e.removeContent();
new Document(e);
});
repairMetadata();
}
try {
Element parsed = new MCRPathContent(src).asXML().getRootElement();
writeData(e -> {
e.detach();
e.setName("collection");
e.removeContent();
List<Content> parsedContent = new ArrayList<>(parsed.getContent());
parsedContent.forEach(Content::detach);
e.addContent(parsedContent);
new Document(e);
});
} catch (JDOMException e) {
throw new IOException(e);
}
}
protected void saveAdditionalData() throws IOException {
Path target = path.resolve(DATA_FILE);
try {
readData(e -> {
try {
boolean needsUpdate = true;
while (needsUpdate) {
try {
new MCRJDOMContent(e.getDocument()).sendTo(target, StandardCopyOption.REPLACE_EXISTING);
needsUpdate = false;
} catch (FileAlreadyExistsException ex) {
//other process writes to the same file, let us win
} catch (IOException | RuntimeException ex) {
throw ex;
}
}
return null;
} catch (IOException e1) {
throw new UncheckedIOException(e1);
}
});
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
@Override
public Stream<MCRNode> getChildren() throws IOException {
return super.getChildren()
.filter(f -> !DATA_FILE.equals(f.getName()));
}
/**
* Deletes this file collection with all its data and children
*/
public void delete() throws IOException {
writeData(Element::removeContent);
Files.walkFileTree(path, MCRRecursiveDeleter.instance());
store.delete(id);
}
/**
* Throws a exception, because a file collection's name is always the empty
* string and therefore can not be renamed.
*/
@Override
public void renameTo(String name) {
throw new UnsupportedOperationException("File collections can not be renamed");
}
/**
* Returns the store this file collection is stored in.
*
* @return the store this file collection is stored in.
*/
public MCRStore getStore() {
return store;
}
/**
* Returns the ID of this file collection
*
* @return the ID of this file collection
*/
public int getID() {
return id;
}
/**
* Returns this object, because the FileCollection instance is the root of
* all files and directories contained in the collection.
*
* @return this
*/
@Override
public MCRFileCollection getRoot() {
return this;
}
@Override
public MCRNode getChild(String name) {
if (DATA_FILE.equals(name)) {
return null;
} else {
return super.getChild(name);
}
}
@Override
public boolean hasChildren() throws IOException {
try (Stream<Path> stream = getUsableChildSream()) {
return stream.findAny().isPresent();
}
}
@Override
public int getNumChildren() throws IOException {
try (Stream<Path> stream = getUsableChildSream()) {
return Math.toIntExact(stream.count());
}
}
private Stream<Path> getUsableChildSream() throws IOException {
return Files.list(path)
.filter(p -> !DATA_FILE.equals(p.getFileName().toString()));
}
@Override
public String getName() {
return "";
}
/**
* Repairs additional metadata stored for all files and directories in this
* collection
*/
@Override
public void repairMetadata() throws IOException {
super.repairMetadata();
writeData(e -> {
e.setName("collection");
e.removeAttribute("name");
});
saveAdditionalData();
}
/**
* Returns additional metadata stored for all files and directories in this
* collection
*/
Document getMetadata() {
return new Document(readData(Element::clone));
}
}
| 7,891 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoredMetadata.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs2/MCRStoredMetadata.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.datamodel.ifs2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileTime;
import java.util.Date;
import org.jdom2.JDOMException;
import org.mycore.common.MCRUsageException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRPathContent;
/**
* Represents an XML metadata document that is stored in MCRMetadataStore.
*
* @author Frank Lützenkirchen
*/
public class MCRStoredMetadata {
/** The ID of the metadata document */
protected int id;
/** The file object in local filesystem storing the data */
protected Path path;
/** The store this document is stored in */
protected MCRMetadataStore store;
private String docType;
protected boolean deleted;
/**
* Creates a new stored metadata object
*
* @param store
* the store this document is stored in
* @param path
* the file object storing the data
* @param id
* the ID of the metadata document
* @param docType
* if not null overwrites any detected doctype
*/
MCRStoredMetadata(MCRMetadataStore store, Path path, int id, String docType) {
this.store = store;
this.id = id;
this.path = path;
this.docType = docType;
this.deleted = false;
}
/**
* Creates a new local file to save XML to
*
* @param xml
* the XML to save to a new file
* @throws JDOMException if content is not XML and corresponding
* {@link MCRMetadataStore} forces MCRContent to be XML
*/
void create(MCRContent xml) throws IOException, JDOMException {
if (store.shouldForceXML()) {
xml = xml.ensureXML();
}
if (!Files.exists(path.getParent())) {
Files.createDirectories(path.getParent());
}
xml.sendTo(path);
}
/**
* Updates the stored XML document
*
* @param xml
* the XML document to be stored
* @throws JDOMException if content is not XML and corresponding
* {@link MCRMetadataStore} forces MCRContent to be XML
*/
public void update(MCRContent xml) throws IOException, JDOMException {
if (isDeleted()) {
String msg = "You can not update a deleted data object";
throw new MCRUsageException(msg);
}
if (store.shouldForceXML()) {
xml = xml.ensureXML();
}
xml.sendTo(path, StandardCopyOption.REPLACE_EXISTING);
}
/**
* Returns the stored XML document
*
* @return the stored XML document
*/
public MCRContent getMetadata() {
MCRPathContent pathContent = new MCRPathContent(path);
pathContent.setDocType(docType);
return pathContent;
}
/**
* Returns the ID of this metadata document
*
* @return the ID of this metadata document
*/
public int getID() {
return id;
}
/**
* Returns the store this metadata document is stored in
*
* @return the store this metadata document is stored in
*/
public MCRMetadataStore getStore() {
return store;
}
/**
* Returns the date this metadata document was last modified
*
* @return the date this metadata document was last modified
*/
public Date getLastModified() throws IOException {
return Date.from(Files.getLastModifiedTime(path).toInstant());
}
/**
* Sets the date this metadata document was last modified
*
* @param date
* the date this metadata document was last modified
*/
public void setLastModified(Date date) throws IOException {
if (!isDeleted()) {
Files.setLastModifiedTime(path, FileTime.from(date.toInstant()));
}
}
/**
* Deletes the metadata document. This object is invalid afterwards, do not
* use it any more.
*
*/
public void delete() throws IOException {
if (!deleted) {
store.delete(path);
deleted = true;
}
}
/**
* Returns true if this object is deleted
*/
public boolean isDeleted() {
return deleted;
}
}
| 5,121 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/language/MCRLanguageFactory.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.datamodel.language;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
/**
* Returns MCRLanguage instances. The languages most commonly used, English and German,
* are provided as constants. Other languages are read from a classification thats ID can be
* configured using the property "MCR.LanguageClassification". That classification should use
* ISO 639-1 code as category ID, where ISO 639-2 codes can be added by extra labels x-term and x-bibl
* for the category. Unknown languages are created by code as required, but a warning is logged.
*
* @author Frank Lützenkirchen
*/
public class MCRLanguageFactory {
private static final Logger LOGGER = LogManager.getLogger();
private static final MCRLanguageFactory SINGLETON = new MCRLanguageFactory();
public static final MCRLanguage GERMAN = MCRLanguageFactory.instance().getLanguage("de");
public static final MCRLanguage ENGLISH = MCRLanguageFactory.instance().getLanguage("en");
/**
* Map of languages by ISO 639-1 or -2 code
*/
private Map<String, MCRLanguage> languageByCode = new HashMap<>();
/**
* The ID of the classification containing the language codes and labels
*/
private MCRCategoryID classification;
private MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
/**
* Language classification may change at runtime, so we remember the time we last read the languages in.
*/
private long classificationLastRead = Long.MIN_VALUE;
/**
* The default language is configured via "MCR.Metadata.DefaultLang"
*/
private String codeOfDefaultLanguage;
private MCRLanguageFactory() {
codeOfDefaultLanguage = MCRConfiguration2.getString("MCR.Metadata.DefaultLang")
.orElse(MCRConstants.DEFAULT_LANG);
initDefaultLanguages();
classification = MCRConfiguration2.getString("MCR.LanguageClassification")
.map(MCRCategoryID::rootID)
.orElse(null);
}
/**
* Returns the MCRLanguageFactory singleton
*/
public static MCRLanguageFactory instance() {
return SINGLETON;
}
/**
* Returns the default language, as configured by "MCR.Metadata.DefaultLang"
*/
public MCRLanguage getDefaultLanguage() {
return getLanguage(codeOfDefaultLanguage);
}
/**
* Returns the language with the given ISO 639-1 or -2 code. When the given code contains a
* subcode like "en-us", and the main language is configured, that main language is returned.
* When the given code does not match any language configured, a language is created on-the-fly,
* but a warning is logged.
*/
public MCRLanguage getLanguage(String code) {
if (classificationHasChanged()) {
initLanguages();
}
return lookupLanguage(code);
}
private MCRLanguage lookupLanguage(String code) {
if ((!languageByCode.containsKey(code)) && code.contains("-") && !code.startsWith("x-")) {
code = code.split("-")[0];
}
if (!languageByCode.containsKey(code)) {
LOGGER.warn("Unknown language: {}", code);
buildLanguage(code, code.length() > 2 ? code : null, null);
}
return languageByCode.get(code);
}
/**
* This method check the language string base on RFC 1766 to the supported
* languages in MyCoRe in a current application environment. Without appending
* this MCRLanguageFactory only ENGLISH and GERMAN are supported.
*
* @param code
* the language string in RFC 1766 syntax
* @return true if the language code is supported. It return true too if the code starts
* with x- or i-, otherwise return false;
*/
public final boolean isSupportedLanguage(String code) {
if (code == null) {
return false;
}
code = code.trim();
if (code.length() == 0) {
return false;
}
if (code.startsWith("x-") || code.startsWith("i-")) {
return true;
}
return languageByCode.containsKey(code);
}
/**
* Checks if any classification has changed in the persistent store, so that the languages
* should be read again.
*/
private boolean classificationHasChanged() {
//TODO: remove usage of MCREntityManagerProvider
return MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)
&& MCREntityManagerProvider.getEntityManagerFactory() != null && (classification != null)
&& (categoryDAO.getLastModified() > classificationLastRead);
}
/**
* Builds the default languages and reads in the languages configured by classification
*/
private void initLanguages() {
languageByCode.clear();
initDefaultLanguages();
readLanguageClassification();
}
/**
* Builds the default languages
*/
private void initDefaultLanguages() {
MCRLanguage de = buildLanguage("de", "deu", "ger");
MCRLanguage en = buildLanguage("en", "eng", null);
de.setLabel(de, "Deutsch");
de.setLabel(en, "German");
en.setLabel(de, "Englisch");
en.setLabel(en, "English");
}
/**
* Builds a new language object with the given ISO codes.
*
* @param xmlCode ISO 639-1 code as used for xml:lang
* @param termCode ISO 639-2 terminologic code, may be null
* @param biblCode ISO 639-2 bibliographical code, may be null
*/
private MCRLanguage buildLanguage(String xmlCode, String termCode, String biblCode) {
MCRLanguage language = new MCRLanguage();
addCode(language, MCRLanguageCodeType.xmlCode, xmlCode);
if (termCode != null) {
addCode(language, MCRLanguageCodeType.termCode, termCode);
addCode(language, MCRLanguageCodeType.biblCode, biblCode == null ? termCode : biblCode);
}
Locale locale = Arrays.stream(Locale.getAvailableLocales())
.filter(l -> l.toString().equals(xmlCode))
.findFirst()
.orElseGet(() -> Locale.forLanguageTag(xmlCode));
language.setLocale(locale);
return language;
}
/**
* Adds and registers the code for the language
*/
private void addCode(MCRLanguage language, MCRLanguageCodeType type, String code) {
language.setCode(type, code);
languageByCode.put(code, language);
}
/**
* Reads in the language classification and builds language objects from its categories
*/
private void readLanguageClassification() {
MCRSession session = MCRSessionMgr.getCurrentSession();
if (!MCRTransactionHelper.isTransactionActive()) {
MCRTransactionHelper.beginTransaction();
buildLanguagesFromClassification();
MCRTransactionHelper.commitTransaction();
} else {
buildLanguagesFromClassification();
}
}
/**
* Builds language objects from classification categories
*/
private void buildLanguagesFromClassification() {
this.classificationLastRead = categoryDAO.getLastModified();
MCRCategory root = categoryDAO.getCategory(classification, -1);
if (root == null) {
LOGGER.warn("Language classification {} not found", classification.getRootID());
return;
}
for (MCRCategory category : root.getChildren()) {
buildLanguage(category);
}
}
/**
* Builds a new language object from the given category
*/
private void buildLanguage(MCRCategory category) {
String xmlCode = category.getId().getId();
String termCode = category.getLabel("x-term").map(MCRLabel::getText).orElse(null);
String biblCode = category.getLabel("x-bibl").map(MCRLabel::getText).orElse(termCode);
MCRLanguage language = buildLanguage(xmlCode, termCode, biblCode);
category
.getLabels()
.stream()
.filter(l -> !l.getLang().startsWith("x-"))
.sequential() //MCRLanguage is not thread safe
.forEach(l -> {
MCRLanguage languageOfLabel = lookupLanguage(l.getLang());
language.setLabel(languageOfLabel, l.getText());
});
}
}
| 9,826 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguage.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/language/MCRLanguage.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.datamodel.language;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* Represents a language in the datamodel, independent of the type of code used to encode it.
*
* @author Frank Lützenkirchen
*/
public class MCRLanguage {
/**
* A map from codes used for this language, by code type
*/
private Map<MCRLanguageCodeType, String> codesByType = new HashMap<>();
/**
* A map of labels for this language, by language
*/
private Map<MCRLanguage, String> labelsByLanguage = new HashMap<>();
private Locale locale;
/**
* Language instances are created by the package itself, do not use on your own, use MCRLanguageFactory instead.
*
* @see MCRLanguageFactory
*/
MCRLanguage() {
}
/**
* Sets the language code of the given type
*/
void setCode(MCRLanguageCodeType type, String code) {
codesByType.put(type, code);
}
/**
* Returns the code of this language for the given type
*/
public String getCode(MCRLanguageCodeType type) {
return codesByType.get(type);
}
/**
* Returns all language codes used for this language
*/
public Map<MCRLanguageCodeType, String> getCodes() {
return codesByType;
}
/**
* Sets the label in the given language
*/
void setLabel(MCRLanguage language, String label) {
labelsByLanguage.put(language, label);
}
/**
* Returns the label in the given language
*/
public String getLabel(MCRLanguage language) {
return labelsByLanguage.get(language);
}
/**
* Returns the label in the given language
*/
public String getLabel(String languageCode) {
MCRLanguage language = MCRLanguageFactory.instance().getLanguage(languageCode);
return labelsByLanguage.get(language);
}
/**
* Returns all labels used for this language
*/
public Map<MCRLanguage, String> getLabels() {
return labelsByLanguage;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MCRLanguage) {
return this.toString().equals(obj.toString());
} else {
return false;
}
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
return getCode(MCRLanguageCodeType.xmlCode);
}
public Locale getLocale() {
return locale;
}
void setLocale(Locale locale) {
this.locale = locale;
}
}
| 3,330 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageCodeType.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/language/MCRLanguageCodeType.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.datamodel.language;
/**
* Represents a type of langauge code, currently the ISO 639-1 and ISO 639-2b and 2t code types.
*
* @author Frank Lützenkirchen
*/
public enum MCRLanguageCodeType {
/** ISO 639-2 terminology code is identical with ISO 639-3 and used in Dublin Core and OAI output */
termCode,
/** ISO 639-2 bibliographic code is used in some bibliographic metadata standards */
biblCode,
/** ISO 639-1 is used in xml:lang and HTML lang attribute in XML and XHTML output */
xmlCode
}
| 1,268 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/language/MCRLanguageResolver.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.datamodel.language;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.mycore.tools.MCRLanguageOrientationHelper;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import java.util.Map.Entry;
/**
* Resolves languages by code. Syntax: language:{ISOCode}
*
* @author Frank Lützenkirchen
*/
public class MCRLanguageResolver implements URIResolver {
public Source resolve(String href, String base) throws TransformerException, IllegalArgumentException {
String[] hrefContent = href.split(":");
if (hrefContent.length < 2) {
throw new IllegalArgumentException("Empty language code found while resolving URI 'language:'.");
}
try {
String code = hrefContent[1];
MCRLanguage language = MCRLanguageFactory.instance().getLanguage(code);
Document doc = new Document(buildXML(language));
return new JDOMSource(doc);
} catch (Exception ex) {
throw new TransformerException(ex);
}
}
private Element buildXML(MCRLanguage language) {
Element xml = new Element("language");
for (Entry<MCRLanguageCodeType, String> entry : language.getCodes().entrySet()) {
xml.setAttribute(entry.getKey().name(), entry.getValue());
}
for (Entry<MCRLanguage, String> entry : language.getLabels().entrySet()) {
Element label = new Element("label");
label.setText(entry.getValue());
MCRLanguageXML.setXMLLangAttribute(entry.getKey(), label);
xml.addContent(label);
}
xml.setAttribute("rtl",
MCRLanguageOrientationHelper.isRTL(language.getCode(MCRLanguageCodeType.xmlCode)) ? "true" : "false");
return xml;
}
}
| 2,625 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageXML.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/language/MCRLanguageXML.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.datamodel.language;
import org.jdom2.Element;
import org.jdom2.Namespace;
/**
* Helper class to map xml:lang and lang attributes in XML to MCRLanguage
*
* @author Frank Lützenkirchen
*/
public class MCRLanguageXML {
/**
* Sets the lang attribute to the ISO 639-2 bibliographic code of the given language
*/
public static void setLangAttribute(MCRLanguage lang, Element element) {
String code = lang.getCode(MCRLanguageCodeType.biblCode);
if (code != null) {
element.setAttribute("lang", code);
}
}
/**
* Sets the xml:lang attribute to the ISO 639-1 code of the given language
*/
public static void setXMLLangAttribute(MCRLanguage lang, Element element) {
element.setAttribute("lang", lang.getCode(MCRLanguageCodeType.xmlCode), Namespace.XML_NAMESPACE);
}
/**
* Returns the language of the given XML element, by inspecting the xml:lang or lang attribute.
* If neither exists, the default language is returned.
*/
public static MCRLanguage getLanguage(Element element) {
String code = element.getAttributeValue("lang", Namespace.XML_NAMESPACE);
if ((code == null) || code.isEmpty()) {
code = element.getAttributeValue("lang");
}
if ((code == null) || code.isEmpty()) {
return MCRLanguageFactory.instance().getDefaultLanguage();
} else {
return MCRLanguageFactory.instance().getLanguage(code);
}
}
}
| 2,259 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTransactionHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRTransactionHelper.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.common;
import java.util.List;
import java.util.ServiceLoader;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.util.concurrent.MCRPool;
public class MCRTransactionHelper {
private static final MCRPool<ServiceLoader<MCRPersistenceTransaction>> SERVICE_LOADER_POOL = new MCRPool<>(
Runtime.getRuntime().availableProcessors(), () -> ServiceLoader
.load(MCRPersistenceTransaction.class, MCRClassTools.getClassLoader()));
private static final ThreadLocal<List<MCRPersistenceTransaction>> TRANSACTION = ThreadLocal
.withInitial(MCRTransactionHelper::getPersistenceTransactions);
/**
* performs a safe operation on the serviceLoader backed by an internal ServiceLoader pool
* @param f function that runs with the service loader
* @param defaultValue a fallback default if a service loader could not be acquired
* @return result of operation <code>f</code>
*/
private static <V> V applyServiceLoader(Function<ServiceLoader<MCRPersistenceTransaction>, V> f, V defaultValue) {
final ServiceLoader<MCRPersistenceTransaction> serviceLoader;
try {
serviceLoader = SERVICE_LOADER_POOL.acquire();
} catch (InterruptedException e) {
return defaultValue;
}
try {
return f.apply(serviceLoader);
} finally {
SERVICE_LOADER_POOL.release(serviceLoader);
}
}
private static List<MCRPersistenceTransaction> getPersistenceTransactions() {
return applyServiceLoader(sl -> sl.stream()
.map(ServiceLoader.Provider::get)
.filter(MCRPersistenceTransaction::isReady)
.collect(Collectors.toUnmodifiableList()), List.of());
}
public static boolean isDatabaseAccessEnabled() {
return MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)
&& applyServiceLoader(sl -> sl.stream().findAny().isPresent(), false); //impl present
}
/**
* commits the database transaction. Commit is only done if {@link #isTransactionActive()} returns true.
*/
public static void commitTransaction() {
if (isTransactionActive()) {
TRANSACTION.get().forEach(MCRPersistenceTransaction::commit);
TRANSACTION.remove();
}
MCRSessionMgr.getCurrentSession().submitOnCommitTasks();
}
/**
* Forces the database transaction to roll back. Roll back is only performed if {@link #isTransactionActive()}
* returns true.
*/
public static void rollbackTransaction() {
if (isTransactionActive()) {
TRANSACTION.get().forEach(MCRPersistenceTransaction::rollback);
TRANSACTION.remove();
}
}
/**
* Mark the current resource transaction so that the only possible outcome of the transaction is for the
* transaction to be rolled back.
*/
public static void setRollbackOnly() {
if (isTransactionActive()) {
TRANSACTION.get().forEach(MCRPersistenceTransaction::setRollbackOnly);
}
}
/**
* Is the transaction still alive?
*
* @return true if the transaction is still alive
*/
public static boolean isTransactionActive() {
return isDatabaseAccessEnabled() && TRANSACTION.get().stream().anyMatch(MCRPersistenceTransaction::isActive);
}
/**
* Determine whether the current resource transaction has been marked for rollback.
* @return boolean indicating whether the transaction has been marked for rollback
*/
public static boolean transactionRequiresRollback() {
return isTransactionActive() && TRANSACTION.get().stream().anyMatch(MCRPersistenceTransaction::getRollbackOnly);
}
/**
* starts a new database transaction.
*/
public static void beginTransaction() {
if (isDatabaseAccessEnabled()) {
TRANSACTION.get().forEach(MCRPersistenceTransaction::begin);
}
}
}
| 4,826 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCatchException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRCatchException.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.common;
/**
* Instances of this class represent a general exception thrown by any part of
* the MyCoRe implementation classes.
*
* Note that this class extends <code>java.lang.Exception</code>. Any call of
* a method that throws subclass of this class must be catched and handled in
* some way.
*
* @author Thomas Scheffler (yagee)
*
* @see java.lang.Exception
*/
public class MCRCatchException extends Exception {
private static final long serialVersionUID = -2244850451757768863L;
/**
* Creates a new MCRCatchException with an error message
*
* @param message
* the error message for this exception
*/
public MCRCatchException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* Note that the detail message associated with cause is not automatically
* incorporated in this exception's detail message.
*
* @param message
* the detail message
* @param cause the
* cause (A null value is permitted, and indicates that the cause
* is nonexistent or unknown.)
* @see Exception#Exception(java.lang.String, java.lang.Throwable)
*/
public MCRCatchException(String message, Throwable cause) {
super(message, cause);
}
/**
* Returns a String containing the invocation stack trace for this exception
*
* @return a String containing the invocation stack trace for this exception
* @see MCRException#getStackTraceAsString(Throwable)
*/
public String getStackTraceAsString() {
return MCRException.getStackTraceAsString(this);
}
/** Counter to prevent a recursion between getStackTrace() and toString() */
private int toStringInvocationCounter = 0;
/**
* Returns a String representation of this exception and all its properties
*
* @return a String representation of this exception and all its properties
*/
@Override
public synchronized String toString() {
// Use counter to prevent a recursion between getStackTrace() and
// toString()
toStringInvocationCounter++;
if (toStringInvocationCounter > 1) {
return super.toString();
}
StringBuilder sb = new StringBuilder();
sb.append("MyCoRe Exception: ").append(getClass().getName());
sb.append("\n\n");
sb.append("Message:\n");
sb.append(getMessage()).append("\n\n");
sb.append("Stack trace:\n");
sb.append(getStackTraceAsString());
if (getCause() != null) {
sb.append("\n");
sb.append("This exception was thrown because of the following underlying exception:\n\n");
sb.append(getCause().getClass().getName());
sb.append("\n\n");
String msg = getCause().getLocalizedMessage();
if (msg != null) {
sb.append("Message:\n").append(msg).append("\n\n");
}
sb.append("Stack trace:\n");
sb.append(MCRException.getStackTraceAsString(getCause()));
}
toStringInvocationCounter--;
return sb.toString();
}
}
| 4,004 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultHTTPClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRDefaultHTTPClient.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.common;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.http.client.cache.HttpCacheContext;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.CachingHttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.services.http.MCRHttpUtils;
public class MCRDefaultHTTPClient implements MCRHTTPClient {
private static Logger logger = LogManager.getLogger();
private long maxObjectSize;
private int maxCacheEntries;
private int requestTimeout;
private CloseableHttpClient restClient;
public MCRDefaultHTTPClient() {
CacheConfig cacheConfig = CacheConfig.custom()
.setMaxObjectSize(maxObjectSize)
.setMaxCacheEntries(maxCacheEntries)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(requestTimeout)
.setSocketTimeout(requestTimeout)
.build();
this.restClient = CachingHttpClients.custom()
.setCacheConfig(cacheConfig)
.setDefaultRequestConfig(requestConfig)
.setUserAgent(MCRHttpUtils.getHttpUserAgent())
.useSystemProperties()
.build();
MCRShutdownHandler.getInstance().addCloseable(this::close);
}
@MCRProperty(name = "MaxObjectSize")
public void setMaxObjectSize(String size) {
this.maxObjectSize = Long.parseLong(size);
}
@MCRProperty(name = "MaxCacheEntries")
public void setMaxCacheEntries(String size) {
this.maxCacheEntries = Integer.parseInt(size);
}
@MCRProperty(name = "RequestTimeout")
public void setRequestTimeout(String size) {
this.requestTimeout = Integer.parseInt(size);
}
public void close() {
try {
restClient.close();
} catch (IOException e) {
logger.warn("Exception while closing http client.", e);
}
}
@Override
public MCRContent get(URI hrefURI) throws IOException {
HttpCacheContext context = HttpCacheContext.create();
HttpGet get = new HttpGet(hrefURI);
MCRContent retContent = null;
try (CloseableHttpResponse response = restClient.execute(get, context);
InputStream content = response.getEntity().getContent();) {
logger.debug("http query: {}", hrefURI);
logger.debug("http resp status: {}", response.getStatusLine());
logger.debug(() -> getCacheDebugMsg(hrefURI, context));
retContent = (new MCRStreamContent(content)).getReusableCopy();
} finally {
get.reset();
}
return retContent;
}
private String getCacheDebugMsg(URI hrefURI, HttpCacheContext context) {
return hrefURI.toASCIIString() + ": " +
switch (context.getCacheResponseStatus()) {
case CACHE_HIT -> "A response was generated from the cache with no requests sent upstream";
case CACHE_MODULE_RESPONSE -> "The response was generated directly by the caching module";
case CACHE_MISS -> "The response came from an upstream server";
case VALIDATED -> "The response was generated from the cache after validating the entry "
+ "with the origin server";
};
}
}
| 4,570 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCacheManagerMBean.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRCacheManagerMBean.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.common;
public interface MCRCacheManagerMBean {
long getSize();
long getRequests();
long getEvictions();
long getHits();
long getCapacity();
void setCapacity(long size);
double getHitRate();
double getFillRate();
void clear();
}
| 1,022 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGsonUTCDateAdapter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRGsonUTCDateAdapter.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.common;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.google.gson.internal.bind.util.ISO8601Utils;
// https://stackoverflow.com/questions/26044881/java-date-to-utc-using-gson
public class MCRGsonUTCDateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private final DateFormat dateFormat;
private final DateFormat enUsFormat;
private final DateFormat enUsFormat2;
private final DateFormat localFormat;
public MCRGsonUTCDateAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); //This is the format I need
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); //converts the date to UTC
enUsFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US);
enUsFormat2 = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.US);
localFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.ROOT);
}
@Override
public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
@Override
public synchronized Date deserialize(JsonElement json, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(json.getAsString());
} catch (ParseException e) {
// backward compatibility (parse like default GSON does)
synchronized (localFormat) {
try {
return localFormat.parse(json.getAsString());
} catch (ParseException ignored) {
}
try {
return enUsFormat2.parse(json.getAsString());
} catch (ParseException ignored) {
}
try {
return enUsFormat.parse(json.getAsString());
} catch (ParseException ignored) {
}
try {
return ISO8601Utils.parse(json.getAsString(), new ParsePosition(0));
} catch (ParseException e1) {
throw new JsonSyntaxException(json.getAsString(), e);
}
}
}
}
}
| 3,543 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.