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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRSimpleModelJSONConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRSimpleModelJSONConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mets.model.converter;
import org.mycore.mets.model.simple.MCRMetsAltoLink;
import org.mycore.mets.model.simple.MCRMetsLink;
import org.mycore.mets.model.simple.MCRMetsSimpleModel;
import com.google.gson.GsonBuilder;
/**
* This class converts MCRMetsSimpleModel to JSON
* @author Sebastian Hofmann(mcrshofm)
*/
public class MCRSimpleModelJSONConverter {
public static String toJSON(MCRMetsSimpleModel model) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MCRMetsLink.class, new MCRMetsLinkTypeAdapter());
gsonBuilder.registerTypeAdapter(MCRMetsAltoLink.class, new MCRAltoLinkTypeAdapter());
gsonBuilder.setPrettyPrinting();
return gsonBuilder.create().toJson(model);
}
}
| 1,506 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSimpleModelXMLConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRSimpleModelXMLConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mets.model.converter;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.jdom2.Document;
import org.mycore.common.MCRException;
import org.mycore.mets.model.Mets;
import org.mycore.mets.model.files.FLocat;
import org.mycore.mets.model.files.File;
import org.mycore.mets.model.files.FileGrp;
import org.mycore.mets.model.simple.MCRMetsPage;
import org.mycore.mets.model.simple.MCRMetsSection;
import org.mycore.mets.model.simple.MCRMetsSimpleModel;
import org.mycore.mets.model.struct.Area;
import org.mycore.mets.model.struct.Fptr;
import org.mycore.mets.model.struct.LOCTYPE;
import org.mycore.mets.model.struct.LogicalDiv;
import org.mycore.mets.model.struct.LogicalStructMap;
import org.mycore.mets.model.struct.PhysicalDiv;
import org.mycore.mets.model.struct.PhysicalStructMap;
import org.mycore.mets.model.struct.PhysicalSubDiv;
import org.mycore.mets.model.struct.Seq;
import org.mycore.mets.model.struct.SmLink;
import org.mycore.mets.model.struct.StructLink;
/**
* This Class converts MCRMetsSimpleModel to JDOM XML.
* @author Sebastian Hofmann(mcrshofm)
*/
public class MCRSimpleModelXMLConverter {
public static final String DEFAULT_PHYSICAL_TYPE = "page";
public static final String PHYSICAL_ID_PREFIX = "phys_";
public static final String LOGICAL_ID_PREFIX = "log_";
/**
* Converts MetsSimpleModel to XML
* @param msm the MetsSimpleModel which should be converted
* @return xml
*/
public static Document toXML(MCRMetsSimpleModel msm) {
Mets mets = new Mets();
Hashtable<MCRMetsPage, String> pageIdMap = new Hashtable<>();
Map<String, String> idToNewIDMap = new Hashtable<>();
buildPhysicalPages(msm, mets, pageIdMap, idToNewIDMap);
Hashtable<MCRMetsSection, String> sectionIdMap = new Hashtable<>();
buildLogicalPages(msm, mets, sectionIdMap, idToNewIDMap);
StructLink structLink = mets.getStructLink();
msm.getSectionPageLinkList().stream()
.map((metsLink) -> {
MCRMetsSection section = metsLink.getFrom();
MCRMetsPage page = metsLink.getTo();
String fromId = sectionIdMap.get(section);
String toId = pageIdMap.get(page);
return new SmLink(fromId, toId);
})
.forEach(structLink::addSmLink);
return mets.asDocument();
}
private static void buildPhysicalPages(MCRMetsSimpleModel msm, Mets mets, Map<MCRMetsPage, String> pageIdMap,
Map<String, String> idToNewIDMap) {
List<MCRMetsPage> pageList = msm.getMetsPageList();
PhysicalStructMap structMap = (PhysicalStructMap) mets.getStructMap(PhysicalStructMap.TYPE);
structMap.setDivContainer(
new PhysicalDiv(PHYSICAL_ID_PREFIX + UUID.randomUUID(), PhysicalDiv.TYPE_PHYS_SEQ));
for (MCRMetsPage page : pageList) {
String id = page.getId();
PhysicalSubDiv physicalSubDiv = new PhysicalSubDiv(id, DEFAULT_PHYSICAL_TYPE);
String orderLabel = page.getOrderLabel();
if (orderLabel != null) {
physicalSubDiv.setOrderLabel(orderLabel);
}
String contentIds = page.getContentIds();
if (contentIds != null) {
physicalSubDiv.setContentIds(contentIds);
}
structMap.getDivContainer().add(physicalSubDiv);
pageIdMap.put(page, id);
page.getFileList().forEach((simpleFile) -> {
String href = simpleFile.getHref();
String fileID = simpleFile.getId();
String mimeType = simpleFile.getMimeType();
String use = simpleFile.getUse();
idToNewIDMap.put(simpleFile.getId(), fileID);
File file = new File(fileID, mimeType);
FLocat fLocat = new FLocat(LOCTYPE.URL, href);
file.setFLocat(fLocat);
FileGrp fileGrp = getFileGroup(mets, use);
fileGrp.addFile(file);
physicalSubDiv.add(new Fptr(fileID));
});
}
}
private static void buildLogicalPages(MCRMetsSimpleModel msm, Mets mets, Map<MCRMetsSection, String> sectionIdMap,
Map<String, String> idToNewIDMap) {
LogicalStructMap logicalStructMap = (LogicalStructMap) mets.getStructMap(LogicalStructMap.TYPE);
MCRMetsSection rootSection = msm.getRootSection();
String type = rootSection.getType();
String label = rootSection.getLabel();
String id = rootSection.getId();
LogicalDiv logicalDiv = new LogicalDiv(id, type, label);
sectionIdMap.put(rootSection, id);
for (MCRMetsSection metsSection : rootSection.getMetsSectionList()) {
buildLogicalSubDiv(metsSection, logicalDiv, sectionIdMap, idToNewIDMap);
}
logicalStructMap.setDivContainer(logicalDiv);
}
private static void buildLogicalSubDiv(MCRMetsSection metsSection, LogicalDiv parent,
Map<MCRMetsSection, String> sectionIdMap, Map<String, String> idToNewIDMap) {
String id = metsSection.getId();
LogicalDiv logicalSubDiv = new LogicalDiv(id, metsSection.getType(), metsSection.getLabel());
if (metsSection.getAltoLinks().size() > 0) {
Fptr fptr = new Fptr();
List<Seq> seqList = fptr.getSeqList();
Seq seq = new Seq();
seqList.add(seq);
metsSection.getAltoLinks().forEach(al -> {
Area area = new Area();
seq.getAreaList().add(area);
area.setBetype("IDREF");
area.setBegin(al.getBegin());
area.setEnd(al.getEnd());
String oldID = al.getFile().getId();
if (!idToNewIDMap.containsKey(oldID)) {
throw new MCRException("Could not get new id for: " + oldID);
}
area.setFileId(idToNewIDMap.get(oldID));
});
logicalSubDiv.getFptrList().add(fptr);
}
sectionIdMap.put(metsSection, id);
parent.add(logicalSubDiv);
for (MCRMetsSection section : metsSection.getMetsSectionList()) {
buildLogicalSubDiv(section, logicalSubDiv, sectionIdMap, idToNewIDMap);
}
}
private static FileGrp getFileGroup(Mets mets, String use) {
FileGrp fileGroup = mets.getFileSec().getFileGroup(use);
if (fileGroup == null) {
fileGroup = new FileGrp(use);
mets.getFileSec().addFileGrp(fileGroup);
}
return fileGroup;
}
}
| 7,414 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLSimpleModelConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRXMLSimpleModelConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mets.model.converter;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.jdom2.Document;
import org.mycore.common.MCRException;
import org.mycore.mets.model.Mets;
import org.mycore.mets.model.files.FileGrp;
import org.mycore.mets.model.simple.MCRMetsAltoLink;
import org.mycore.mets.model.simple.MCRMetsFile;
import org.mycore.mets.model.simple.MCRMetsLink;
import org.mycore.mets.model.simple.MCRMetsPage;
import org.mycore.mets.model.simple.MCRMetsSection;
import org.mycore.mets.model.simple.MCRMetsSimpleModel;
import org.mycore.mets.model.struct.IStructMap;
import org.mycore.mets.model.struct.LogicalDiv;
import org.mycore.mets.model.struct.LogicalStructMap;
import org.mycore.mets.model.struct.PhysicalStructMap;
import org.mycore.mets.model.struct.PhysicalSubDiv;
/**
* This Class is used to converts mets.xml to MCRMetsSimpleModel.
* @author Sebastian Hofmann(mcrshofm)
*/
public class MCRXMLSimpleModelConverter {
/**
* Converts a Document to MetsSimpleModel
*
* @param metsDocument the Document which should be converted
* @return the converted MetsSimpleModel
*/
public static MCRMetsSimpleModel fromXML(Document metsDocument) {
Mets mets = new Mets(metsDocument);
MCRMetsSimpleModel msm = new MCRMetsSimpleModel();
Map<String, MCRMetsPage> idPageMap = new Hashtable<>();
Map<String, MCRMetsFile> idFileMap = buildidFileMap(mets);
List<MCRMetsPage> metsPageList = buildPageList(mets, idPageMap, idFileMap);
msm.getMetsPageList().addAll(metsPageList);
Map<String, MCRMetsSection> idSectionMap = new Hashtable<>();
MCRMetsSection rootMetsSection = buidRootSection(mets, idSectionMap, idFileMap);
msm.setRootSection(rootMetsSection);
linkPages(mets, idSectionMap, idPageMap, msm);
return msm;
}
private static MCRMetsSection buidRootSection(Mets mets, Map<String, MCRMetsSection> idSectionMap,
Map<String, MCRMetsFile> idFileMap) {
IStructMap structMap = mets.getStructMap(LogicalStructMap.TYPE);
LogicalStructMap logicalStructMap = (LogicalStructMap) structMap;
LogicalDiv divContainer = logicalStructMap.getDivContainer();
return buildSection(divContainer, idSectionMap, null, idFileMap);
}
private static MCRMetsSection buildSection(LogicalDiv current, Map<String, MCRMetsSection> idSectionMap,
MCRMetsSection parent, Map<String, MCRMetsFile> idFileMap) {
MCRMetsSection metsSection = new MCRMetsSection();
metsSection.setId(current.getId());
metsSection.setLabel(current.getLabel());
metsSection.setType(current.getType());
metsSection.setParent(parent);
current.getFptrList().forEach(
fptr -> fptr.getSeqList().forEach(
seq -> seq.getAreaList().forEach(
area -> {
String fileId = area.getFileId();
String begin = area.getBegin();
String end = area.getEnd();
if (!idFileMap.containsKey(fileId)) {
throw new MCRException("No file with id " + fileId + " found!");
}
MCRMetsFile file = idFileMap.get(fileId);
MCRMetsAltoLink e = new MCRMetsAltoLink(file, begin, end);
metsSection.addAltoLink(e);
})));
if (idSectionMap != null) {
idSectionMap.put(current.getId(), metsSection);
}
current.getChildren()
.stream()
.map(section -> MCRXMLSimpleModelConverter.buildSection(section, idSectionMap, metsSection, idFileMap))
.forEachOrdered(metsSection::addSection);
return metsSection;
}
private static List<MCRMetsPage> buildPageList(Mets mets, Map<String, MCRMetsPage> idPageMap,
Map<String, MCRMetsFile> idFileMap) {
PhysicalStructMap physicalStructMap = (PhysicalStructMap) mets.getStructMap(PhysicalStructMap.TYPE);
List<PhysicalSubDiv> physicalSubDivs = physicalStructMap.getDivContainer().getChildren();
List<MCRMetsPage> result = new ArrayList<>();
physicalSubDivs.stream()
.map(physicalSubDiv -> {
// Convert PhysicalSubDiv to MetsPage
MCRMetsPage metsPage = new MCRMetsPage();
metsPage.setId(physicalSubDiv.getId());
metsPage.setOrderLabel(physicalSubDiv.getOrderLabel());
metsPage.setContentIds(physicalSubDiv.getContentIds());
// Add all MetsFile to the MetsPage
List<MCRMetsFile> fileList = metsPage.getFileList();
physicalSubDiv.getChildren().stream()
.map(file -> idFileMap.get(file.getFileId()))
.forEachOrdered(fileList::add);
// return a entry of physicalSubDiv.id and MetsPage
return new AbstractMap.SimpleEntry<>(physicalSubDiv.getId(), metsPage);
})
.forEachOrdered(entry -> {
// Put page to list
result.add(entry.getValue());
// Put that generated entry to a Hashtable
idPageMap.put(entry.getKey(), entry.getValue());
});
return result;
}
private static void linkPages(Mets mets, Map<String, MCRMetsSection> idSectionMap,
Map<String, MCRMetsPage> idPageMap, MCRMetsSimpleModel metsSimpleModel) {
mets.getStructLink().getSmLinks().stream()
.filter(smLink -> idSectionMap.containsKey(smLink.getFrom()) && idPageMap.containsKey(smLink.getTo()))
.map(smLink -> {
MCRMetsSection metsSection = idSectionMap.get(smLink.getFrom());
MCRMetsPage metsPage = idPageMap.get(smLink.getTo());
return new MCRMetsLink(metsSection, metsPage);
}).forEach(metsSimpleModel.getSectionPageLinkList()::add);
}
private static Map<String, MCRMetsFile> buildidFileMap(Mets mets) {
Map<String, MCRMetsFile> idMetsFileMap = new HashMap<>();
mets.getFileSec().getFileGroups().forEach(
fileGroup -> addFilesFromGroup(idMetsFileMap, fileGroup));
return idMetsFileMap;
}
private static void addFilesFromGroup(Map<String, MCRMetsFile> idPageMap, FileGrp fileGroup) {
String fileGroupUse = fileGroup.getUse();
fileGroup.getFileList().forEach(
file -> idPageMap.put(file.getId(),
new MCRMetsFile(file.getId(), file.getFLocat().getHref(), file.getMimeType(), fileGroupUse)));
}
}
| 7,539 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJSONSimpleModelConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRJSONSimpleModelConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mets.model.converter;
import static java.util.stream.Collectors.toList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.mycore.common.MCRException;
import org.mycore.mets.model.MCRMetsModelHelper;
import org.mycore.mets.model.converter.MCRAltoLinkTypeAdapter.MCRAltoLinkPlaceHolder;
import org.mycore.mets.model.converter.MCRMetsLinkTypeAdapter.MCRMetsLinkPlaceholder;
import org.mycore.mets.model.simple.MCRMetsAltoLink;
import org.mycore.mets.model.simple.MCRMetsFile;
import org.mycore.mets.model.simple.MCRMetsLink;
import org.mycore.mets.model.simple.MCRMetsPage;
import org.mycore.mets.model.simple.MCRMetsSection;
import org.mycore.mets.model.simple.MCRMetsSimpleModel;
import com.google.gson.GsonBuilder;
/**
* This class converts JSON to MCRMetsSimpleModel.
* @author Sebastian Hofmann(mcrshofm)
*/
public class MCRJSONSimpleModelConverter {
public static MCRMetsSimpleModel toSimpleModel(String model) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MCRMetsLink.class, new MCRMetsLinkTypeAdapter());
gsonBuilder.registerTypeAdapter(MCRMetsAltoLink.class, new MCRAltoLinkTypeAdapter());
gsonBuilder.setPrettyPrinting();
MCRMetsSimpleModel metsSimpleModel = gsonBuilder.create().fromJson(model, MCRMetsSimpleModel.class);
Hashtable<String, MCRMetsPage> idPageMap = new Hashtable<>();
metsSimpleModel.getMetsPageList().stream().forEach(page -> idPageMap.put(page.getId(), page));
final Map<String, MCRMetsFile> idMCRMetsFileMap = extractIdFileMap(metsSimpleModel.getMetsPageList());
Hashtable<String, MCRMetsSection> idSectionMap = new Hashtable<>();
processSections(metsSimpleModel.getRootSection(), idSectionMap, idMCRMetsFileMap);
List<MCRMetsLink> sectionPageLinkList = metsSimpleModel.getSectionPageLinkList();
List<MCRMetsLink> metsLinks = sectionPageLinkList
.stream()
.map((link) -> {
if (link instanceof MCRMetsLinkPlaceholder placeholder) {
MCRMetsSection metsSection = idSectionMap.get(placeholder.getFromString());
MCRMetsPage metsPage = idPageMap.get(placeholder.getToString());
return new MCRMetsLink(metsSection, metsPage);
} else {
return link;
}
}).collect(toList());
sectionPageLinkList.clear();
sectionPageLinkList.addAll(metsLinks);
return metsSimpleModel;
}
private static Map<String, MCRMetsFile> extractIdFileMap(List<MCRMetsPage> pages) {
final Map<String, MCRMetsFile> idFileMap = new Hashtable<>();
pages.forEach(p -> p.getFileList().stream()
.filter(file -> file.getUse().equals(MCRMetsModelHelper.ALTO_USE))
.forEach(file -> idFileMap.put(file.getId(), file)));
return idFileMap;
}
private static void processSections(MCRMetsSection current, Hashtable<String, MCRMetsSection> idSectionTable,
Map<String, MCRMetsFile> idFileMap) {
idSectionTable.put(current.getId(), current);
final List<MCRMetsAltoLink> altoLinks = current.getAltoLinks().stream().map(altoLink -> {
if (altoLink instanceof MCRAltoLinkPlaceHolder ph) {
if (!idFileMap.containsKey(ph.getFileID())) {
throw new MCRException(
"Could not parse link from section to alto! (FileID of alto not found in file list)");
}
return new MCRMetsAltoLink(idFileMap.get(ph.getFileID()), ph.getBegin(), ph.getEnd());
}
return altoLink;
}).collect(toList());
current.setAltoLinks(altoLinks);
current.getMetsSectionList().forEach((child) -> {
child.setParent(current);
processSections(child, idSectionTable, idFileMap);
});
}
}
| 4,710 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetsLinkTypeAdapter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRMetsLinkTypeAdapter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mets.model.converter;
import java.io.IOException;
import org.mycore.mets.model.simple.MCRMetsLink;
import org.mycore.mets.model.simple.MCRMetsPage;
import org.mycore.mets.model.simple.MCRMetsSection;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* This is a helper class to help GSON to convert simple model to JSON.
* @author Sebastian Hofmann(mcrshofm)
*/
public class MCRMetsLinkTypeAdapter extends TypeAdapter<MCRMetsLink> {
@Override
public void write(JsonWriter jsonWriter, MCRMetsLink metsLink) throws IOException {
jsonWriter.beginObject();
jsonWriter.name("from").value(metsLink.getFrom().getId());
jsonWriter.name("to").value(metsLink.getTo().getId());
jsonWriter.endObject();
}
@Override
public MCRMetsLink read(JsonReader jsonReader) throws IOException {
MCRMetsLinkPlaceholder ml = new MCRMetsLinkPlaceholder();
jsonReader.beginObject();
while (jsonReader.hasNext()) {
switch (jsonReader.nextName()) {
case "from" -> ml.setFromString(jsonReader.nextString());
case "to" -> ml.setToString(jsonReader.nextString());
}
}
jsonReader.endObject();
return ml;
}
protected static class MCRMetsLinkPlaceholder extends MCRMetsLink {
public static final String PLACEHOLDER_EXCEPTION_MESSAGE = "this is a placeholder class";
private String fromString;
private String toString;
public String getFromString() {
return fromString;
}
public void setFromString(String fromString) {
this.fromString = fromString;
}
public String getToString() {
return toString;
}
public void setToString(String toString) {
this.toString = toString;
}
@Override
public MCRMetsPage getTo() {
throw new RuntimeException(PLACEHOLDER_EXCEPTION_MESSAGE);
}
@Override
public MCRMetsSection getFrom() {
throw new RuntimeException(PLACEHOLDER_EXCEPTION_MESSAGE);
}
@Override
public void setFrom(MCRMetsSection from) {
throw new RuntimeException(PLACEHOLDER_EXCEPTION_MESSAGE);
}
@Override
public void setTo(MCRMetsPage to) {
throw new RuntimeException(PLACEHOLDER_EXCEPTION_MESSAGE);
}
}
}
| 3,254 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAltoLinkTypeAdapter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/converter/MCRAltoLinkTypeAdapter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mets.model.converter;
import java.io.IOException;
import org.mycore.common.MCRException;
import org.mycore.mets.model.simple.MCRMetsAltoLink;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* This is a helper class to help GSON to convert simple model to JSON.
*
* @author Sebastian Hofmann(mcrshofm)
*/
public class MCRAltoLinkTypeAdapter extends TypeAdapter<MCRMetsAltoLink> {
@Override
public void write(JsonWriter jsonWriter, MCRMetsAltoLink altoLink) throws IOException {
jsonWriter.beginObject();
jsonWriter.name("altoFile").value(altoLink.getFile().getId());
jsonWriter.name("begin").value(altoLink.getBegin());
jsonWriter.name("end").value(altoLink.getEnd());
jsonWriter.endObject();
}
@Override
public MCRMetsAltoLink read(JsonReader jsonReader) throws IOException {
String fileID = null;
String begin = null;
String end = null;
jsonReader.beginObject();
while (jsonReader.hasNext()) {
//CSOFF: InnerAssignment
switch (jsonReader.nextName()) {
case "altoFile" -> fileID = jsonReader.nextString();
case "begin" -> begin = jsonReader.nextString();
case "end" -> end = jsonReader.nextString();
}
//CSON: InnerAssignment
}
jsonReader.endObject();
if (fileID == null || begin == null || end == null) {
throw new MCRException("Cannot read MCRMetsAltoLink! FileID && begin && end expected!");
}
return new MCRAltoLinkPlaceHolder(fileID, begin, end);
}
/**
* Created by sebastian on 25.11.15.
*/
public static class MCRAltoLinkPlaceHolder extends MCRMetsAltoLink {
public static final String PLACEHOLDER_EXCEPTION_MESSAGE = "this is a placeholder class";
private String fileID;
public MCRAltoLinkPlaceHolder(String fileID, String begin, String end) {
super(null, begin, end);
this.fileID = fileID;
}
public String getFileID() {
return fileID;
}
public void setFileID(String fileID) {
this.fileID = fileID;
}
}
}
| 3,038 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileBaseCacheObjectIDGeneratorTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/common/MCRFileBaseCacheObjectIDGeneratorTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.datamodel.metadata.MCRObjectID;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class MCRFileBaseCacheObjectIDGeneratorTest extends MCRTestCase {
public static final int GENERATOR_COUNT = 10;
public static final int TEST_IDS = 100;
private static final Logger LOGGER = LogManager.getLogger();
@Test
public void getNextFreeId() throws IOException {
Files.createDirectories(MCRFileBaseCacheObjectIDGenerator.getDataDirPath());
var generatorList = new ArrayList<MCRFileBaseCacheObjectIDGenerator>();
for (int i = 0; i < GENERATOR_COUNT; i++) {
generatorList.add(new MCRFileBaseCacheObjectIDGenerator());
}
// need thread safe list of generated ids
var generatedIds = Collections.synchronizedList(new ArrayList<MCRObjectID>());
IntStream.range(0, TEST_IDS)
.parallel()
.forEach(i -> {
LOGGER.info("Generating ID {}", i);
var generator = generatorList.get(i % GENERATOR_COUNT);
MCRObjectID id = generator.getNextFreeId("junit", "test");
generatedIds.add(id);
});
// check if all ids are unique
assertEquals(TEST_IDS, generatedIds.size());
assertEquals(TEST_IDS, generatedIds.stream().distinct().count());
// check if there is no space in the ids
var sortedIds = new ArrayList<>(generatedIds);
Collections.sort(sortedIds);
for (int i = 0; i < sortedIds.size() - 1; i++) {
assertEquals(i+1, sortedIds.get(i).getNumberAsInteger());
}
}
}
| 2,692 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataURLTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/common/MCRDataURLTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.nio.charset.IllegalCharsetNameException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* @author RenΓ© Adler (eagle)
*
*/
public class MCRDataURLTest extends MCRTestCase {
private static final String[] VALID = {
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIBAMAAAA2IaO4AAAAFVBMVEXk5OTn5+ft7e319fX29vb5+fn///++GUmVAAAALUlEQVQIHWNICnYLZnALTgpmMGYIFWYIZTA2ZFAzTTFlSDFVMwVyQhmAwsYMAKDaBy0axX/iAAAAAElFTkSuQmCC",
" data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIBAMAAAA2IaO4AAAAFVBMVEXk5OTn5+ft7e319fX29vb5+fn///++GUmVAAAALUlEQVQIHWNICnYLZnALTgpmMGYIFWYIZTA2ZFAzTTFlSDFVMwVyQhmAwsYMAKDaBy0axX/iAAAAAElFTkSuQmCC ",
" data:,Hello%2C%20World!", " data:,Hello World!", " data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E",
"data:,A%20brief%20note", "data:text/html;charset=US-ASCII,%3Ch1%3EHello!%3C%2Fh1%3E",
"data:text/html;charset=UTF-8,%3Ch1%3EHello!%3C%2Fh1%3E",
"data:text/html;charset=US-ASCII;param=extra,%3Ch1%3EHello!%3C%2Fh1%3E",
"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48cmVjdCBmaWxsPSIjMDBCMUZGIiB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIvPjwvc3ZnPg==" };
private static final String[] INVALID = { " data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D",
"dataxbase64", "data:HelloWorld", "data:text/html;charset=,%3Ch1%3EHello!%3C%2Fh1%3E",
"data:text/html;charset,%3Ch1%3EHello!%3C%2Fh1%3E",
"data:base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC",
"", "http://wikipedia.org", "base64",
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC" };
private static final String TEST_XML = "<testxml>Blah</testxml>";
private static final String TEST_EXCEPTION_XML = "<xml><testxml>Blah</testxml><testxml>Blub</testxml></xml>";
@Test
public void testParseValid() {
for (final String url : VALID) {
try {
MCRDataURL dataURL = MCRDataURL.parse(url);
assertNotNull(dataURL);
} catch (IllegalCharsetNameException | MalformedURLException e) {
fail(url + ": " + e.getMessage());
}
}
}
@Test
public void testParseInValid() {
for (final String url : INVALID) {
boolean thrown = false;
try {
MCRDataURL dataURL = MCRDataURL.parse(url);
assertNull(url + " is not null.", dataURL);
} catch (IllegalCharsetNameException | MalformedURLException e) {
thrown = true;
}
assertTrue(thrown);
}
}
@Test
public void testCompose() {
for (final String url : VALID) {
MCRDataURL du1;
try {
du1 = MCRDataURL.parse(url);
assertNotNull(du1);
} catch (IllegalCharsetNameException | MalformedURLException e) {
fail("unserialize " + url + ": " + e.getMessage());
return;
}
try {
MCRDataURL du2 = MCRDataURL.parse(du1.toString());
assertEquals(du1, du2);
} catch (IllegalCharsetNameException | MalformedURLException e) {
fail("serialize " + url + ": " + e.getMessage());
}
}
}
@Test
public void testComposeFromDocument()
throws ParserConfigurationException, SAXException, IOException, TransformerException {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(TEST_XML));
Document doc = db.parse(is);
String du = MCRDataURL.build(doc, MCRDataURLEncoding.BASE64.value(), "application/xml", "utf-8");
assertNotNull(du);
}
@Test(expected = IllegalArgumentException.class)
public void testException() throws ParserConfigurationException, SAXException, IOException, TransformerException {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(TEST_EXCEPTION_XML));
Document doc = db.parse(is);
MCRDataURL.build(doc.getChildNodes().item(0).getChildNodes(), MCRDataURLEncoding.BASE64.value(),
"TEXT/xml",
"utf-8");
}
}
| 6,258 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLMetadataManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/common/MCRXMLMetadataManagerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Date;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRStoreTestCase;
import org.mycore.common.content.MCRByteContent;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.xml.sax.SAXException;
/**
* @author Thomas Scheffler (yagee)
* @author Frank LΓΌtzenkirchen
*/
public class MCRXMLMetadataManagerTest extends MCRStoreTestCase {
private XMLInfo MyCoRe_document_00000001, MyCoRe_document_00000001_new, MCR_document_00000001;
private static final SAXBuilder SAX_BUILDER = new SAXBuilder();
@Override
@Before
public void setUp() throws Exception {
super.setUp();
MyCoRe_document_00000001 = new XMLInfo("MyCoRe_document_00000001",
"<object id=\"MyCoRe_document_00000001\"/>".getBytes(StandardCharsets.UTF_8), new Date());
MyCoRe_document_00000001_new = new XMLInfo("MyCoRe_document_00000001",
"<object id=\"MyCoRe_document_00000001\" update=\"true\"/>".getBytes(StandardCharsets.UTF_8), new Date());
MCR_document_00000001 = new XMLInfo("MCR_document_00000001",
"<object id=\"MCR_document_00000001\"/>".getBytes(StandardCharsets.UTF_8), new Date());
}
@Override
@After
public void tearDown() throws Exception {
for (File projectDir : getStoreBaseDir().toFile().listFiles()) {
for (File typeDir : projectDir.listFiles()) {
Files.walkFileTree(typeDir.toPath(), MCRRecursiveDeleter.instance());
typeDir.mkdir();
}
}
for (File projectDir : getSvnBaseDir().toFile().listFiles()) {
for (File typeDir : projectDir.listFiles()) {
Files.walkFileTree(typeDir.toPath(), MCRRecursiveDeleter.instance());
typeDir.mkdir();
SVNRepositoryFactory.createLocalRepository(typeDir, true, false);
}
}
super.tearDown();
}
static Document getDocument(InputStream in) throws JDOMException, IOException {
try (in) {
return SAX_BUILDER.build(in);
}
}
@Test
public void create() {
getStore().create(MyCoRe_document_00000001.id, MyCoRe_document_00000001.blob,
MyCoRe_document_00000001.lastModified);
getStore().create(MCR_document_00000001.id, MCR_document_00000001.blob, MCR_document_00000001.lastModified);
}
@Test
public void delete() {
getStore().create(MyCoRe_document_00000001.id, MyCoRe_document_00000001.blob,
MyCoRe_document_00000001.lastModified);
assertTrue(MyCoRe_document_00000001.id + " should exist", getStore().exists(MyCoRe_document_00000001.id));
try {
getStore().delete(MCR_document_00000001.id);
} catch (MCRPersistenceException e) {
//is expected as MCR_document_00000001 does not exist
}
assertTrue(MyCoRe_document_00000001.id + " should not have been deleted",
getStore().exists(MyCoRe_document_00000001.id));
}
@Test
public void update() {
getStore().create(MyCoRe_document_00000001.id, MyCoRe_document_00000001.blob,
MyCoRe_document_00000001.lastModified);
getStore().update(MyCoRe_document_00000001_new.id, MyCoRe_document_00000001_new.blob,
MyCoRe_document_00000001_new.lastModified);
try {
getStore().update(MCR_document_00000001.id, MCR_document_00000001.blob, MCR_document_00000001.lastModified);
fail("Update for non existent " + MCR_document_00000001.id + " succeeded.");
} catch (RuntimeException e) {
//this exception is expected here
}
}
@Test
public void retrieve() throws JDOMException, IOException, SAXException {
assertEquals("Stored document ID do not match:", MyCoRe_document_00000001.id.toString(),
SAX_BUILDER.build(new ByteArrayInputStream(MyCoRe_document_00000001.blob)).getRootElement()
.getAttributeValue("id"));
getStore().create(MyCoRe_document_00000001.id,
new MCRByteContent(MyCoRe_document_00000001.blob, MCR_document_00000001.lastModified.getTime()),
MyCoRe_document_00000001.lastModified);
assertTrue(getStore().exists(MyCoRe_document_00000001.id));
Document doc = getStore().retrieveXML(MyCoRe_document_00000001.id);
assertEquals("Stored document ID do not match:", MyCoRe_document_00000001.id.toString(), doc.getRootElement()
.getAttributeValue("id"));
try {
doc = getStore().retrieveXML(MCR_document_00000001.id);
if (doc != null) {
fail("Requested " + MCR_document_00000001.id + ", retrieved wrong document:\n"
+ new XMLOutputter(Format.getPrettyFormat()).outputString(doc));
}
} catch (Exception e) {
//this is ok
}
}
@Test
public void getHighestStoredID() {
Method[] methods = getStore().getClass().getMethods();
for (Method method : methods) {
if (method.getName().equals("getHighestStoredID") && method.getParameterTypes().length == 0) {
fail(
"org.mycore.datamodel.ifs2.MCRObjectMetadataStoreIFS2.getHighestStoredID() does not respect ProjectID");
}
}
}
@Test
public void exists() {
assertFalse("Object " + MyCoRe_document_00000001.id + " should not exist.",
getStore().exists(MyCoRe_document_00000001.id));
getStore().create(MyCoRe_document_00000001.id, MyCoRe_document_00000001.blob,
MyCoRe_document_00000001.lastModified);
assertTrue("Object " + MyCoRe_document_00000001.id + " should exist.",
getStore().exists(MyCoRe_document_00000001.id));
}
@Test
public void retrieveAllIDs() {
assertEquals("Store should not contain any objects.", 0, getStore().listIDs().size());
getStore().create(MyCoRe_document_00000001.id, MyCoRe_document_00000001.blob,
MyCoRe_document_00000001.lastModified);
assertTrue("Store does not contain object " + MyCoRe_document_00000001.id,
getStore().listIDs().contains(MyCoRe_document_00000001.id.toString()));
}
@Test
public void listIDs() {
assertTrue(getStore().listIDsForBase("foo_bar").isEmpty());
assertTrue(getStore().listIDsOfType("bar").isEmpty());
assertTrue(getStore().listIDs().isEmpty());
}
private static class XMLInfo {
XMLInfo(String id, byte[] blob, Date lastModified) {
this.id = MCRObjectID.getInstance(id);
this.blob = blob;
this.lastModified = lastModified;
}
MCRObjectID id;
byte[] blob;
Date lastModified;
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Manager.Class", MCRDefaultXMLMetadataManager.class.getCanonicalName());
testProperties.put("MCR.Metadata.Type.document", "true");
testProperties.put("MCR.Metadata.ObjectID.NumberPattern", "00000000");
return testProperties;
}
}
| 8,776 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRISO8601FormatChooserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/common/MCRISO8601FormatChooserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.common;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAccessor;
import org.junit.Test;
public class MCRISO8601FormatChooserTest {
@Test
public void formatChooser() {
// test year
LocalDate localDate = LocalDate.of(2001, 5, 23);
ZonedDateTime zonedDateTime = LocalDateTime.of(localDate, LocalTime.of(20, 30, 15)).atZone(ZoneId.of("UTC"));
String duration = "-16";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.YEAR_FORMAT.format(localDate),
getFormat(localDate, duration));
duration = "2006";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.YEAR_FORMAT.format(localDate),
getFormat(localDate, duration));
// test year-month
duration = "2006-01";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.YEAR_MONTH_FORMAT.format(localDate),
getFormat(localDate, duration));
// test complete
duration = "2006-01-18";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.COMPLETE_FORMAT.format(localDate),
getFormat(localDate, duration));
// test complete with hour and minutes
duration = "2006-01-18T11:08Z";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.COMPLETE_HH_MM_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
duration = "2006-01-18T11:08+02:00";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.COMPLETE_HH_MM_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
// test complete with hour, minutes and seconds
duration = "2006-01-18T11:08:20Z";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
duration = "2006-01-18T11:08:20+02:00";
assertEquals(duration + " test failed", MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
// test complete with hour, minutes, seconds and fractions of a second
duration = "2006-01-18T11:08:20.1Z";
assertEquals(duration + " test failed",
MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_SSS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
duration = "2006-01-18T11:08:20.12Z";
assertEquals(duration + " test failed",
MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_SSS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
duration = "2006-01-18T11:08:20.123Z";
assertEquals(duration + " test failed",
MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_SSS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
duration = "2006-01-18T11:08:20.1+02:00";
assertEquals(duration + " test failed",
MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_SSS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
duration = "2006-01-18T11:08:20.12+02:00";
assertEquals(duration + " test failed",
MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_SSS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
duration = "2006-01-18T11:08:20.123+02:00";
assertEquals(duration + " test failed",
MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_SSS_FORMAT.format(zonedDateTime),
getFormat(zonedDateTime, duration));
}
private String getFormat(TemporalAccessor compareDate, String duration) {
return MCRISO8601FormatChooser.getFormatter(duration, null).format(compareDate);
}
}
| 4,700 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRISO8601DateTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/common/MCRISO8601DateTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class MCRISO8601DateTest {
@BeforeClass
public static void setUpBeforeClass() {
}
@AfterClass
public static void tearDownAfterClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void getDate() {
MCRISO8601Date ts = new MCRISO8601Date();
assertNull("Date is not Null", ts.getDate());
Date dt = new Date();
ts.setDate(dt);
assertNotNull("Date is Null", ts.getDate());
assertEquals("Set date differs from get date", dt, ts.getDate());
}
@Test
public void getFormat() {
MCRISO8601Date ts = new MCRISO8601Date();
assertNull("Format used is not Null", ts.getIsoFormat());
ts.setFormat(MCRISO8601Format.COMPLETE);
assertEquals("Set format differs from get format", MCRISO8601Format.COMPLETE, ts.getIsoFormat());
}
@Test
public void getISOString() {
MCRISO8601Date ts = new MCRISO8601Date();
assertNull("Date is not Null", ts.getISOString());
Date dt = new Date();
ts.setDate(dt);
assertNotNull("Date is Null", ts.getISOString());
}
@Test
public void testFormat() {
String year = "2015";
String simpleFormat = "yyyy";
String language = "de";
//simulate MCRXMLFunctions.format();
Locale locale = Locale.forLanguageTag(language);
MCRISO8601Date mcrdate = new MCRISO8601Date();
mcrdate.setFormat((String) null);
mcrdate.setDate(year);
String formatted = mcrdate.format(simpleFormat, locale, TimeZone.getDefault().getID());
assertEquals(year, formatted);
}
/*
* Test method for
* 'org.mycore.datamodel.metadata.MCRMetaTimestamp.getSecond()'
*/
@Test
public void setDate() {
MCRISO8601Date ts = new MCRISO8601Date();
String timeString = "1997-07-16T19:20:30.452300+01:00";
System.out.println(timeString);
ts.setDate(timeString);
assertNotNull("Date is null", ts.getDate());
// this can be a different String, but point in time should be the same
System.out.println(ts.getISOString());
ts.setFormat(MCRISO8601Format.COMPLETE_HH_MM);
System.out.println(ts.getISOString());
// wrong date format for the following string should null the internal
// date.
timeString = "1997-07-16T19:20:30+01:00";
System.out.println(timeString);
ts.setDate(timeString);
assertNull("Date is not null", ts.getDate());
ts.setFormat((String) null); // check auto format determination
ts.setDate(timeString);
assertNotNull("Date is null", ts.getDate());
// check if shorter format declarations fail if String is longer
ts.setFormat(MCRISO8601Format.YEAR);
timeString = "1997-07";
ts.setDate(timeString);
assertNull("Date is not null", ts.getDate());
System.out.println(ts.getISOString());
timeString = "01.12.1986";
ts.setFormat((String) null);
ts.setDate(timeString);
assertNull("Date is not null", ts.getDate());
}
}
| 4,295 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPathTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/niofs/MCRPathTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.niofs;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.nio.file.FileStore;
import java.nio.file.Path;
import java.nio.file.spi.FileSystemProvider;
import org.junit.Test;
public class MCRPathTest {
@Test
public void startsWith() {
Path test1 = new TestMCRPath("foo", "/bar/baz");
Path test2 = new TestMCRPath("foo", "/bar");
assertTrue(test1.startsWith(test2));
test2 = new TestMCRPath("foo", "");
assertTrue(test1.startsWith(test2));
test2 = test1.resolve("..");
assertFalse(test1.startsWith(test2));
assertTrue(test1.startsWith(test2.normalize()));
test2 = test1.resolve("../bin");
assertFalse(test1.startsWith(test2));
test2 = test1.resolve(new TestMCRPath("bin", "/bar"));
assertFalse(test1.startsWith(test2));
}
private static class TestMCRPath extends MCRPath {
public static final MCRAbstractFileSystem MCR_ABSTRACT_FILE_SYSTEM = new MCRAbstractFileSystem() {
@Override
public void createRoot(String owner) {
//no implementation needed for test
}
@Override
public void removeRoot(String owner) {
//no implementation needed for test
}
@Override
public FileSystemProvider provider() {
return null;
}
@Override
public Iterable<Path> getRootDirectories() {
return null;
}
@Override
public Iterable<FileStore> getFileStores() {
return null;
}
};
TestMCRPath(String root, String path) {
super(root, path);
}
@Override
public MCRAbstractFileSystem getFileSystem() {
return MCR_ABSTRACT_FILE_SYSTEM;
}
}
}
| 2,680 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaPersonNameTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaPersonNameTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaPersonName.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaPersonNameTest extends MCRTestCase {
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsClone() {
MCRMetaPersonName person = new MCRMetaPersonName("subtag", 0);
person.setLang("de");
person.setType("mytype");
person.setFirstName("Jens Uwe");
person.setCallName("Jens");
person.setSurName("Kupferschmidt");
person.setFullName("Jens Kupferschmidt");
person.setAcademic("Dipl. Inform.");
person.setPeerage("Freiherr");
person.setNumeration("II.");
person.setTitle("Bahnverwalter");
person.setPrefix("von");
person.setAffix("zu");
Element person_xml = person.createXML();
MCRMetaPersonName person_read = new MCRMetaPersonName();
person_read.setFromDOM(person_xml);
assertEquals("read objects from XML should be equal", person, person_read);
MCRMetaPersonName person_clone = person_read.clone();
assertEquals("cloned object should be equal with original", person_read, person_clone);
}
@Test
public void testCreateXMLDoesNotChange() {
final MCRMetaPersonName name = new MCRMetaPersonName("tag", 0);
name.setFirstName("firstname");
assertEquals("firstname", name.getFirstName());
assertEquals("firstname", name.getCallName());
name.createXML();
assertEquals("firstname", name.getCallName());
}
}
| 2,531 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDPoolTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRObjectIDPoolTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.lang.ref.WeakReference;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRObjectIDPoolTest extends MCRTestCase {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void getInstance() {
Duration maxGCTime = Duration.ofSeconds(30);
runGarbageCollection(new ArrayDeque<>(Arrays.asList(false, false, true))::poll, maxGCTime);
long before = MCRObjectIDPool.getSize();
int intPart = Year.now().getValue();
String id = MCRObjectID.formatID("MyCoRe_test", intPart);
MCRObjectID mcrId = MCRObjectIDPool.getMCRObjectID(id);
WeakReference<MCRObjectID> objRef = new WeakReference<>(mcrId);
assertEquals("ObjectIDPool size is different", before + 1, MCRObjectIDPool.getSize());
mcrId = null;
runGarbageCollection(() -> objRef.get() == null, maxGCTime);
id = MCRObjectID.formatID("MyCoRe_test", intPart);
assertNull("ObjectIDPool should not contain ID anymore.", MCRObjectIDPool.getIfPresent(id));
assertEquals("ObjectIDPool size is different", before, MCRObjectIDPool.getSize());
}
private void runGarbageCollection(Supplier<Boolean> test, Duration maxTime) {
LocalDateTime start = LocalDateTime.now();
int runs = 0;
boolean succeed = test.get();
while (!maxTime.minus(Duration.between(start, LocalDateTime.now())).isNegative()) {
if (succeed) {
break;
}
runs++;
System.gc();
succeed = test.get();
}
if (!succeed) {
LogManager.getLogger().warn("Maximum wait time for garbage collector of {} exceeded.", maxTime);
}
LogManager.getLogger().info("Garbage collector ran {} times.", runs);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
return testProperties;
}
}
| 3,318 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRObjectTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRException;
import org.mycore.common.MCRTestCase;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
public class MCRObjectTest extends MCRTestCase {
private static final String TEST_OBJECT_RESOURCE_NAME = "/mcr_test_01.xml";
private MCRObject testObject;
/* (non-Javadoc)
* @see org.mycore.common.MCRTestCase#setUp()
*/
@Override
@Before
public void setUp() throws Exception {
super.setUp();
// create doc
Document testObjectDocument = loadResourceDocument(TEST_OBJECT_RESOURCE_NAME);
testObject = new MCRObject();
testObject.setFromJDOM(testObjectDocument);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
return testProperties;
}
@Test
public void createJSON() {
JsonObject json = testObject.createJSON();
assertEquals("Invalid id", "mcr_test_00000001", json.getAsJsonPrimitive("id").getAsString());
JsonObject textfield = json.getAsJsonObject("metadata").getAsJsonObject("def.textfield");
String text = textfield.getAsJsonArray("data").get(0).getAsJsonObject().getAsJsonPrimitive("text")
.getAsString();
assertEquals("Invalid text metadata", "JUnit Test object 1", text);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(json));
}
private static Document loadResourceDocument(String resource) throws MCRException, IOException, JDOMException {
URL mcrTestUrl = MCRObjectMetadataTest.class.getResource(resource);
return MCRXMLParserFactory.getValidatingParser().parseXML(new MCRURLContent(mcrTestUrl));
}
}
| 2,996 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaEnrichedLinkIDTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaEnrichedLinkIDTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.List;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
public class MCRMetaEnrichedLinkIDTest extends MCRTestCase {
protected static final String TEST_ELEMENT_NAME = "atest";
protected static final String TEST2_ELEMENT_NAME = "test";
@Test
public void testOrdering() {
final MCREditableMetaEnrichedLinkID mcrMetaEnrichedLinkID = new MCREditableMetaEnrichedLinkID();
mcrMetaEnrichedLinkID.setReference("mir_derivate_00000001", null, "");
mcrMetaEnrichedLinkID.setSubTag("derobject");
mcrMetaEnrichedLinkID.setMainDoc("main");
mcrMetaEnrichedLinkID.setOrder(1);
mcrMetaEnrichedLinkID.getContentList().add(new Element(TEST_ELEMENT_NAME));
mcrMetaEnrichedLinkID.getContentList().add(new Element(TEST2_ELEMENT_NAME));
final Element xml = mcrMetaEnrichedLinkID.createXML();
final List<Element> children = xml.getChildren();
Assert.assertEquals("First Element should be order", MCRMetaEnrichedLinkID.ORDER_ELEMENT_NAME,
children.get(0).getName());
Assert.assertEquals("Second Element should be maindoc", MCRMetaEnrichedLinkID.MAIN_DOC_ELEMENT_NAME,
children.get(1).getName());
Assert.assertEquals("Third Element should be " + TEST_ELEMENT_NAME, TEST_ELEMENT_NAME,
children.get(2).getName());
}
}
| 2,199 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaISO8601DateTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaISO8601DateTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.io.StringWriter;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.common.MCRISO8601Date;
import org.mycore.datamodel.common.MCRISO8601Format;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMeta8601Date.
*
* @author Thomas Scheffler
*
*/
public class MCRMetaISO8601DateTest extends MCRTestCase {
private static Logger LOGGER;
@Override
@Before
public void setUp() throws Exception {
super.setUp();//org.mycore.datamodel.metadata.MCRMetaISO8601Date
if (LOGGER == null) {
LOGGER = LogManager.getLogger(MCRMetaISO8601DateTest.class);
}
}
/*
* Test method for
* 'org.mycore.datamodel.metadata.MCRMetaTimestamp.getSecond()'
*/
@Test
public void setDate() {
MCRMetaISO8601Date ts = new MCRMetaISO8601Date();
String timeString = "1997-07-16T19:20:30.452300+01:00";
LOGGER.debug(timeString);
ts.setDate(timeString);
assertNotNull("Date is null", ts.getDate());
// this can be a different String, but point in time should be the same
LOGGER.debug(ts.getISOString());
ts.setFormat(MCRISO8601Format.COMPLETE_HH_MM.toString());
LOGGER.debug(ts.getISOString());
// wrong date format for the following string should null the internal
// date.
timeString = "1997-07-16T19:20:30+01:00";
LOGGER.debug(timeString);
ts.setDate(timeString);
assertNull("Date is not null", ts.getDate());
ts.setFormat(null); // check auto format determination
ts.setDate(timeString);
assertNotNull("Date is null", ts.getDate());
// check if shorter format declarations fail if String is longer
ts.setFormat(MCRISO8601Format.YEAR.toString());
timeString = "1997-07";
ts.setDate(timeString);
assertNull("Date is not null", ts.getDate());
LOGGER.debug(ts.getISOString());
timeString = "01.12.1986";
ts.setFormat(null);
ts.setDate(timeString);
assertNull("Date is not null", ts.getDate());
MCRConfiguration2.set("MCR.Metadata.SimpleDateFormat.StrictParsing", "false");
MCRConfiguration2.set("MCR.Metadata.SimpleDateFormat.Locales", "de_DE,en_US");
ts.setFormat(null);
ts.setDate(timeString);
LOGGER.debug(ts.getISOString());
timeString = "12/01/1986";
ts.setDate(timeString);
LOGGER.debug(ts.getISOString());
ts.setDate("2001");
assertEquals(2001, ts.getMCRISO8601Date().getDt().get(ChronoField.YEAR));
// test b.c.
ts.setDate("-0312");
assertEquals(-312, ts.getMCRISO8601Date().getDt().get(ChronoField.YEAR));
ts.setDate("-0315-05");
assertEquals(-315, ts.getMCRISO8601Date().getDt().get(ChronoField.YEAR));
assertEquals(5, ts.getMCRISO8601Date().getDt().get(ChronoField.MONTH_OF_YEAR));
ts.setDate("-0318-08-12");
assertEquals(-318, ts.getMCRISO8601Date().getDt().get(ChronoField.YEAR));
assertEquals(8, ts.getMCRISO8601Date().getDt().get(ChronoField.MONTH_OF_YEAR));
assertEquals(12, ts.getMCRISO8601Date().getDt().get(ChronoField.DAY_OF_MONTH));
}
/*
* Test method for
* 'org.mycore.datamodel.metadata.MCRMetaTimestamp.getSecond()'
*/
@Test
public void createXML() {
MCRMetaISO8601Date ts = new MCRMetaISO8601Date("servdate", "createdate", 0);
String timeString = "1997-07-16T19:20:30.452300+01:00";
ts.setDate(timeString);
assertNotNull("Date is null", ts.getDate());
Element export = ts.createXML();
if (LOGGER.isDebugEnabled()) {
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
StringWriter sw = new StringWriter();
try {
xout.output(export, sw);
LOGGER.debug(sw.toString());
} catch (IOException e) {
LOGGER.warn("Failure printing xml result", e);
}
}
}
@Test
public void getFormat() {
MCRMetaISO8601Date ts = new MCRMetaISO8601Date();
assertNull("Format used is not Null", ts.getFormat());
ts.setFormat(MCRISO8601Format.COMPLETE.toString());
assertEquals("Set format differs from get format", MCRISO8601Format.COMPLETE.toString(), ts.getFormat());
}
@Test
public void getDate() {
MCRMetaISO8601Date ts = new MCRMetaISO8601Date();
assertNull("Date is not Null", ts.getDate());
Date dt = new Date();
ts.setDate(dt);
assertNotNull("Date is Null", ts.getDate());
assertEquals("Set date differs from get date", dt, ts.getDate());
}
@Test
public void getISOString() {
MCRMetaISO8601Date ts = new MCRMetaISO8601Date();
assertNull("Date is not Null", ts.getISOString());
Date dt = new Date();
ts.setDate(dt);
assertNotNull("Date is Null", ts.getISOString());
}
@Test
public void setFromDOM() {
MCRMetaISO8601Date ts = new MCRMetaISO8601Date();
Element datum = new Element("datum");
datum.setAttribute("inherited", "0").setText("2006-01-23");
ts.setFromDOM(datum);
assertEquals("Dates not equal", "2006-01-23", ts.getISOString());
datum.setAttribute("format", MCRISO8601Format.COMPLETE_HH_MM.toString());
ts.setFromDOM(datum);
assertNull("Date should be null", ts.getDate());
assertEquals("Format should be set by jdom", MCRISO8601Format.COMPLETE_HH_MM.toString(), ts.getFormat());
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put(MCRISO8601Date.PROPERTY_STRICT_PARSING, "true");
testProperties.put("log4j.logger.org.mycore.datamodel.metadata.MCRMetaISO8601Date", "INFO");
return testProperties;
}
}
| 7,292 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaLinkTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaLinkTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import java.util.Map;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaLinkID and MCRMetaLinkID.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaLinkTest extends MCRTestCase {
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.mods", "true");
testProperties.put("MCR.Metadata.Type.derivate", "true");
return testProperties;
}
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsCloneLink() {
MCRMetaLink link1 = new MCRMetaLink("subtag", 0);
link1.setReference("https://www.zoje.de", "ZOJE", "IV Zittauer Schmalspurbahnen e. V.");
Element link1_xml = link1.createXML();
MCRMetaLink link1_read = new MCRMetaLink();
link1_read.setFromDOM(link1_xml);
assertEquals("read objects from XML should be equal", link1, link1_read);
MCRMetaLink link1_clone = link1_read.clone();
assertEquals("cloned object should be equal with original", link1_read, link1_clone);
MCRMetaLink link2 = new MCRMetaLink("subtag", 0);
link2.setBiLink("ZOJE", "SOEG", "Partner Zittauer Schmalspurbahnen");
Element link2_xml = link2.createXML();
MCRMetaLink link2_read = new MCRMetaLink();
link2_read.setFromDOM(link2_xml);
assertEquals("read objects from XML should be equal", link2, link2_read);
MCRMetaLink link2_clone = link2_read.clone();
assertEquals("cloned object should be equal with original", link2_read, link2_clone);
}
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsCloneLinkID() {
MCRMetaLinkID link1 = new MCRMetaLinkID("subtag", 0);
link1.setReference("MIR_mods_00000001", "MODS", "MODS-Objekt 1");
link1.setType("mytype");
Element link1_xml = link1.createXML();
MCRMetaLinkID link1_read = new MCRMetaLinkID();
link1_read.setFromDOM(link1_xml);
assertEquals("read objects from XML should be equal", link1, link1_read);
MCRMetaLinkID link1_clone = link1_read.clone();
assertEquals("cloned object should be equal with original", link1_read, link1_clone);
MCRMetaLinkID link2 = new MCRMetaLinkID("subtag", 0);
link2.setReference(MCRObjectID.getInstance("MIR_mods_00000001"), "MODS", "MODS-Objekt 1");
link2.setType("mytype");
assertEquals("MCRID object should be equal with original", link1, link2);
MCRMetaLinkID link3 = new MCRMetaLinkID("subtag", 0);
link3.setBiLink("MIR_mods_00000001", "MIR_derivate_00000001", "Derivate link");
Element link3_xml = link3.createXML();
MCRMetaLinkID link3_read = new MCRMetaLinkID();
link3_read.setFromDOM(link3_xml);
assertEquals("read objects from XML should be equal", link3, link3_read);
MCRMetaLinkID link3_clone = link3_read.clone();
assertEquals("cloned object should be equal with original", link3_read, link3_clone);
MCRMetaLinkID link4 = new MCRMetaLinkID("subtag", 0);
link4.setBiLink(MCRObjectID.getInstance("MIR_mods_00000001"),
MCRObjectID.getInstance("MIR_derivate_00000001"), "Derivate link");
assertEquals("MCRID object should be equal with original", link3, link4);
}
}
| 4,399 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRObjectIDTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRStoreTestCase;
public class MCRObjectIDTest extends MCRStoreTestCase {
private static final String BASE_ID = "MyCoRe_test";
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public void setNextFreeIdString() {
MCRObjectID id1 = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(BASE_ID);
assertEquals("First id should be int 1", 1, id1.getNumberAsInteger());
MCRObjectID id2 = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(BASE_ID);
assertEquals("Second id should be int 2", 2, id2.getNumberAsInteger());
getStore().create(id2, new Document(new Element("test")), new Date());
MCRObjectID id3 = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(BASE_ID);
assertEquals("Second id should be int 3", 3, id3.getNumberAsInteger());
}
@Test
public void validateID() {
assertTrue("The mcrid 'JUnit_test_123' is valid", MCRObjectID.isValid("JUnit_test_123"));
assertFalse("The mcrid 'JUnit_xxx_123' is invalid (unknown type)", MCRObjectID.isValid("JUnit_xxx_123"));
assertFalse("The mcrid 'JUnit_test__123' is invalid (to many underscores)",
MCRObjectID.isValid("JUnit_test__123"));
assertFalse("The mcrid 'JUnit_test_123 ' is invalid (space at end)", MCRObjectID.isValid("JUnit_test_123 "));
assertFalse("The mcrid 'JUnit_test_-123' is invalid (negative number)", MCRObjectID.isValid("JUnit_test_-123"));
assertFalse(
"The mcrid 'aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffffffffff_test_123' is invalid (length)",
MCRObjectID.isValid("aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffffffffff_test_123"));
}
@Test
public void compareTo() {
Set<MCRObjectID> testIds = IntStream.range(0, 17)
.mapToObj(i -> MCRObjectID.getInstance(MCRObjectID.formatID("MyCoRe", "test", i)))
.flatMap(o -> Stream.of(o, MCRObjectID.getInstance(
MCRObjectID.formatID(o.getProjectId(), "junit", o.getNumberAsInteger()))))
.flatMap(o -> Stream.concat(Stream.of(o),
Stream.of("junit", "mcr", "JUnit")
.map(projectId -> MCRObjectID
.getInstance(
MCRObjectID.formatID(
projectId,
o.getTypeId(),
o.getNumberAsInteger())))))
.collect(Collectors.toSet());
ArrayList<MCRObjectID> first = new ArrayList<>(testIds);
ArrayList<MCRObjectID> test = new ArrayList<>(testIds);
first.sort(Comparator.comparing(MCRObjectID::toString));
test.sort(MCRObjectID::compareTo);
assertArrayEquals("Order should be the same.", first.toArray(), test.toArray());
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
testProperties.put("MCR.Metadata.Type.junit", Boolean.TRUE.toString());
return testProperties;
}
}
| 4,535 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaClassificationTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaClassificationTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaClassification.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaClassificationTest extends MCRTestCase {
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsClone() {
MCRMetaClassification classification = new MCRMetaClassification("subtag", 0, "my_type", "my_classification",
"my_category");
Element langtext_xml = classification.createXML();
MCRMetaClassification langtext_read = new MCRMetaClassification();
langtext_read.setFromDOM(langtext_xml);
assertEquals("read objects from XML should be equal", classification, langtext_read);
MCRMetaClassification langtext_clone = langtext_read.clone();
assertEquals("cloned object should be equal with original", langtext_read, langtext_clone);
}
}
| 1,829 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaBooleanTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaBooleanTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaBoolean.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaBooleanTest extends MCRTestCase {
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsClone() {
MCRMetaBoolean bool = new MCRMetaBoolean("subtag", "my_type", 0, true);
Element boolean_xml = bool.createXML();
MCRMetaBoolean boolean_read = new MCRMetaBoolean();
boolean_read.setFromDOM(boolean_xml);
assertEquals("read objects from XML should be equal", bool, boolean_read);
MCRMetaBoolean boolean_clone = boolean_read.clone();
assertEquals("cloned object should be equal with original", boolean_read, boolean_clone);
}
}
| 1,699 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectUtilsTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRObjectUtilsTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.mycore.access.MCRAccessBaseImpl;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRStoreTestCase;
import org.mycore.common.events.MCREvent.ObjectType;
import org.mycore.common.events.MCREventManager;
import org.mycore.datamodel.common.MCRLinkTableEventHandler;
import org.mycore.datamodel.common.MCRXMLMetadataEventHandler;
public class MCRObjectUtilsTest extends MCRStoreTestCase {
private MCRObject root;
private MCRObject l11;
private MCRObject l12;
private MCRObject l13;
private MCRObject l21;
private MCRObject l22;
private MCRObject l31;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
MCREventManager.instance().clear();
MCREventManager.instance().addEventHandler(ObjectType.OBJECT, new MCRXMLMetadataEventHandler());
MCREventManager.instance().addEventHandler(ObjectType.OBJECT, new MCRLinkTableEventHandler());
root = createObject("test_document_00000001", null);
l11 = createObject("test_document_00000002", root.getId());
l12 = createObject("test_document_00000003", root.getId());
l13 = createObject("test_document_00000004", root.getId());
l21 = createObject("test_document_00000005", l11.getId());
l22 = createObject("test_document_00000006", l11.getId());
l31 = createObject("test_document_00000007", l21.getId());
MCRMetadataManager.create(root);
MCRMetadataManager.create(l11);
MCRMetadataManager.create(l12);
MCRMetadataManager.create(l13);
MCRMetadataManager.create(l21);
MCRMetadataManager.create(l22);
MCRMetadataManager.create(l31);
}
private MCRObject createObject(String id, MCRObjectID parent) {
MCRObject object = new MCRObject();
object.setId(MCRObjectID.getInstance(id));
object.setSchema("noSchema");
if (parent != null) {
object.getStructure().setParent(parent);
}
return object;
}
@Test
public void getAncestors() {
MCRObject doc = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance("test_document_00000007"));
List<MCRObject> ancestors = MCRObjectUtils.getAncestors(doc);
assertEquals(3, ancestors.size());
assertEquals(l21.getId(), ancestors.get(0).getId());
assertEquals(l11.getId(), ancestors.get(1).getId());
assertEquals(root.getId(), ancestors.get(2).getId());
}
@Test
public void getAncestorsAndSelf() {
MCRObject doc = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance("test_document_00000007"));
List<MCRObject> ancestors = MCRObjectUtils.getAncestorsAndSelf(doc);
assertEquals(4, ancestors.size());
assertEquals(l31.getId(), ancestors.get(0).getId());
assertEquals(l21.getId(), ancestors.get(1).getId());
assertEquals(l11.getId(), ancestors.get(2).getId());
assertEquals(root.getId(), ancestors.get(3).getId());
}
@Test
public void getRoot() {
MCRObject doc = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance("test_document_00000006"));
MCRObject root = MCRObjectUtils.getRoot(doc);
assertNotNull(root);
assertEquals(this.root.getId(), root.getId());
}
@Test
public void getDescendants() {
MCRObject doc = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance("test_document_00000001"));
List<MCRObject> descendants = MCRObjectUtils.getDescendants(doc);
assertEquals(6, descendants.size());
MCRObject doc2 = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance("test_document_00000002"));
List<MCRObject> descendants2 = MCRObjectUtils.getDescendants(doc2);
assertEquals(3, descendants2.size());
MCRObject doc3 = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance("test_document_00000004"));
List<MCRObject> descendants3 = MCRObjectUtils.getDescendants(doc3);
assertEquals(0, descendants3.size());
}
@Test
public void getDescendantsAndSelf() {
MCRObject doc = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance("test_document_00000001"));
List<MCRObject> descendants = MCRObjectUtils.getDescendantsAndSelf(doc);
assertEquals(7, descendants.size());
}
@Test
public void removeLink() throws MCRAccessException {
// remove parent link
assertTrue(MCRObjectUtils.removeLink(l22, l11.getId()));
MCRMetadataManager.update(l22);
l11 = MCRMetadataManager.retrieveMCRObject(l11.getId());
l22 = MCRMetadataManager.retrieveMCRObject(l22.getId());
assertNull(l22.getParent());
assertFalse(l11.getStructure().containsChild(l22.getId()));
// add metadata links to test
addLinksToL22();
assertEquals(2, l22.getMetadata().stream("links").count());
// remove metadata link
assertTrue(MCRObjectUtils.removeLink(l22, l31.getId()));
assertEquals(1, l22.getMetadata().stream("links").count());
assertTrue(MCRObjectUtils.removeLink(l22, l11.getId()));
assertEquals(0, l22.getMetadata().stream("links").count());
// check if links element is completely removed
MCRMetadataManager.update(l22);
l22 = MCRMetadataManager.retrieveMCRObject(l22.getId());
assertNull(l22.getMetadata().getMetadataElement("links"));
}
@Test
public void removeLinks() throws MCRAccessException {
// add metadata links to test
addLinksToL22();
assertEquals(2, l22.getMetadata().stream("links").count());
// remove l11
for (MCRObject linkedObject : MCRObjectUtils.removeLinks(l11.getId()).collect(Collectors.toList())) {
MCRMetadataManager.update(linkedObject);
}
l22 = MCRMetadataManager.retrieveMCRObject(l22.getId());
assertEquals(1, l22.getMetadata().stream("links").count());
// remove l31
for (MCRObject linkedObject : MCRObjectUtils.removeLinks(l31.getId()).collect(Collectors.toList())) {
MCRMetadataManager.update(linkedObject);
}
l22 = MCRMetadataManager.retrieveMCRObject(l22.getId());
assertEquals(0, l22.getMetadata().stream("links").count());
}
private void addLinksToL22() throws MCRAccessException {
MCRMetaLinkID l11Link = new MCRMetaLinkID("link", l11.getId(), "l11", "l11");
MCRMetaLinkID l31Link = new MCRMetaLinkID("link", l31.getId(), "l31", "l31");
List<MCRMetaLinkID> linkList = Arrays.asList(l11Link, l31Link);
MCRMetaElement link = new MCRMetaElement(MCRMetaLinkID.class, "links", false, false, linkList);
l22.getMetadata().setMetadataElement(link);
MCRMetadataManager.update(l22);
l22 = MCRMetadataManager.retrieveMCRObject(l22.getId());
}
@Override
public void tearDown() throws Exception {
MCRMetadataManager.delete(l31);
MCRMetadataManager.delete(l22);
MCRMetadataManager.delete(l21);
MCRMetadataManager.delete(l13);
MCRMetadataManager.delete(l12);
MCRMetadataManager.delete(l11);
MCRMetadataManager.delete(root);
super.tearDown();
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties
.put("MCR.Persistence.LinkTable.Store.Class", "org.mycore.backend.hibernate.MCRHIBLinkTableStore");
testProperties.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName());
testProperties.put("MCR.Metadata.Type.document", "true");
return testProperties;
}
}
| 8,912 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaAddressTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaAddressTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaAddress.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaAddressTest extends MCRTestCase {
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsClone() {
MCRMetaAddress address = new MCRMetaAddress("subtag", "de", "mytype", 0, "Deutschland", "Sachsen",
"04109", "Leipzig", "Augustusplatz", "10");
Element address_xml = address.createXML();
MCRMetaAddress address_read = new MCRMetaAddress();
address_read.setFromDOM(address_xml);
assertEquals("read objects from XML should be equal", address, address_read);
MCRMetaAddress address_clone = address_read.clone();
assertEquals("cloned object should be equal with original", address_read, address_clone);
}
}
| 1,788 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectMetadataTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRObjectMetadataTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mycore.common.MCRException;
import org.mycore.common.MCRTestCase;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRXMLParserFactory;
/**
* @author Thomas Scheffler
*
*/
public class MCRObjectMetadataTest extends MCRTestCase {
private static final String TEST_OBJECT_RESOURCE_NAME = "/mcr_test_01.xml";
private MCRObjectMetadata testMetadata;
/* (non-Javadoc)
* @see org.mycore.common.MCRTestCase#setUp()
*/
@Override
@Before
public void setUp() throws Exception {
super.setUp();
Document testObjectDocument = loadResourceDocument(TEST_OBJECT_RESOURCE_NAME);
testMetadata = new MCRObjectMetadata();
testMetadata.setFromDOM(testObjectDocument.getRootElement().getChild("metadata"));
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#size()}.
*/
@Test
public void size() {
assertEquals("Expected just one metadata entry", 1, testMetadata.size());
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#getMetadataElement(int)}.
*/
@Test
public void getMetadataTagName() {
assertEquals("Metadata tag is not 'def.textfield'", "def.textfield", testMetadata.getMetadataElement(0)
.getTag());
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#getHeritableMetadata()}.
*/
@Test
public void getHeritableMetadata() {
assertEquals("Did not find any heritable metadata", 1, testMetadata.getHeritableMetadata().size());
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#removeInheritedMetadata()}.
*/
@Test
public void removeInheritedMetadata() {
testMetadata.removeInheritedMetadata();
assertEquals("Did not expect removal of any metadata", 1, testMetadata.size());
testMetadata.setMetadataElement(getInheritedMetadata());
testMetadata.removeInheritedMetadata();
assertEquals("Did not expect removal of any metadata element", 2, testMetadata.size());
MCRMetaElement defJunit = testMetadata.getMetadataElement("def.junit");
assertEquals("Not all inherited metadata was removed", 1, defJunit.size());
defJunit = getInheritedMetadata();
for (MCRMetaInterface i : defJunit) {
if (i.getInherited() == 0) {
i.setInherited(1);
}
}
testMetadata.setMetadataElement(defJunit);
testMetadata.removeInheritedMetadata();
assertEquals("Did expect removal of \"def.junit\" metadata element", 1, testMetadata.size());
}
private MCRMetaElement getInheritedMetadata() {
MCRMetaElement defJunit = new MCRMetaElement(MCRMetaLangText.class, "def.junit", true, false, null);
MCRMetaLangText test1 = new MCRMetaLangText("junit", "de", null, 0, null, "Test 1");
MCRMetaLangText test2 = new MCRMetaLangText("junit", "de", null, 1, null, "Test 2");
MCRMetaLangText test3 = new MCRMetaLangText("junit", "de", null, 1, null, "Test 3");
defJunit.addMetaObject(test1);
defJunit.addMetaObject(test2);
defJunit.addMetaObject(test3);
return defJunit;
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#appendMetadata(org.mycore.datamodel.metadata.MCRObjectMetadata)}.
*/
@Test
public void appendMetadata() {
MCRObjectMetadata meta2 = getDateObjectMetadata();
testMetadata.appendMetadata(meta2);
assertEquals("Expected 2 metadates", 2, testMetadata.size());
}
private MCRObjectMetadata getDateObjectMetadata() {
MCRObjectMetadata meta2 = new MCRObjectMetadata();
MCRMetaISO8601Date date = new MCRMetaISO8601Date("datefield", "test", 0);
date.setDate(new Date());
MCRMetaElement el2 = new MCRMetaElement();
el2.addMetaObject(date);
el2.setClass(MCRMetaISO8601Date.class);
el2.setHeritable(true);
el2.setTag(date.datapart);
meta2.setMetadataElement(el2);
return meta2;
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#getMetadataElement(java.lang.String)}.
*/
@Test
public void getMetadataElementString() {
assertEquals("did not get correct MCRMetaElement instance", testMetadata.getMetadataElement(0),
testMetadata.getMetadataElement("def.textfield"));
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#getMetadataElement(int)}.
*/
@Test
public void getMetadataElementInt() {
assertEquals("did not get correct MCRMetaElement instance", testMetadata.getMetadataElement("def.textfield"),
testMetadata.getMetadataElement(0));
}
/**
* Test method for org.mycore.datamodel.metadata.MCRObjectMetadata#setMetadataElement(org.mycore.datamodel.metadata.MCRMetaElement, java.lang.String) (not implemented yet).
*/
@Test
@Ignore("not implemented")
public void setMetadataElement() {
fail("Not yet implemented"); // TODO
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#removeMetadataElement(java.lang.String)}.
*/
@Test
@Ignore("not implemented")
public void removeMetadataElementString() {
fail("Not yet implemented"); // TODO
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#removeMetadataElement(int)}.
*/
@Test
@Ignore("not implemented")
public void removeMetadataElementInt() {
fail("Not yet implemented"); // TODO
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#createXML()}.
*/
@Test
@Ignore("not implemented")
public void createXML() {
fail("Not yet implemented"); // TODO
}
/**
* Test method for {@link org.mycore.datamodel.metadata.MCRObjectMetadata#isValid()}.
*/
@Test
@Ignore("not implemented")
public void isValid() {
fail("Not yet implemented"); // TODO
}
private static Document loadResourceDocument(String resource) throws MCRException, IOException, JDOMException {
URL mcrTestUrl = MCRObjectMetadataTest.class.getResource(resource);
return MCRXMLParserFactory.getValidatingParser().parseXML(new MCRURLContent(mcrTestUrl));
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.DefaultLang", "de");
return testProperties;
}
}
| 7,825 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaNumberTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaNumberTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Text;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.xml.MCRXMLHelper;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaNumber.
* It tests again the ENGLISH Locale
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaNumberTest extends MCRTestCase {
private static Logger LOGGER;
@Override
@Before
public void setUp() throws Exception {
super.setUp();//org.mycore.datamodel.metadata.MCRMetaXML
if (LOGGER == null) {
LOGGER = LogManager.getLogger(MCRMetaNumber.class);
}
}
@Test
public void numberTransformation() {
MCRMetaNumber meta_number = new MCRMetaNumber("number", 0, null, null, "0,1");
String number_string = meta_number.getNumberAsString();
assertEquals("datamodel", "0.100", number_string);
meta_number = new MCRMetaNumber("number", 0, null, null, "0.10");
number_string = meta_number.getNumberAsString();
assertEquals("datamodel", "0.100", number_string);
meta_number = new MCRMetaNumber("number", 0, null, null, "12345,6789");
number_string = meta_number.getNumberAsString();
assertEquals("datamodel", "12345.679", number_string);
// geo data
MCRConfiguration2.set("MCR.Metadata.MetaNumber.FractionDigits", String.valueOf(8));
meta_number = new MCRMetaNumber("number", 0, null, null, "123.45678999");
number_string = meta_number.getNumberAsString();
assertEquals("datamodel", "123.45678999", number_string);
meta_number = new MCRMetaNumber("number", 0, null, null, "-123,45678999");
number_string = meta_number.getNumberAsString();
assertEquals("datamodel", "-123.45678999", number_string);
}
@Test
public void xmlRoundrip() {
// test 0.100
MCRMetaNumber meta_number = new MCRMetaNumber();
Element imported = new Element("number");
imported.setAttribute("inherited", "0");
imported.setAttribute("dimension", "width");
imported.setAttribute("measurement", "cm");
imported.addContent(new Text("0.100"));
meta_number.setFromDOM(imported);
Element exported = meta_number.createXML();
print_data(imported, exported);
check_data(imported, exported);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("log4j.logger.org.mycore.datamodel.metadata", "INFO");
return testProperties;
}
private void print_data(Element imported, Element exported) {
if (LOGGER.isDebugEnabled()) {
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
StringWriter sw = new StringWriter();
StringWriter sw2 = new StringWriter();
try {
xout.output(imported, sw);
LOGGER.info(sw.toString());
xout.output(exported, sw2);
LOGGER.info(sw2.toString());
} catch (IOException e) {
LOGGER.warn("Failure printing xml result", e);
}
}
}
private void check_data(Element imported, Element exported) {
try {
assertTrue(MCRXMLHelper.deepEqual(new Document(imported), new Document(exported)));
} catch (AssertionError e) {
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
try {
out.output(imported, System.err);
} catch (IOException e1) {
LOGGER.error("Can't print imported for Test MCRMetaNumberTest.");
}
try {
out.output(exported, System.err);
} catch (IOException e1) {
LOGGER.error("Can't print exported for Test MCRMetaNumberTest.");
}
throw e;
}
}
}
| 5,186 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaHistoryDateTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaHistoryDateTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRCalendar;
import org.mycore.common.MCRTestCase;
import com.ibm.icu.util.GregorianCalendar;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaHistoryDate.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaHistoryDateTest extends MCRTestCase {
/**
* check set date methods
*/
@Test
public void checkSetDateMethods() {
MCRMetaHistoryDate hd = new MCRMetaHistoryDate();
hd.setVonDate(new GregorianCalendar(1964, 1, 23));
assertEquals("Von value is not 1964-02-23 AD", "1964-02-23 AD", hd.getVonToString());
hd = new MCRMetaHistoryDate();
hd.setVonDate("23.02.1964", MCRCalendar.TAG_GREGORIAN);
assertEquals("Von value is not 1964-02-23 AD", "1964-02-23 AD", hd.getVonToString());
hd = new MCRMetaHistoryDate();
hd.setBisDate(new GregorianCalendar(1964, 1, 23));
assertEquals("Bis value is not 1964-02-23 AD", "1964-02-23 AD", hd.getBisToString());
hd = new MCRMetaHistoryDate();
hd.setBisDate("23.02.1964", MCRCalendar.TAG_GREGORIAN);
assertEquals("Bis value is not 1964-02-23 AD", "1964-02-23 AD", hd.getBisToString());
}
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsClone() {
MCRMetaHistoryDate julian_date = new MCRMetaHistoryDate("subtag", "type", 0);
julian_date.setCalendar(MCRCalendar.TAG_JULIAN);
julian_date.setVonDate("22.02.1964", julian_date.getCalendar());
julian_date.setBisDate("22.02.1964", julian_date.getCalendar());
julian_date.addText("mein Tag", "de");
MCRMetaHistoryDate gregorian_date = new MCRMetaHistoryDate("subtag", "type", 0);
gregorian_date.setCalendar(MCRCalendar.TAG_GREGORIAN);
gregorian_date.setVonDate("06.03.1964", gregorian_date.getCalendar());
gregorian_date.setBisDate("06.03.1964", gregorian_date.getCalendar());
gregorian_date.addText("mein Tag", "de");
Element julian_date_xml = julian_date.createXML();
Element gregorian_date_xml = gregorian_date.createXML();
assertEquals(julian_date_xml.getChildText("text"), gregorian_date_xml.getChildText("text"));
assertEquals(julian_date_xml.getChildText("ivon"), gregorian_date_xml.getChildText("ivon"));
assertEquals(julian_date_xml.getChildText("ibis"), gregorian_date_xml.getChildText("ibis"));
assertEquals(julian_date_xml.getChildText("calendar"), MCRCalendar.TAG_JULIAN);
assertEquals(julian_date_xml.getChildText("von"), "1964-02-22 AD");
assertEquals(julian_date_xml.getChildText("bis"), "1964-02-22 AD");
assertEquals(gregorian_date_xml.getChildText("calendar"), MCRCalendar.TAG_GREGORIAN);
assertEquals(gregorian_date_xml.getChildText("von"), "1964-03-06 AD");
assertEquals(gregorian_date_xml.getChildText("bis"), "1964-03-06 AD");
MCRMetaHistoryDate julian_date_read = new MCRMetaHistoryDate();
julian_date_read.setFromDOM(julian_date_xml);
MCRMetaHistoryDate gregorian_date_read = new MCRMetaHistoryDate();
gregorian_date_read.setFromDOM(gregorian_date_xml);
assertEquals("read objects from XML should be equal", julian_date_read, gregorian_date_read);
MCRMetaHistoryDate gregorian_date_clone = gregorian_date_read.clone();
assertEquals("cloned object should be equal with original", gregorian_date_read, gregorian_date_clone);
}
}
| 4,392 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaInstitutionNameTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaInstitutionNameTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaInstitutionName.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaInstitutionNameTest extends MCRTestCase {
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsClone() {
MCRMetaInstitutionName instname = new MCRMetaInstitutionName("subtag", "de", "my_type", 0,
"UniversitΓ€tsrechenzentrum", "URZ", "UL");
Element langtext_xml = instname.createXML();
MCRMetaInstitutionName langtext_read = new MCRMetaInstitutionName();
langtext_read.setFromDOM(langtext_xml);
assertEquals("read objects from XML should be equal", instname, langtext_read);
MCRMetaInstitutionName langtext_clone = langtext_read.clone();
assertEquals("cloned object should be equal with original", langtext_read, langtext_clone);
}
}
| 1,831 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaLangTextTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaLangTextTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaLangText.
*
* @author Jens Kupferschmidt
*
*/
public class MCRMetaLangTextTest extends MCRTestCase {
/**
* check createXML, setFromDom, equals and clone
*/
@Test
public void checkCreateParseEqualsClone() {
MCRMetaLangText langtext = new MCRMetaLangText("subtag", "de", "my_type", 0, "plain", "mein text");
Element langtext_xml = langtext.createXML();
MCRMetaLangText langtext_read = new MCRMetaLangText();
langtext_read.setFromDOM(langtext_xml);
assertEquals("read objects from XML should be equal", langtext, langtext_read);
langtext.setSequence(3);
langtext_read.setSequence(langtext.getSequence());
assertEquals("sequence of objects should be equal", langtext, langtext_read);
MCRMetaLangText langtext_clone = langtext_read.clone();
assertEquals("cloned object should be equal with original", langtext_read, langtext_clone);
}
}
| 1,928 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaXMLTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/MCRMetaXMLTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.Text;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.xml.MCRXMLHelper;
/**
* This class is a JUnit test case for org.mycore.datamodel.metadata.MCRMetaXML.
*
* @author Thomas Scheffler
*
*/
public class MCRMetaXMLTest extends MCRTestCase {
private static final Logger LOGGER = LogManager.getLogger();
@Test
public void xmlRoundrip() throws IOException {
MCRMetaXML mXml = new MCRMetaXML("def.heading", "complete", 0);
Element imported = new Element("heading");
imported.setAttribute("lang", MCRMetaDefault.DEFAULT_LANGUAGE, Namespace.XML_NAMESPACE);
imported.setAttribute("inherited", "0");
imported.setAttribute("type", "complete");
imported.addContent(new Text("This is a "));
imported.addContent(new Element("span").setText("JUnit"));
imported.addContent(new Text("test"));
mXml.setFromDOM(imported);
Element exported = mXml.createXML();
if (LOGGER.isDebugEnabled()) {
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
StringWriter sw = new StringWriter();
StringWriter sw2 = new StringWriter();
try {
xout.output(imported, sw);
LOGGER.info(sw.toString());
xout.output(exported, sw2);
LOGGER.info(sw2.toString());
} catch (IOException e) {
LOGGER.warn("Failure printing xml result", e);
}
}
try {
assertTrue(MCRXMLHelper.deepEqual(new Document(imported), new Document(exported)));
} catch (AssertionError e) {
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
out.output(imported, System.err);
out.output(exported, System.err);
throw e;
}
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("log4j.logger.org.mycore.datamodel.metadata", "INFO");
return testProperties;
}
}
| 3,272 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataHistoryManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/metadata/history/MCRMetadataHistoryManagerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import org.junit.Test;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRJPATestCase;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.persistence.EntityManager;
public class MCRMetadataHistoryManagerTest extends MCRJPATestCase {
private static final Instant HISTORY_START = Instant.parse("2017-06-19T10:28:36.565Z");
private MCRObjectID testObject;
private Instant lastDelete;
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.mods", Boolean.TRUE.toString());
return testProperties;
}
@Override
public void setUp() throws Exception {
super.setUp();
}
@Test
public void testGetEmptyHistoryStart() {
//MCR-1979
assertFalse("No earliest timestamp should be present", MCRMetadataHistoryManager.getHistoryStart().isPresent());
}
@Test
public void testGetHighestStoredID() {
addTestData();
assertEquals(testObject,
MCRMetadataHistoryManager.getHighestStoredID(testObject.getProjectId(), testObject.getTypeId()).get());
}
@Test
public void testGetHistoryStart() {
addTestData();
assertEquals(HISTORY_START, MCRMetadataHistoryManager.getHistoryStart().get());
}
@Test
public void testGetDeletedItems() {
addTestData();
Map<MCRObjectID, Instant> deletedItems = MCRMetadataHistoryManager.getDeletedItems(Instant.ofEpochMilli(0),
Optional.empty());
assertEquals("Expected a single deletion event.", 1, deletedItems.size());
}
@Test
public void testGetLastDeletedDate() {
addTestData();
assertEquals(lastDelete, MCRMetadataHistoryManager.getLastDeletedDate(testObject).get());
}
private void addTestData() {
testObject = MCRObjectID.getInstance("mir_mods_00000355");
create(testObject, HISTORY_START);
delete(testObject, Instant.parse("2017-06-19T10:34:27.915Z"));
create(testObject, Instant.parse("2017-06-19T10:52:59.711Z"));
lastDelete = Instant.parse("2017-06-19T10:52:59.718Z");
delete(testObject, lastDelete);
startNewTransaction();
}
private void create(MCRObjectID id, Instant time) {
MCRMetaHistoryItem created = MCRMetaHistoryItem.createdNow(id);
created.setTime(time);
store(created);
}
private void delete(MCRObjectID id, Instant time) {
MCRMetaHistoryItem deleted = MCRMetaHistoryItem.deletedNow(id);
deleted.setTime(time);
store(deleted);
}
private void store(MCRMetaHistoryItem item) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.persist(item);
}
}
| 3,797 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryIDTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/MCRCategoryIDTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.mycore.common.MCRException;
import org.mycore.common.MCRTestCase;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRCategoryIDTest extends MCRTestCase {
private static final String invalidID = "identifier:.sub";
private static final String validRootID = "rootID";
private static final String validCategID = "categID";
private static final String toLongRootID = "012345678901234567890123456789012";
private static final String toLongCategID
= "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678";
/**
* Test method for {@link org.mycore.datamodel.classifications2.MCRCategoryID#MCRCategoryID(java.lang.String, java.lang.String)}.
*/
@Test
public void testMCRCategoryIDStringString() {
MCRCategoryID categID;
categID = new MCRCategoryID(validRootID, validCategID);
assertEquals("RootIDs do not match", validRootID, categID.getRootID());
assertEquals("CategIDs do not match", validCategID, categID.getId());
}
@Test
public void testRootID() {
assertEquals("RootIds do not match", validRootID, MCRCategoryID.rootID(validRootID).getRootID());
}
@Test(expected = MCRException.class)
public void testInvalidRootID() {
new MCRCategoryID(invalidID, validCategID);
}
@Test(expected = MCRException.class)
public void testInvalidCategID() {
new MCRCategoryID(validRootID, invalidID);
}
@Test(expected = MCRException.class)
public void testLongCategID() {
new MCRCategoryID(validRootID, toLongCategID);
}
@Test(expected = MCRException.class)
public void testLongRootID() {
new MCRCategoryID(toLongRootID, validCategID);
}
}
| 2,655 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLabelTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/MCRLabelTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.fail;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
public class MCRLabelTest extends MCRTestCase {
@Test
public final void testMCRLabelStringStringString() {
new MCRLabel("de", "test", null);
try {
new MCRLabel("de", null, null);
fail("MCRLabel should not allow 'null' as 'text'.");
} catch (NullPointerException e) {
}
try {
new MCRLabel("de", "", null);
fail("MCRLabel should not allow empty 'text'.");
} catch (IllegalArgumentException e) {
}
try {
new MCRLabel("de", " ", null);
} catch (IllegalArgumentException e) {
}
new MCRLabel("x-uri", "http://...", null);
try {
new MCRLabel("x-toolong", "http://...", null);
} catch (IllegalArgumentException e) {
}
}
}
| 1,687 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestCategoryMapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/mapper/MCRTestCategoryMapper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.mycore.datamodel.classifications2.MCRCategoryID;
/**
* @author Frank LΓΌtzenkirchen
*/
public class MCRTestCategoryMapper extends MCRCategoryMapperBase {
private Map<MCRCategoryID, MCRCategoryID> parents = new HashMap<>();
private Map<MCRCategoryID, String> mappingRules = new HashMap<>();
public void setParent(MCRCategoryID childID, MCRCategoryID parentID) {
parents.put(childID, parentID);
}
@Override
protected void addParentsToList(MCRCategoryID childID, List<MCRCategoryID> list) {
MCRCategoryID parent = parents.get(childID);
if (parent != null) {
list.add(parent);
addParentsToList(parent, list);
}
}
public void addMappingRule(MCRCategoryID categoryID, String mappingRule) {
mappingRules.put(categoryID, mappingRule);
}
@Override
protected String getMappingRule(MCRCategoryID categoryID) {
return mappingRules.get(categoryID);
}
@Test
public void doNothing() {
// remove me if needed, just prevent test errors java.lang.Exception: No runnable methods
}
}
| 2,002 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryImplTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/impl/MCRCategoryImplTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.junit.Test;
import org.mycore.common.MCRException;
import org.mycore.common.MCRTestCase;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer;
import org.xml.sax.SAXParseException;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRCategoryImplTest extends MCRTestCase {
static final String WORLD_CLASS_RESOURCE_NAME = "/worldclass.xml";
private MCRCategoryImpl category;
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategoryImpl#calculateLeftRightAndLevel(int, int)}.
*/
@Test
public void calculateLeftRightAndLevel() {
MCRCategoryImpl rootNode = buildNode(MCRCategoryID.rootID("co1"));
final int leftStart = 1;
final int levelStart = 0;
assertEquals(2, rootNode.calculateLeftRightAndLevel(leftStart, levelStart));
assertEquals(levelStart, rootNode.getLevel());
MCRCategoryImpl co2 = buildNode(new MCRCategoryID(rootNode.getId().getRootID(), "co2"));
rootNode.getChildren().add(co2);
assertEquals(4, rootNode.calculateLeftRightAndLevel(leftStart, levelStart));
assertEquals(leftStart, co2.getLevel());
MCRCategoryImpl co3 = buildNode(new MCRCategoryID(rootNode.getId().getRootID(), "co3"));
rootNode.getChildren().add(co3);
assertEquals(6, rootNode.calculateLeftRightAndLevel(leftStart, levelStart));
assertEquals(leftStart, co3.getLevel());
MCRCategoryImpl co4 = buildNode(new MCRCategoryID(rootNode.getId().getRootID(), "co4"));
co3.getChildren().add(co4);
assertEquals(8, rootNode.calculateLeftRightAndLevel(leftStart, levelStart));
assertEquals(2, co4.getLevel());
}
@Test
public void getLeftSiblingOrOfAncestor() throws URISyntaxException, MCRException, IOException, JDOMException {
loadWorldClassification();
MCRCategory europe = category.getChildren().get(0);
MCRCategoryImpl asia = (MCRCategoryImpl) category.getChildren().get(1);
MCRCategoryImpl germany = (MCRCategoryImpl) europe.getChildren().get(0);
assertEquals("Did not get Europe as left sibling of Asia", europe.getId(),
asia.getLeftSiblingOrOfAncestor().getId());
assertEquals("Did not get World as left sibling or ancestor of Germany", category.getId(),
germany.getLeftSiblingOrOfAncestor().getId());
MCRCategoryImpl america = buildNode(new MCRCategoryID(category.getRootID(), "America"));
category.getChildren().add(0, america);
assertEquals("Did not get America as left sibling or ancestor of Germany", america.getId(),
germany.getLeftSiblingOrOfAncestor().getId());
}
@Test
public void getLeftSiblingOrParent() throws URISyntaxException, MCRException, IOException, JDOMException {
loadWorldClassification();
MCRCategory europe = category.getChildren().get(0);
MCRCategoryImpl asia = (MCRCategoryImpl) category.getChildren().get(1);
MCRCategoryImpl germany = (MCRCategoryImpl) europe.getChildren().get(0);
assertEquals("Did not get Europe as left sibling of Asia", europe.getId(),
asia.getLeftSiblingOrParent().getId());
assertEquals("Did not get Europa as left sibling or ancestor of Germany", europe.getId(),
germany.getLeftSiblingOrParent().getId());
}
@Test
public void getRightSiblingOrOfAncestor() throws URISyntaxException, MCRException, IOException, JDOMException {
loadWorldClassification();
MCRCategoryImpl europe = (MCRCategoryImpl) category.getChildren().get(0);
MCRCategoryImpl asia = (MCRCategoryImpl) category.getChildren().get(1);
MCRCategoryImpl spain = (MCRCategoryImpl) europe.getChildren().get(3);
assertEquals("Did not get Asia as right sibling of Europe", asia.getId(),
europe.getRightSiblingOrOfAncestor().getId());
assertEquals("Did not get Asia as right sibling or ancestor of Spain", asia.getId(),
spain.getRightSiblingOrOfAncestor().getId());
assertEquals("Did not get World as right sibling or ancestor of Asia", category.getId(),
asia.getRightSiblingOrOfAncestor().getId());
}
@Test
public void getRightSiblingOrParent() throws URISyntaxException, MCRException, IOException, JDOMException {
loadWorldClassification();
MCRCategoryImpl europe = (MCRCategoryImpl) category.getChildren().get(0);
MCRCategoryImpl asia = (MCRCategoryImpl) category.getChildren().get(1);
MCRCategoryImpl spain = (MCRCategoryImpl) europe.getChildren().get(3);
assertEquals("Did not get Asia as right sibling of Europe", asia.getId(),
europe.getRightSiblingOrParent().getId());
assertEquals("Did not get Europa as right sibling or ancestor of Spain", europe.getId(),
spain.getRightSiblingOrParent().getId());
}
/**
* @throws URISyntaxException
* @throws SAXParseException
* @throws MCRException
*/
private void loadWorldClassification() throws URISyntaxException, MCRException, IOException, JDOMException {
URL worlClassUrl = this.getClass().getResource(WORLD_CLASS_RESOURCE_NAME);
Document xml = MCRXMLParserFactory.getParser().parseXML(new MCRURLContent(worlClassUrl));
category = MCRCategoryImpl.wrapCategory(MCRXMLTransformer.getCategory(xml), null, null);
category.calculateLeftRightAndLevel(1, 0);
}
private static MCRCategoryImpl buildNode(MCRCategoryID id) {
MCRCategoryImpl rootNode = new MCRCategoryImpl();
rootNode.setId(id);
final List<MCRCategory> emptyList = Collections.emptyList();
rootNode.setChildren(emptyList);
return rootNode;
}
}
| 7,020 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractCategoryImplTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/impl/MCRAbstractCategoryImplTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTestCase;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRLabel;
public class MCRAbstractCategoryImplTest extends MCRTestCase {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
System.setProperty("MCR.Metadata.DefaultLang.foo", "true");
}
@After
public void clean() {
System.setProperty("MCR.Metadata.DefaultLang.foo", "false");
}
@Test
public void getCurrentLabel() {
MCRCategory cat = new MCRSimpleAbstractCategoryImpl();
MCRLabel label1 = new MCRLabel("de", "german", null);
MCRLabel label2 = new MCRLabel("fr", "french", null);
MCRLabel label3 = new MCRLabel("at", "austrian", null);
cat.getLabels().add(label1);
cat.getLabels().add(label2);
cat.getLabels().add(label3);
MCRSession session = MCRSessionMgr.getCurrentSession();
session.setCurrentLanguage("en");
assertEquals("German label expected", label3, cat.getCurrentLabel().get());
cat.getLabels().clear();
cat.getLabels().add(label2);
cat.getLabels().add(label3);
cat.getLabels().add(label1);
assertEquals("German label expected", label3, cat.getCurrentLabel().get());
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.DefaultLang", "at");
return testProperties;
}
}
| 2,571 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategLinkServiceImplTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/impl/MCRCategLinkServiceImplTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImplTest.DAO;
import static org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImplTest.WORLD_CLASS_RESOURCE_NAME;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.junit.Before;
import org.junit.Test;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRException;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
/**
* @author Thomas Scheffler (yagee) Need to insert some things here
*/
public class MCRCategLinkServiceImplTest extends MCRJPATestCase {
private static final MCRCategLinkReference ENGLAND_REFERENCE = new MCRCategLinkReference("England", "state");
private static final MCRCategLinkReference LONDON_REFERENCE = new MCRCategLinkReference("London", "city");
private MCRCategory category;
private Collection<MCRCategoryLinkImpl> testLinks;
private static MCRCategLinkServiceImpl SERVICE = null;
private static final Logger LOGGER = LogManager.getLogger(MCRCategLinkServiceImplTest.class);
@Override
@Before
public void setUp() throws Exception {
super.setUp();
if (SERVICE == null) {
SERVICE = new MCRCategLinkServiceImpl();
}
loadWorldClassification();
MCRCategoryImpl germany = (MCRCategoryImpl) category.getChildren().get(0).getChildren().get(0);
MCRCategoryImpl uk = (MCRCategoryImpl) category.getChildren().get(0).getChildren().get(1);
DAO.addCategory(null, category);
testLinks = new ArrayList<>();
testLinks.add(new MCRCategoryLinkImpl(germany, new MCRCategLinkReference("Jena", "city")));
testLinks.add(new MCRCategoryLinkImpl(germany, new MCRCategLinkReference("ThΓΌringen", "state")));
testLinks.add(new MCRCategoryLinkImpl(germany, new MCRCategLinkReference("Hessen", "state")));
testLinks.add(new MCRCategoryLinkImpl(germany, new MCRCategLinkReference("Saale", "river")));
final MCRCategLinkReference northSeaReference = new MCRCategLinkReference("North Sea", "sea");
testLinks.add(new MCRCategoryLinkImpl(germany, northSeaReference));
testLinks.add(new MCRCategoryLinkImpl(uk, LONDON_REFERENCE));
testLinks.add(new MCRCategoryLinkImpl(uk, ENGLAND_REFERENCE));
testLinks.add(new MCRCategoryLinkImpl(uk, new MCRCategLinkReference("Thames", "river")));
testLinks.add(new MCRCategoryLinkImpl(uk, northSeaReference));
}
/**
* Test method for
* {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#setLinks(org.mycore.datamodel.classifications2.MCRCategLinkReference, java.util.Collection)}
* .
*/
@Test
public void setLinks() {
addTestLinks();
startNewTransaction();
assertEquals("Link count does not match.", testLinks.size(), getLinkCount());
}
private int getLinkCount() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Number> countQuery = cb.createQuery(Number.class);
return em
.createQuery(countQuery
.select(cb
.count(countQuery
.from(MCRCategoryLinkImpl.class))))
.getSingleResult()
.intValue();
}
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#deleteLink(MCRCategLinkReference)}.
*/
@Test
public void deleteLink() {
addTestLinks();
startNewTransaction();
SERVICE.deleteLink(LONDON_REFERENCE);
assertEquals("Link count does not match.", testLinks.size() - 1, getLinkCount());
}
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#deleteLinks(java.util.Collection)}.
*/
@Test
public void deleteLinks() {
addTestLinks();
startNewTransaction();
SERVICE.deleteLinks(Arrays.asList(LONDON_REFERENCE, ENGLAND_REFERENCE));
assertEquals("Link count does not match.", testLinks.size() - 2, getLinkCount());
}
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#getLinksFromReference(MCRCategLinkReference)}.
*/
@Test
public void getLinksFromObject() {
addTestLinks();
startNewTransaction();
MCRCategoryLinkImpl link = testLinks.iterator().next();
assertTrue("Did not find category: " + link.getCategory().getId(),
SERVICE.getLinksFromReference(link.getObjectReference()).contains(link.getCategory().getId()));
}
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#getLinksFromCategory(MCRCategoryID)}.
*/
@Test
public void getLinksFromCategory() {
addTestLinks();
startNewTransaction();
MCRCategoryLinkImpl link = testLinks.iterator().next();
assertTrue("Did not find object: " + link.getObjectReference(),
SERVICE.getLinksFromCategory(link.getCategory().getId()).contains(link.getObjectReference().getObjectID()));
}
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#getLinksFromCategoryForType(MCRCategoryID, String)}.
*/
@Test
public void getLinksFromCategoryForType() {
addTestLinks();
startNewTransaction();
MCRCategoryLinkImpl link = testLinks.iterator().next();
final String objectType = link.getObjectReference().getType();
final MCRCategoryID categoryID = link.getCategory().getId();
final String objectID = link.getObjectReference().getObjectID();
final Collection<String> result = SERVICE.getLinksFromCategoryForType(categoryID, objectType);
assertTrue("Did not find object: " + link.getObjectReference(), result.contains(objectID));
for (String id : result) {
String type = getType(id);
assertEquals("Wrong return type detected: " + id, objectType, type);
}
}
private String getType(String objectID) {
return testLinks.stream()
.filter(link -> link.getObjectReference().getObjectID().equals(objectID))
.findFirst()
.map(link -> link.getObjectReference().getType())
.orElse(null);
}
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#countLinks(MCRCategory, boolean)}.
*/
@Test
public void countLinks() {
addTestLinks();
startNewTransaction();
Map<MCRCategoryID, Number> map = SERVICE.countLinks(category, false);
LOGGER.debug("****List of returned map");
LOGGER.debug(map);
assertEquals("Returned amount of MCRCategoryIDs does not match.", getAllCategIDs(category).size(), map.size());
assertEquals("Count of Europe links does not match.", 8, map.get(category.getChildren().get(0).getId())
.intValue());
assertEquals("Count of Germany links does not match.", 5,
map.get(category.getChildren().get(0).getChildren().get(0).getId()).intValue());
map = SERVICE.countLinks(category, true);
assertEquals("Count of Europe links does not match.", 8, map.get(category.getChildren().get(0).getId())
.intValue());
}
/**
* Test method for {@link org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl#countLinksForType(MCRCategory, String, boolean)}.
*/
@Test
public void countLinksForType() {
addTestLinks();
startNewTransaction();
Map<MCRCategoryID, Number> map = SERVICE.countLinksForType(category, "city", false);
LOGGER.debug("****List of returned map");
LOGGER.debug(map);
assertEquals("Returned amount of MCRCategoryIDs does not match.", getAllCategIDs(category).size(), map.size());
assertEquals("Count of Europe links does not match.", 2, map.get(category.getChildren().get(0).getId())
.intValue());
}
@Test
public void hasLinks() {
MCRCategoryImpl germany = (MCRCategoryImpl) category.getChildren().get(0).getChildren().get(0);
assertFalse("Classification should not be in use", SERVICE.hasLinks(category).get(category.getId()));
assertFalse("Classification should not be in use", SERVICE.hasLinks(null).get(category.getId()));
assertFalse("Category should not be in use", SERVICE.hasLinks(germany).get(germany.getId()));
addTestLinks();
startNewTransaction();
assertTrue("Classification should be in use", SERVICE.hasLinks(category).get(category.getId()));
assertTrue("Classification should be in use", SERVICE.hasLinks(null).get(category.getId()));
assertTrue("Category should be in use", SERVICE.hasLinks(germany).get(germany.getId()));
}
@Test
public void isInCategory() {
MCRCategoryImpl germany = (MCRCategoryImpl) category.getChildren().get(0).getChildren().get(0);
MCRCategoryImpl europe = (MCRCategoryImpl) category.getChildren().get(0);
MCRCategoryImpl asia = (MCRCategoryImpl) category.getChildren().get(1);
MCRCategLinkReference jena = new MCRCategLinkReference("Jena", "city");
addTestLinks();
startNewTransaction();
assertTrue("Jena should be in Germany", SERVICE.isInCategory(jena, germany.getId()));
assertTrue("Jena should be in Europe", SERVICE.isInCategory(jena, europe.getId()));
assertFalse("Jena should not be in Asia", SERVICE.isInCategory(jena, asia.getId()));
}
@Test
public void getReferences() {
addTestLinks();
startNewTransaction();
String type = "state";
Collection<MCRCategLinkReference> references = SERVICE.getReferences(type);
assertNotNull("Did not return a collection", references);
assertFalse("Collection is empty", references.isEmpty());
for (MCRCategLinkReference ref : references) {
assertEquals("Type of reference is not correct.", type, ref.getType());
}
assertEquals("Collection is not complete",
testLinks.stream()
.filter(link -> link.getObjectReference().getType().equals(type))
.count(),
references.size());
}
private void loadWorldClassification() throws URISyntaxException, MCRException, IOException, JDOMException {
URL worlClassUrl = this.getClass().getResource(WORLD_CLASS_RESOURCE_NAME);
Document xml = MCRXMLParserFactory.getParser().parseXML(new MCRURLContent(worlClassUrl));
category = MCRXMLTransformer.getCategory(xml);
}
private void addTestLinks() {
for (MCRCategoryLinkImpl link : testLinks) {
SERVICE.setLinks(link.getObjectReference(), Collections.nCopies(1, link.getCategory().getId()));
}
}
private static Collection<MCRCategoryID> getAllCategIDs(MCRCategory category) {
HashSet<MCRCategoryID> ids = new HashSet<>();
ids.add(category.getId());
for (MCRCategory cat : category.getChildren()) {
ids.addAll(getAllCategIDs(cat));
}
return ids;
}
}
| 13,091 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSimpleAbstractCategoryImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/impl/MCRSimpleAbstractCategoryImpl.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.List;
import java.util.TreeSet;
import org.mycore.datamodel.classifications2.MCRCategory;
final class MCRSimpleAbstractCategoryImpl extends MCRAbstractCategoryImpl {
{
labels = new TreeSet<>();
}
@Override
protected void setChildrenUnlocked(List<MCRCategory> children) {
}
@Override
public int getLevel() {
return 0;
}
}
| 1,170 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryDAOImplTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/classifications2/impl/MCRCategoryDAOImplTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.hibernate.Session;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRException;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.MCRStreamUtils;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.datamodel.classifications2.utils.MCRCategoryTransformer;
import org.mycore.datamodel.classifications2.utils.MCRStringTransformer;
import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer;
import org.xml.sax.SAXParseException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
public class MCRCategoryDAOImplTest extends MCRJPATestCase {
static final String WORLD_CLASS_RESOURCE_NAME = "/worldclass.xml";
private static final String WORLD_CLASS2_RESOURCE_NAME = "/worldclass2.xml";
static final String CATEGORY_MAPPING_RESOURCE_NAME
= "/org/mycore/datamodel/classifications2/impl/MCRCategoryImpl.hbm.xml";
static final MCRCategoryDAOImpl DAO = new MCRCategoryDAOImpl();
private MCRCategory category, category2;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
loadWorldClassification();
}
@After
@Override
public void tearDown() throws Exception {
try {
startNewTransaction();
MCRCategoryImpl rootNode = getRootCategoryFromSession();
MCRCategoryImpl rootNode2 = (MCRCategoryImpl) DAO.getCategory(category.getId(), -1);
if (rootNode != null) {
try {
checkLeftRightLevelValue(rootNode, 0, 0);
checkLeftRightLevelValue(rootNode2, 0, 0);
} catch (AssertionError e) {
LogManager.getLogger().error("Error while checking left, right an level values in database.");
new XMLOutputter(Format.getPrettyFormat())
.output(MCRCategoryTransformer.getMetaDataDocument(rootNode, false), System.out);
printCategoryTable();
throw e;
}
}
} finally {
super.tearDown();
}
}
@Test
public void testLicenses() throws Exception {
MCRCategory licenses = loadClassificationResource("/mycore-classifications/mir_licenses.xml");
DAO.addCategory(null, licenses);
MCRCategoryID cc_30 = new MCRCategoryID(licenses.getId().getRootID(), "cc_3.0");
DAO.deleteCategory(cc_30);
startNewTransaction();
}
@Test
public void testClassEditorBatch() throws Exception {
EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
MCRCategory nameIdentifier = loadClassificationResource("/mycore-classifications/nameIdentifier.xml");
MCRCategory secondCateg = nameIdentifier.getChildren().get(1);
DAO.addCategory(null, nameIdentifier);
startNewTransaction();
MCRCategLinkServiceFactory.getInstance().getLinksFromCategory(secondCateg.getId());
assertTrue(secondCateg.getId() + " should exist.", DAO.exist(secondCateg.getId()));
//re-set labels
DAO.setLabels(secondCateg.getId(), new TreeSet<>(secondCateg.getLabels().stream().collect(Collectors.toSet())));
//re-set URI
entityManager.detach(DAO.setURI(secondCateg.getId(), secondCateg.getURI()));
//move to new index
DAO.moveCategory(secondCateg.getId(), secondCateg.getParent().getId(), 0);
startNewTransaction();
MCRCategoryImpl copyOfDB = MCRCategoryDAOImpl.getByNaturalID(entityManager,
secondCateg.getId());
assertNotNull(secondCateg.getId() + " must hav a parent.", copyOfDB.getParent());
}
@Test
public void addCategory() throws MCRException {
addWorldClassification();
assertTrue("Exist check failed for Category " + category.getId(), DAO.exist(category.getId()));
MCRCategoryImpl india = new MCRCategoryImpl();
india.setId(new MCRCategoryID(category.getId().getRootID(), "India"));
india.setLabels(new TreeSet<>());
india.getLabels().add(new MCRLabel("de", "Indien", null));
india.getLabels().add(new MCRLabel("en", "India", null));
DAO.addCategory(new MCRCategoryID(category.getId().getRootID(), "Asia"), india);
startNewTransaction();
assertTrue("Exist check failed for Category " + india.getId(), DAO.exist(india.getId()));
MCRCategoryImpl rootCategory = getRootCategoryFromSession();
assertEquals("Child category count does not match.", category.getChildren().size(), rootCategory.getChildren()
.size());
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Number> countQuery = cb.createQuery(Number.class);
long allNodes = em
.createQuery(countQuery
.select(cb
.count(countQuery
.from(MCRCategoryImpl.class))))
.getSingleResult()
.longValue();
// category + india
assertEquals("Complete category count does not match.", countNodes(category) + 1, allNodes);
assertTrue("No root category present", rootCategory.getRoot() != null);
}
/**
* Test case for https://sourceforge.net/p/mycore/bugs/612/
*/
@Test
public void addCategorySingleSteps() {
MCRCategory root = new MCRCategoryImpl();
MCRCategoryID rootID = MCRCategoryID.rootID("junit");
root.setId(rootID);
DAO.addCategory(null, root);
startNewTransaction();
MCRCategory a = new MCRCategoryImpl();
MCRCategoryID aId = new MCRCategoryID(rootID.getRootID(), "a");
a.setId(aId);
MCRCategory b = new MCRCategoryImpl();
MCRCategoryID bId = new MCRCategoryID(rootID.getRootID(), "b");
b.setId(bId);
MCRCategory c = new MCRCategoryImpl();
MCRCategoryID cId = new MCRCategoryID(rootID.getRootID(), "c");
c.setId(cId);
DAO.addCategory(rootID, a);
DAO.addCategory(rootID, c);
DAO.addCategory(aId, b);
startNewTransaction();
assertTrue("Category c should not contain child categories.", DAO.getChildren(cId).isEmpty());
assertFalse("Category a should contain child categories.", DAO.getChildren(aId).isEmpty());
root = DAO.getCategory(rootID, -1);
checkLeftRightLevelValue((MCRCategoryImpl) root, 0, 0);
assertEquals("Did not get all categories", 4, countNodes(root));
List<MCRCategory> children = root.getChildren();
assertEquals("Children count mismatch", 2, children.size());
a = children.get(0);
c = children.get(1);
assertEquals("Wrong order of children", aId, a.getId());
assertEquals("Wrong order of children", cId, c.getId());
assertTrue("Category c should not contain child categories.", c.getChildren().isEmpty());
assertFalse("Category a should contain child categories.", a.getChildren().isEmpty());
}
/**
* Test case for https://sourceforge.net/p/mycore/bugs/664/
*/
@Test
public void addCategoryToPosition() {
addWorldClassification();
MCRCategoryImpl america = new MCRCategoryImpl();
MCRCategoryID categoryID = new MCRCategoryID(category.getId().getRootID(), "America");
america.setId(categoryID);
america.setLabels(new TreeSet<>());
america.getLabels().add(new MCRLabel("de", "Amerika", null));
america.getLabels().add(new MCRLabel("en", "America", null));
DAO.addCategory(category.getId(), america, 1);
startNewTransaction();
america = MCRCategoryDAOImpl.getByNaturalID(getEntityManager().get(), america.getId());
assertNotNull(categoryID + " was not added to database.", america);
assertEquals("invalid position in parent", 1, america.getPositionInParent());
}
@Test
public void deleteRootCategory() {
addWorldClassification();
testDelete(category);
}
@Test
public void deleteSubCategory() {
addWorldClassification();
MCRCategory deleteCategory = category.getChildren().get(0);
assertTrue("Sub category does not exist.", DAO.exist(deleteCategory.getId()));
testDelete(deleteCategory);
}
@Test
public void deleteMultipleCategories() {
//check for MCR-1863
addWorldClassification();
List<MCRCategoryID> europeChildrenIds = category.getChildren()
.get(0)
.getChildren()
.stream()
.map(MCRCategory::getId)
.collect(Collectors.toList());
DAO.deleteCategory(europeChildrenIds.get(0));
DAO.deleteCategory(europeChildrenIds.get(1));
DAO.deleteCategory(europeChildrenIds.get(2));
}
private void testDelete(MCRCategory deleteCategory) {
DAO.deleteCategory(deleteCategory.getId());
startNewTransaction();
// check if classification is present
assertFalse("Category is not deleted: " + deleteCategory.getId(), DAO.exist(deleteCategory.getId()));
// check if any subcategory is present
assertFalse("Category is not deleted: " + deleteCategory.getChildren().get(0).getId(),
DAO.exist(deleteCategory.getChildren().get(0).getId()));
}
@Test
public void getCategoriesByLabel() {
addWorldClassification();
MCRCategory find = category.getChildren().get(0).getChildren().get(0);
MCRCategory dontFind = category.getChildren().get(1);
MCRLabel label = find.getLabels().iterator().next();
List<MCRCategory> results = DAO.getCategoriesByLabel(category.getId(), label.getLang(), label.getText());
assertFalse("No search results found", results.isEmpty());
assertTrue("Could not find Category: " + find.getId(), results.get(0).getLabels().contains(label));
assertTrue("No search result expected.",
DAO.getCategoriesByLabel(dontFind.getId(), label.getLang(), label.getText()).isEmpty());
results = DAO.getCategoriesByLabel(label.getLang(), label.getText());
assertFalse("No search results found", results.isEmpty());
assertTrue("Could not find Category: " + find.getId(), results.get(0).getLabels().contains(label));
}
@Test
public void getCategory() {
addWorldClassification();
MCRCategory rootCategory = DAO.getCategory(category.getId(), 0);
assertTrue("Children present with child Level 0.", rootCategory.getChildren().isEmpty());
rootCategory = DAO.getCategory(category.getId(), 1);
MCRCategory origSubCategory = rootCategory.getChildren().get(0);
assertTrue("Children present with child Level 1.", origSubCategory.getChildren().isEmpty());
assertEquals(
"Category count does not match with child Level 1.\n" + MCRStringTransformer.getString(rootCategory),
category.getChildren().size(), rootCategory.getChildren().size());
assertEquals(
"Children of Level 1 do not know that they are at the first level.\n"
+ MCRStringTransformer.getString(rootCategory),
1, origSubCategory.getLevel());
MCRCategory europe = DAO.getCategory(category.getChildren().get(0).getId(), -1);
assertFalse("No children present in " + europe.getId(), europe.getChildren().isEmpty());
europe = DAO.getCategory(category.getChildren().get(0).getId(), 1);
assertFalse("No children present in " + europe.getId(), europe.getChildren().isEmpty());
rootCategory = DAO.getCategory(category.getId(), -1);
assertEquals("Did not get all categories." + MCRStringTransformer.getString(rootCategory),
countNodes(category), countNodes(rootCategory));
assertEquals("Children of Level 1 do not match", category.getChildren().size(), rootCategory.getChildren()
.size());
MCRCategory subCategory = DAO.getCategory(origSubCategory.getId(), 0);
assertNotNull("Did not return ", subCategory);
assertEquals("ObjectIDs did not match", origSubCategory.getId(), subCategory.getId());
assertNotNull("Root category may not null.", subCategory.getRoot());
assertEquals("Root does not match", origSubCategory.getRoot().getId(), subCategory.getRoot().getId());
MCRCategory germanyResource = find(category, "Germany").get();
MCRCategory germanyDB = DAO.getCategory(germanyResource.getId(), 1);
printCategoryTable();
assertEquals("Children of Level 1 do not match", germanyResource.getChildren().size(), germanyDB.getChildren()
.size());
}
@Test
public void getChildren() {
addWorldClassification();
List<MCRCategory> children = DAO.getChildren(category.getId());
assertEquals("Did not get all children of :" + category.getId(), category.getChildren().size(),
children.size());
for (int i = 0; i < children.size(); i++) {
assertEquals("Category IDs of children do not match.", category.getChildren().get(i).getId(),
children.get(i).getId());
}
}
@Test
public void getParents() {
addWorldClassification();
MCRCategory find = category.getChildren().get(0).getChildren().get(0);
List<MCRCategory> parents = DAO.getParents(find.getId());
MCRCategory findParent = find;
for (MCRCategory parent : parents) {
findParent = findParent.getParent();
assertNotNull("Returned too much parents.", findParent);
assertEquals("Parents did not match.", findParent.getId(), parent.getId());
}
}
@Test
public void getRootCategoryIDs() {
addWorldClassification();
MCRCategoryID find = category.getId();
List<MCRCategoryID> classIds = DAO.getRootCategoryIDs();
assertEquals("Result size does not match.", 1, classIds.size());
assertEquals("Returned MCRCategoryID does not match.", find, classIds.get(0));
}
@Test
public void getRootCategories() {
addWorldClassification();
MCRCategoryID find = category.getId();
List<MCRCategory> classes = DAO.getRootCategories();
assertEquals("Result size does not match.", 1, classes.size());
assertEquals("Returned MCRCategoryID does not match.", find, classes.get(0).getId());
}
@Test
public void getRootCategory() {
addWorldClassification();
// Europe
MCRCategory find = category.getChildren().get(0);
MCRCategory rootCategory = DAO.getRootCategory(find.getId(), 0);
assertEquals("Category count does not match.", 2, countNodes(rootCategory));
assertEquals("Did not get root Category.", find.getRoot().getId(), rootCategory.getId());
rootCategory = DAO.getRootCategory(find.getId(), -1);
assertEquals("Category count does not match.", 1 + countNodes(find), countNodes(rootCategory));
}
@Test
public void children() {
addWorldClassification();
assertTrue("Category '" + category.getId() + "' should have children.", DAO.hasChildren(category.getId()));
assertFalse("Category '" + category.getChildren().get(1).getId() + "' shouldn't have children.",
DAO.hasChildren(category.getChildren().get(1).getId()));
}
@Test
public void moveCategoryWithoutIndex() {
addWorldClassification();
checkLeftRightLevelValue(getRootCategoryFromSession(), 0, 0);
startNewTransaction();
MCRCategory moveNode = category.getChildren().get(1);
// Europe conquer Asia
DAO.moveCategory(moveNode.getId(), category.getChildren().get(0).getId());
startNewTransaction();
MCRCategoryImpl rootNode = getRootCategoryFromSession();
checkLeftRightLevelValue(rootNode, 0, 0);
}
@Test
public void moveCategoryInParent() {
addWorldClassification();
MCRCategory moveNode = category.getChildren().get(1);
DAO.moveCategory(moveNode.getId(), moveNode.getParent().getId(), 0);
startNewTransaction();
MCRCategoryImpl rootNode = getRootCategoryFromSession();
checkLeftRightLevelValue(rootNode, 0, 0);
MCRCategory movedNode = rootNode.getChildren().get(0);
assertEquals("Did not expect this category on position 0.", moveNode.getId(), movedNode.getId());
}
@Test
public void moveRightCategory() {
String rootIDStr = "rootID";
MCRCategoryID rootID = MCRCategoryID.rootID(rootIDStr);
MCRCategoryID child1ID = new MCRCategoryID(rootIDStr, "child1");
MCRCategoryID child2ID = new MCRCategoryID(rootIDStr, "child2");
MCRCategoryID child3ID = new MCRCategoryID(rootIDStr, "child3");
MCRCategoryImpl root = newCategory(rootID, "root node");
addChild(root, newCategory(child1ID, "child node 1"));
addChild(root, newCategory(child2ID, "child node 2"));
addChild(root, newCategory(child3ID, "child node 3"));
startNewTransaction();
DAO.addCategory(null, root);
endTransaction();
startNewTransaction();
printCategoryTable();
endTransaction();
assertLeftRightVal(rootID, 0, 7);
assertLeftRightVal(child1ID, 1, 2);
assertLeftRightVal(child2ID, 3, 4);
assertLeftRightVal(child3ID, 5, 6);
startNewTransaction();
DAO.moveCategory(child2ID, child1ID, 0);
DAO.moveCategory(child3ID, child1ID, 1);
endTransaction();
startNewTransaction();
printCategoryTable();
endTransaction();
assertLeftRightVal(rootID, 0, 7);
assertLeftRightVal(child1ID, 1, 6);
assertLeftRightVal(child2ID, 2, 3);
assertLeftRightVal(child3ID, 4, 5);
}
@Test
public void moveCategoryUp() {
String rootIDStr = "rootID";
MCRCategoryID rootID = MCRCategoryID.rootID(rootIDStr);
MCRCategoryID child1ID = new MCRCategoryID(rootIDStr, "child1");
MCRCategoryID child2ID = new MCRCategoryID(rootIDStr, "child2");
MCRCategoryImpl root = newCategory(rootID, "root node");
MCRCategoryImpl child1 = newCategory(child1ID, "child node 1");
addChild(root, child1);
addChild(child1, newCategory(child2ID, "child node 2"));
startNewTransaction();
DAO.addCategory(null, root);
endTransaction();
assertLeftRightVal(rootID, 0, 5);
assertLeftRightVal(child1ID, 1, 4);
assertLeftRightVal(child2ID, 2, 3);
startNewTransaction();
DAO.moveCategory(child2ID, rootID);
endTransaction();
startNewTransaction();
printCategoryTable();
endTransaction();
assertLeftRightVal(rootID, 0, 5);
assertLeftRightVal(child1ID, 1, 2);
assertLeftRightVal(child2ID, 3, 4);
}
@Test
public void moveCategoryDeep() {
String rootIDStr = "rootID";
MCRCategoryID rootID = MCRCategoryID.rootID(rootIDStr);
MCRCategoryID child1ID = new MCRCategoryID(rootIDStr, "child1");
MCRCategoryID child2ID = new MCRCategoryID(rootIDStr, "child2");
MCRCategoryID child3ID = new MCRCategoryID(rootIDStr, "child3");
MCRCategoryID child4ID = new MCRCategoryID(rootIDStr, "child4");
MCRCategoryImpl root = newCategory(rootID, "root node");
MCRCategoryImpl a = newCategory(child1ID, "child node 1");
MCRCategoryImpl aa = newCategory(child2ID, "child node 2");
MCRCategoryImpl aaa = newCategory(child3ID, "child node 3");
MCRCategoryImpl aab = newCategory(child4ID, "child node 4");
addChild(root, a);
addChild(a, aa);
addChild(aa, aaa);
addChild(aa, aab);
startNewTransaction();
DAO.addCategory(null, root);
endTransaction();
startNewTransaction();
DAO.moveCategory(child4ID, child3ID);
endTransaction();
}
private void assertLeftRightVal(MCRCategoryID categID, int expectedLeftVal, int expectedRightVal) {
startNewTransaction();
MCRCategoryImpl retrievedRoot = (MCRCategoryImpl) DAO.getCategory(categID, 0);
endTransaction();
assertNotNull(retrievedRoot);
assertEquals("Left value should be " + expectedLeftVal + ".", expectedLeftVal, retrievedRoot.getLeft());
assertEquals("Right value should be " + expectedRightVal + ".", expectedRightVal, retrievedRoot.getRight());
}
private void addChild(MCRCategoryImpl parent, MCRCategoryImpl child) {
List<MCRCategory> children = parent.getChildren();
if (children == null) {
parent.setChildren(new ArrayList<>());
children = parent.getChildren();
}
children.add(child);
}
private MCRCategoryImpl newCategory(MCRCategoryID id, String description) {
MCRCategoryImpl newCateg = new MCRCategoryImpl();
newCateg.setId(id);
SortedSet<MCRLabel> labels = new TreeSet<>();
labels.add(new MCRLabel("en", id.toString(), description));
newCateg.setLabels(labels);
return newCateg;
}
@Test
public void removeLabel() {
addWorldClassification();
final MCRCategory labelNode = category.getChildren().get(0);
int labelCount = labelNode.getLabels().size();
DAO.removeLabel(labelNode.getId(), "en");
startNewTransaction();
final MCRCategory labelNodeNew = getRootCategoryFromSession().getChildren().get(0);
assertEquals("Label count did not match.", labelCount - 1, labelNodeNew.getLabels().size());
}
@Test
public void replaceCategory() throws URISyntaxException, MCRException, IOException, JDOMException {
loadWorldClassification2();
addWorldClassification();
DAO.replaceCategory(category2);
startNewTransaction();
MCRCategoryImpl rootNode = getRootCategoryFromSession();
assertEquals("Category count does not match.", countNodes(category2), countNodes(rootNode));
assertEquals("Label count does not match.", category2.getChildren().get(0).getLabels().size(), rootNode
.getChildren().get(0).getLabels().size());
checkLeftRightLevelValue(rootNode, 0, 0);
final URI germanURI = new URI("http://www.deutschland.de");
final MCRCategory germany = rootNode.getChildren().get(0).getChildren().get(0);
assertEquals("URI was not updated", germanURI, germany.getURI());
}
@Test
public void replaceCategoryWithAdoption() throws URISyntaxException, MCRException, IOException, JDOMException {
MCRCategory gc1 = loadClassificationResource("/grandchild.xml");
MCRCategory gc2 = loadClassificationResource("/grandchild2.xml");
DAO.addCategory(null, gc1);
startNewTransaction();
DAO.replaceCategory(gc2);
startNewTransaction();
MCRCategoryImpl rootNode = (MCRCategoryImpl) DAO.getRootCategory(gc2.getId(), -1);
assertEquals("Category count does not match.", countNodes(gc2), countNodes(rootNode));
checkLeftRightLevelValue(rootNode, 0, 0);
}
@Test
public void replaceSameCategory() throws Exception {
loadWorldClassification2();
addWorldClassification();
MCRCategory oldCategory = DAO.getCategory(new MCRCategoryID("World", "Europe"), -1);
DAO.replaceCategory(oldCategory);
}
@Test
public void replaceMarcRelator() throws Exception {
MCRCategory marcrelator = loadClassificationResource("/marcrelator-test.xml");
DAO.addCategory(null, marcrelator);
startNewTransaction();
marcrelator = loadClassificationResource("/marcrelator-test2.xml");
DAO.replaceCategory(marcrelator);
}
@Test
public void setLabel() {
addWorldClassification();
startNewTransaction();
// test add
int count = category.getLabels().size();
final String lang = "ju";
final String text = "JUnit-Test";
DAO.setLabel(category.getId(), new MCRLabel(lang, text, "Added by JUnit"));
startNewTransaction();
MCRCategory rootNode = getRootCategoryFromSession();
assertEquals("Label count does not match.", count + 1, rootNode.getLabels().size());
// test modify
String description = "Modified by JUnit";
DAO.setLabel(category.getId(), new MCRLabel(lang, text, description));
startNewTransaction();
rootNode = getRootCategoryFromSession();
assertEquals("Label count does not match.", count + 1, rootNode.getLabels().size());
assertEquals("Label does not match.", description, rootNode.getLabel(lang).get().getDescription());
}
@Test
public void setLabels() {
addWorldClassification();
startNewTransaction();
MCRCategory germany = DAO.getCategory(MCRCategoryID.fromString("World:Germany"), 0);
MCRCategory france = DAO.getCategory(MCRCategoryID.fromString("World:France"), 0);
SortedSet<MCRLabel> labels1 = new TreeSet<>();
labels1.add(new MCRLabel("de", "deutschland", null));
DAO.setLabels(germany.getId(), labels1);
startNewTransaction();
SortedSet<MCRLabel> labels2 = new TreeSet<>();
labels2.add(new MCRLabel("de", "frankreich", null));
DAO.setLabels(france.getId(), labels2);
startNewTransaction();
germany = DAO.getCategory(MCRCategoryID.fromString("World:Germany"), 0);
france = DAO.getCategory(MCRCategoryID.fromString("World:France"), 0);
assertEquals(1, germany.getLabels().size());
assertEquals(1, france.getLabels().size());
assertEquals("deutschland", germany.getLabel("de").get().getText());
assertEquals("frankreich", france.getLabel("de").get().getText());
}
/**
* tests relink child to grandparent and removal of parent.
*
*/
@Test
public void replaceCategoryShiftCase() {
addWorldClassification();
MCRCategory europe = category.getChildren().get(0);
MCRCategory germany = europe.getChildren().get(0);
europe.getChildren().remove(0);
assertNull("Germany should not have a parent right now", germany.getParent());
category.getChildren().remove(0);
assertNull("Europe should not have a parent right now", europe.getParent());
category.getChildren().add(germany);
assertEquals("Germany should not have world as parent right now", category.getId(),
germany.getParent().getId());
DAO.replaceCategory(category);
startNewTransaction();
MCRCategory rootNode = getRootCategoryFromSession();
assertEquals("Category count does not match.", countNodes(category), countNodes(rootNode));
assertEquals("Label count does not match.", category.getChildren().get(0).getLabels().size(), rootNode
.getChildren().get(0).getLabels().size());
}
@Test
public void replaceCategoryWithItself() {
addWorldClassification();
MCRCategory europe = category.getChildren().get(0);
MCRCategory germany = europe.getChildren().get(0);
DAO.replaceCategory(germany);
startNewTransaction();
getRootCategoryFromSession();
}
/**
* tests top category child to new parent
*
*/
public void testReplaceCategoryNewParent() {
addWorldClassification();
MCRCategory europe = category.getChildren().get(0);
MCRCategoryImpl test = new MCRCategoryImpl();
test.setId(new MCRCategoryID(category.getId().getRootID(), "test"));
test.setLabels(new TreeSet<>());
test.getLabels().add(new MCRLabel("de", "JUnit testcase", null));
category.getChildren().add(test);
category.getChildren().remove(0);
test.getChildren().add(europe);
DAO.replaceCategory(category);
startNewTransaction();
MCRCategory rootNode = getRootCategoryFromSession();
assertEquals("Category count does not match.", countNodes(category), countNodes(rootNode));
assertEquals("Label count does not match.", category.getChildren().get(0).getLabels().size(), rootNode
.getChildren().get(0).getLabels().size());
}
private MCRCategoryImpl getRootCategoryFromSession() {
return MCREntityManagerProvider.getCurrentEntityManager().find(MCRCategoryImpl.class,
((MCRCategoryImpl) category).getInternalID());
}
private void addWorldClassification() {
DAO.addCategory(null, category);
startNewTransaction();
}
/**
* @throws URISyntaxException
* @throws SAXParseException
* @throws MCRException
*/
private void loadWorldClassification() throws URISyntaxException, MCRException, IOException, JDOMException {
category = loadClassificationResource(WORLD_CLASS_RESOURCE_NAME);
}
public static MCRCategory loadClassificationResource(String resourceName)
throws URISyntaxException, IOException, JDOMException {
URL classResourceUrl = MCRCategoryDAOImplTest.class.getResource(resourceName);
Document xml = MCRXMLParserFactory.getParser().parseXML(new MCRURLContent(classResourceUrl));
return MCRXMLTransformer.getCategory(xml);
}
private void loadWorldClassification2() throws URISyntaxException, MCRException, IOException, JDOMException {
category2 = loadClassificationResource(WORLD_CLASS2_RESOURCE_NAME);
}
private static int countNodes(MCRCategory category) {
return (int) MCRStreamUtils.flatten(category, MCRCategory::getChildren, Collection::stream)
.count();
}
private int checkLeftRightLevelValue(MCRCategoryImpl node, int leftStart, int levelStart) {
int curValue = leftStart;
final int nextLevel = levelStart + 1;
assertEquals("Left value did not match on ID: " + node.getId(), leftStart, node.getLeft());
assertEquals("Level value did not match on ID: " + node.getId(), levelStart, node.getLevel());
for (MCRCategory child : node.getChildren()) {
curValue = checkLeftRightLevelValue((MCRCategoryImpl) child, ++curValue, nextLevel);
}
assertEquals("Right value did not match on ID: " + node.getId(), ++curValue, node.getRight());
return curValue;
}
private void printCategoryTable() {
printTable("MCRCategory");
}
private Optional<MCRCategory> find(MCRCategory base, String id) {
MCRCategoryID lookFor = new MCRCategoryID(base.getId().getRootID(), id);
return MCRStreamUtils
.flatten(base, MCRCategory::getChildren, Collection::stream)
.filter(c -> c.getId().equals(lookFor))
.findAny();
}
}
| 32,984 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfoEntityManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/objectinfo/MCRObjectInfoEntityManagerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.List;
import java.util.Map;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.backend.jpa.MCRObjectIDPK;
import org.mycore.backend.jpa.objectinfo.MCRObjectInfoEntity;
import org.mycore.backend.jpa.objectinfo.MCRObjectInfoEntityManager;
import org.mycore.common.MCRJPATestCase;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
public class MCRObjectInfoEntityManagerTest extends MCRJPATestCase {
@Override
protected Map<String, String> getTestProperties() {
final Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
return testProperties;
}
@Before
public void setUp() throws Exception {
super.setUp();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void removeAll() {
MCRObjectInfoEntity entity = new MCRObjectInfoEntity();
entity.setId(MCRObjectID.getInstance("junit_test_00000001"));
final EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
entityManager.persist(entity);
startNewTransaction();
Assert.assertNotEquals(0, getObjectEntities().size());
MCRObjectInfoEntityManager.removeAll();
startNewTransaction();
Assert.assertEquals(0, getObjectEntities().size());
}
private static List<MCRObjectInfoEntity> getObjectEntities() {
final TypedQuery<MCRObjectInfoEntity> listEntities = MCREntityManagerProvider.getCurrentEntityManager()
.createQuery("FROM MCRObjectInfoEntity", MCRObjectInfoEntity.class);
final List<MCRObjectInfoEntity> entities = listEntities.getResultList();
return entities;
}
@Test
public void getByID() {
MCRObjectInfoEntity entity = new MCRObjectInfoEntity();
entity.setId(MCRObjectID.getInstance("junit_test_00000001"));
MCREntityManagerProvider.getCurrentEntityManager().persist(entity);
final MCRObjectInfoEntity byID = MCRObjectInfoEntityManager.getByID(entity.getId());
Assert.assertNotNull(byID);
Assert.assertEquals(entity.getId(), byID.getId());
}
@Test
public void update() {
MCRObjectInfoEntity entity = new MCRObjectInfoEntity();
entity.setId(MCRObjectID.getInstance("junit_test_00000001"));
MCREntityManagerProvider.getCurrentEntityManager().persist(entity);
final MCRObjectInfoEntity loadedEntity = MCREntityManagerProvider.getCurrentEntityManager()
.find(MCRObjectInfoEntity.class, new MCRObjectIDPK(entity.getId()));
startNewTransaction();
MCRObject obj = new MCRObject();
obj.setId(entity.getId());
MCRObjectInfoEntityManager.update(obj);
final MCRObjectInfoEntity updatedEntity = MCREntityManagerProvider.getCurrentEntityManager()
.find(MCRObjectInfoEntity.class, new MCRObjectIDPK(entity.getId()));
Assert.assertNotEquals(loadedEntity.getCreateDate(), updatedEntity.getCreateDate());
Assert.assertNotEquals(loadedEntity.getModifyDate(), updatedEntity.getModifyDate());
}
@Test
public void create() {
MCRObject obj = new MCRObject();
obj.setId(MCRObjectID.getInstance("junit_test_00000001"));
MCRObjectInfoEntityManager.create(obj);
final MCRObjectInfoEntity entity = MCREntityManagerProvider.getCurrentEntityManager()
.find(MCRObjectInfoEntity.class, new MCRObjectIDPK(obj.getId()));
Assert.assertNotNull(entity);
}
@Test
public void remove() {
MCRObjectInfoEntity entity = new MCRObjectInfoEntity();
entity.setId(MCRObjectID.getInstance("junit_test_00000001"));
final EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
entityManager.persist(entity);
startNewTransaction();
MCRObject obj = new MCRObject();
obj.setId(entity.getId());
MCRObjectInfoEntityManager.remove(obj);
final MCRObjectInfoEntity removedEntity = MCREntityManagerProvider.getCurrentEntityManager()
.find(MCRObjectInfoEntity.class, new MCRObjectIDPK(obj.getId()));
Assert.assertNull(removedEntity);
}
@Test
public void delete() {
MCRObjectInfoEntity entity = new MCRObjectInfoEntity();
entity.setId(MCRObjectID.getInstance("junit_test_00000001"));
final EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
entityManager.persist(entity);
startNewTransaction();
MCRObject obj = new MCRObject();
obj.setId(entity.getId());
final Instant now = Instant.now();
MCRObjectInfoEntityManager.delete(obj, now, "junit");
final MCRObjectInfoEntity deletedEntity = MCREntityManagerProvider.getCurrentEntityManager()
.find(MCRObjectInfoEntity.class, new MCRObjectIDPK(obj.getId()));
Assert.assertNotNull(deletedEntity);
Assert.assertEquals(now, deletedEntity.getDeleteDate());
Assert.assertEquals("junit", deletedEntity.getDeletedBy());
}
}
| 6,206 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectInfoEntityQueryResolverTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/objectinfo/MCRObjectInfoEntityQueryResolverTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.net.URISyntaxException;
import java.net.URL;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.backend.jpa.objectinfo.MCRObjectInfoEntity;
import org.mycore.backend.jpa.objectinfo.MCRObjectInfoEntityQueryResolver;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.content.MCRURLContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImpl;
import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.persistence.EntityManager;
public class MCRObjectInfoEntityQueryResolverTest extends MCRJPATestCase {
public static final Instant YESTERDAY = Instant.now().minus(24, ChronoUnit.HOURS);
public static final Instant ONE_WEEK_AGO = Instant.now().minus(24 * 7, ChronoUnit.HOURS);
public static final Instant TWO_WEEKS_AGO = Instant.now().minus(2 * 24 * 7, ChronoUnit.HOURS);
public static final Instant THREE_WEEKS_AGO = Instant.now().minus(3 * 24 * 7, ChronoUnit.HOURS);
public static final String TEST_ID_1 = "junit_foo_00000001";
public static final String TEST_ID_2 = "junit_test_00000002";
public static final String TEST_USER_1 = "editor";
public static final String TEST_USER_2 = "admin";
public static final String TEST_STATE_1 = "submitted";
public static final String TEST_STATE_2 = "published";
public static final String TEST_CATEGORY_1 = "mir_licenses:cc_3.0";
public static final String TEST_CATEGORY_2 = "mir_licenses:rights_reserved";
public static final String TEST_CATEGORY_3 = "mir_licenses:ogl";
static MCRCategoryDAOImpl DAO;
static MCRCategLinkService CLS;
private MCRObjectQueryResolver instance;
private static void initClassifications() throws URISyntaxException, IOException, JDOMException {
DAO = new MCRCategoryDAOImpl();
CLS = MCRCategLinkServiceFactory.getInstance();
URL classResourceUrl = MCRObjectInfoEntityQueryResolverTest.class
.getResource("/mycore-classifications/mir_licenses.xml");
Document xml = MCRXMLParserFactory.getParser().parseXML(new MCRURLContent(classResourceUrl));
MCRCategory licenses = MCRXMLTransformer.getCategory(xml);
DAO.addCategory(null, licenses);
}
@Before
public void setUp() throws Exception {
super.setUp();
initClassifications();
storeObjectInfo(
TEST_ID_1,
ONE_WEEK_AGO,
YESTERDAY,
TEST_USER_2,
TEST_USER_1,
TEST_STATE_1,
Stream.of(TEST_CATEGORY_1, TEST_CATEGORY_3).collect(Collectors.toList()));
storeObjectInfo(
TEST_ID_2,
THREE_WEEKS_AGO,
TWO_WEEKS_AGO,
TEST_USER_1,
TEST_USER_2,
TEST_STATE_2,
Stream.of(TEST_CATEGORY_2, TEST_CATEGORY_3).collect(Collectors.toList()));
instance = MCRObjectQueryResolver.getInstance();
}
public MCRObjectInfoEntity storeObjectInfo(String id,
Instant createdDate,
Instant modifiedDate,
String createdBy,
String modifiedBy,
String state,
List<String> linkedCategoryIds) {
MCRObjectInfoEntity infoEntity = new MCRObjectInfoEntity();
infoEntity.setId(MCRObjectID.getInstance(id));
infoEntity.setCreateDate(createdDate);
infoEntity.setModifyDate(modifiedDate);
infoEntity.setCreatedBy(createdBy);
infoEntity.setModifiedBy(modifiedBy);
infoEntity.setState(state);
List<MCRCategoryID> linkedCategories = linkedCategoryIds.stream().map(MCRCategoryID::fromString)
.collect(Collectors.toList());
MCRCategLinkReference objectReference = new MCRCategLinkReference(infoEntity.getId());
CLS.setLinks(objectReference, linkedCategories);
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.persist(infoEntity);
return infoEntity;
}
@Test
public void sortByIdTest() {
MCRObjectQuery query = new MCRObjectQuery();
query.sort(MCRObjectQuery.SortBy.id, MCRObjectQuery.SortOrder.asc);
List<MCRObjectInfo> result = instance.getInfos(query);
Assert.assertEquals("The first result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
Assert.assertEquals("The second result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(1).getId());
int count = instance.count(query);
Assert.assertEquals("All objects should match", 2, count);
}
@Test
public void createdBeforeTest() {
MCRObjectQuery createdBeforeTwoWeeksAgo = new MCRObjectQuery().createdBefore(TWO_WEEKS_AGO);
List<MCRObjectInfo> result = instance.getInfos(createdBeforeTwoWeeksAgo);
Assert.assertEquals("The only result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(0).getId());
int count = instance.count(createdBeforeTwoWeeksAgo);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void createdAfterTest() {
MCRObjectQuery createdAfterTwoWeeksAgo = new MCRObjectQuery().createdAfter(TWO_WEEKS_AGO);
List<MCRObjectInfo> result = instance.getInfos(createdAfterTwoWeeksAgo);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
int count = instance.count(createdAfterTwoWeeksAgo);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void modifiedBeforeTest() {
MCRObjectQuery modifiedBeforeOneWeekAgo = new MCRObjectQuery().modifiedBefore(ONE_WEEK_AGO);
List<MCRObjectInfo> result = instance.getInfos(modifiedBeforeOneWeekAgo);
Assert.assertEquals("The only result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(0).getId());
int count = instance.count(modifiedBeforeOneWeekAgo);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void modifiedAfterTest() {
MCRObjectQuery modifiedAfterOneWeekAgo = new MCRObjectQuery().modifiedAfter(ONE_WEEK_AGO);
List<MCRObjectInfo> result = instance.getInfos(modifiedAfterOneWeekAgo);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
int count = instance.count(modifiedAfterOneWeekAgo);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void createdByTest() {
MCRObjectQuery createdByTestUser1 = new MCRObjectQuery().createdBy(TEST_USER_1);
List<MCRObjectInfo> result = instance.getInfos(createdByTestUser1);
Assert.assertEquals("The only result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(0).getId());
int count = instance.count(createdByTestUser1);
Assert.assertEquals("Only one object should match", 1, count);
MCRObjectQuery createdByTestUser2 = new MCRObjectQuery().createdBy(TEST_USER_2);
result = instance.getInfos(createdByTestUser2);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
count = instance.count(createdByTestUser2);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void objectNumberTest() {
MCRObjectQuery numberGreaterTestID1 = new MCRObjectQuery().numberGreater(MCRObjectID.getInstance(TEST_ID_1)
.getNumberAsInteger());
List<MCRObjectInfo> result = instance.getInfos(numberGreaterTestID1);
Assert.assertEquals("The only result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(0).getId());
int count = instance.count(numberGreaterTestID1);
Assert.assertEquals("Only one object should match", 1, count);
MCRObjectQuery numberLessTestID2 = new MCRObjectQuery().numberLess(MCRObjectID.getInstance(TEST_ID_2)
.getNumberAsInteger());
result = instance.getInfos(numberLessTestID2);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
count = instance.count(numberLessTestID2);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void objectTypeTest() {
MCRObjectQuery typeTest = new MCRObjectQuery().type(MCRObjectID.getInstance(TEST_ID_1).getTypeId());
List<MCRObjectInfo> result = instance.getInfos(typeTest);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
int count = instance.count(typeTest);
Assert.assertEquals("Only one object should match", 1, count);
MCRObjectQuery typeFoo = new MCRObjectQuery().type(MCRObjectID.getInstance(TEST_ID_2).getTypeId());
result = instance.getInfos(typeFoo);
Assert.assertEquals("The only result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(0).getId());
count = instance.count(typeFoo);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void stateTest() {
MCRObjectQuery state1 = new MCRObjectQuery().status(TEST_STATE_1);
List<MCRObjectInfo> result = instance.getInfos(state1);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
int count = instance.count(state1);
Assert.assertEquals("Only one object should match", 1, count);
MCRObjectQuery state2 = new MCRObjectQuery().status(TEST_STATE_2);
result = instance.getInfos(state2);
Assert.assertEquals("The only result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(0).getId());
count = instance.count(state2);
Assert.assertEquals("Only one object should match", 1, count);
}
@Test
public void categoryTest() {
MCRObjectQuery category1 = new MCRObjectQuery();
category1.getIncludeCategories().add(TEST_CATEGORY_1);
List<MCRObjectInfo> result = instance.getInfos(category1);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
int count = instance.count(category1);
Assert.assertEquals("Only one object should match", 1, count);
MCRObjectQuery category2 = new MCRObjectQuery();
category2.getIncludeCategories().add(TEST_CATEGORY_2);
result = instance.getInfos(category2);
Assert.assertEquals("The only result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(0).getId());
count = instance.count(category2);
Assert.assertEquals("Only one object should match", 1, count);
MCRObjectQuery category3 = new MCRObjectQuery().sort(MCRObjectQuery.SortBy.id, MCRObjectQuery.SortOrder.asc);
category3.getIncludeCategories().add(TEST_CATEGORY_3);
result = instance.getInfos(category3);
Assert.assertEquals("The first result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
Assert.assertEquals("The second result should be " + TEST_ID_2, MCRObjectID.getInstance(TEST_ID_2),
result.get(1).getId());
count = instance.count(category3);
Assert.assertEquals("both object should match", 2, count);
MCRObjectQuery category1and3 = new MCRObjectQuery().sort(MCRObjectQuery.SortBy.id,
MCRObjectQuery.SortOrder.asc);
category1and3.getIncludeCategories().add(TEST_CATEGORY_1);
category1and3.getIncludeCategories().add(TEST_CATEGORY_3);
result = instance.getInfos(category1and3);
Assert.assertEquals("The only result should be " + TEST_ID_1, MCRObjectID.getInstance(TEST_ID_1),
result.get(0).getId());
count = instance.count(category1and3);
Assert.assertEquals("Only one object should match", 1, count);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Object.QueryResolver.Class", MCRObjectInfoEntityQueryResolver.class.getName());
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
testProperties.put("MCR.Metadata.Type.foo", Boolean.TRUE.toString());
return testProperties;
}
}
| 14,431 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIFS2VersioningTestCase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRIFS2VersioningTestCase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.net.MalformedURLException;
import java.util.Map;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
public class MCRIFS2VersioningTestCase extends MCRIFS2TestCase {
@Rule
public TemporaryFolder versionBaseDir = new TemporaryFolder();
private MCRVersioningMetadataStore versStore;
@Override
protected void createStore() throws Exception {
setVersStore(MCRStoreManager.createStore(STORE_ID, MCRVersioningMetadataStore.class));
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
System.out.println("teardown: " + getVersStore().repURL);
MCRStoreManager.removeStore(STORE_ID);
versionBaseDir.delete();
}
public void setVersStore(MCRVersioningMetadataStore versStore) {
this.versStore = versStore;
}
public MCRVersioningMetadataStore getVersStore() {
return versStore;
}
@Override
public MCRStore getGenericStore() {
return getVersStore();
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
try {
String url = versionBaseDir.getRoot().toURI().toURL().toString();
testProperties.put("MCR.IFS2.Store.TEST.SVNRepositoryURL", url);
} catch (MalformedURLException e) {
Assert.fail(e.getMessage());
}
return testProperties;
}
}
| 2,287 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIFS2MetadataTestCase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRIFS2MetadataTestCase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 MCRIFS2MetadataTestCase extends MCRIFS2TestCase {
private MCRMetadataStore metaDataStore;
protected void createStore() throws Exception {
setMetaDataStore(MCRStoreManager.createStore(STORE_ID, MCRMetadataStore.class));
}
public void setMetaDataStore(MCRMetadataStore metaDataStore) {
this.metaDataStore = metaDataStore;
}
public MCRMetadataStore getMetaDataStore() {
return metaDataStore;
}
@Override
public MCRStore getGenericStore() {
return getMetaDataStore();
}
}
| 1,320 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIFS2TestCase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRIFS2TestCase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertNull;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.mycore.common.MCRTestCase;
public class MCRIFS2TestCase extends MCRTestCase {
protected static final String STORE_ID = "TEST";
@Rule
public TemporaryFolder storeBaseDir = new TemporaryFolder();
private MCRFileStore store;
protected void createStore() throws Exception {
System.out.println(getClass() + " store id: " + STORE_ID);
setStore(MCRStoreManager.createStore(STORE_ID, MCRFileStore.class));
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
createStore();
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
MCRStoreManager.removeStore(STORE_ID);
assertNull("Could not remove store " + STORE_ID, MCRStoreManager.getStore(STORE_ID));
store = null;
}
public void setStore(MCRFileStore store) {
this.store = store;
}
public MCRFileStore getStore() {
return store;
}
public MCRStore getGenericStore() {
return getStore();
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.IFS2.Store.TEST.BaseDir", storeBaseDir.getRoot().getAbsolutePath());
testProperties.put("MCR.IFS2.Store.TEST.SlotLayout", "4-2-2");
return testProperties;
}
}
| 2,363 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDirectoryTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRDirectoryTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import org.junit.Test;
import org.mycore.common.MCRSessionMgr;
/**
* JUnit test for MCRDirectory
*
* @author Frank LΓΌtzenkirchen
*/
public class MCRDirectoryTest extends MCRIFS2TestCase {
private MCRFileCollection col;
@Override
public void setUp() throws Exception {
super.setUp();
col = getStore().create();
}
@Test
public void name() throws Exception {
MCRDirectory dir = col.createDir("foo");
Date created = dir.getLastModified();
assertEquals("foo", dir.getName());
synchronized (this) {
wait(1000);
}
dir.renameTo("bar");
assertEquals("bar", dir.getName());
assertTrue(dir.getLastModified().after(created));
}
@SuppressWarnings("deprecation")
@Test
public void setLastModified() throws Exception {
MCRDirectory dir = col.createDir("foo");
Date other = new Date(109, 1, 1);
dir.setLastModified(other);
assertEquals(other, dir.getLastModified());
}
@Test
public void type() throws Exception {
MCRDirectory dir = col.createDir("foo");
assertFalse(dir.isFile());
assertTrue(dir.isDirectory());
}
@Test
public void labels() throws Exception {
MCRDirectory dir = col.createDir("foo");
assertTrue(dir.getLabels().isEmpty());
assertNull(dir.getCurrentLabel());
dir.setLabel("de", "deutsch");
dir.setLabel("en", "english");
String curr = MCRSessionMgr.getCurrentSession().getCurrentLanguage();
String label = dir.getLabel(curr);
assertEquals(label, dir.getCurrentLabel());
assertEquals(2, dir.getLabels().size());
assertEquals("english", dir.getLabel("en"));
MCRFileCollection col2 = getStore().retrieve(col.getID());
MCRDirectory child = (MCRDirectory) col2.getChild("foo");
assertEquals(2, child.getLabels().size());
dir.clearLabels();
assertTrue(dir.getLabels().isEmpty());
}
@Test
public void getSize() throws Exception {
MCRDirectory dir = col.createDir("foo");
assertEquals(0, dir.getSize());
}
@Test
public void children() throws Exception {
MCRDirectory parent = col.createDir("foo");
assertFalse(parent.hasChildren());
assertEquals(0, parent.getNumChildren());
assertNotNull(parent.getChildren());
assertEquals(0, parent.getChildren().count());
assertNull(parent.getChild("bar"));
parent.createDir("bar");
assertTrue(parent.hasChildren());
assertEquals(1, parent.getNumChildren());
assertNotNull(parent.getChildren());
assertEquals(1, parent.getChildren().count());
assertNotNull(parent.getChild("bar"));
MCRNode fromList = parent.getChildren().findFirst().get();
assertTrue(fromList instanceof MCRDirectory);
assertEquals("bar", fromList.getName());
parent.createFile("readme.txt");
assertTrue(parent.hasChildren());
assertEquals(2, parent.getNumChildren());
assertNotNull(parent.getChildren());
assertEquals(2, parent.getChildren().count());
assertNotNull(parent.getChild("bar"));
assertNotNull(parent.getChild("readme.txt"));
MCRNode[] children = parent.getChildren().toArray(MCRNode[]::new);
assertFalse(children[0].getName().equals(children[1].getName()));
assertTrue("bar readme.txt".contains(children[0].getName()));
assertTrue("bar readme.txt".contains(children[1].getName()));
}
@Test
public void path() throws Exception {
assertEquals("/", col.getPath());
MCRDirectory parent = col.createDir("dir");
assertEquals("/dir", parent.getPath());
MCRDirectory child = parent.createDir("subdir");
assertEquals("/dir/subdir", child.getPath());
MCRFile file = child.createFile("readme.txt");
assertEquals("/dir/subdir/readme.txt", file.getPath());
}
@Test
public void navigationUpwards() throws Exception {
assertEquals(col, col.getRoot());
assertNull(col.getParent());
MCRDirectory dir = col.createDir("dir");
assertEquals(col, dir.getRoot());
assertEquals(col, dir.getParent());
MCRDirectory subdir = dir.createDir("subdir");
assertEquals(col, subdir.getRoot());
assertEquals(dir, subdir.getParent());
MCRFile file = subdir.createFile("readme.txt");
assertEquals(col, file.getRoot());
assertEquals(subdir, file.getParent());
}
@Test
public void getNodeByPath() throws Exception {
MCRNode node = col.getNodeByPath("/");
assertSame(node, col);
node = col.getNodeByPath(".");
assertNotNull(node);
assertSame(node, col);
MCRDirectory dir = col.createDir("dir");
node = col.getNodeByPath("dir");
assertNotNull(node);
assertEquals("dir", node.getName());
node = col.getNodeByPath("./dir");
assertNotNull(node);
assertEquals("dir", node.getName());
node = dir.getNodeByPath("..");
assertNotNull(node);
assertSame(node, col);
MCRDirectory subdir = dir.createDir("subdir");
node = subdir.getNodeByPath("/");
assertNotNull(node);
assertSame(node, col);
node = subdir.getNodeByPath("../subdir");
assertNotNull(node);
assertEquals("subdir", node.getName());
node = subdir.getNodeByPath("../..");
assertNotNull(node);
assertSame(node, col);
node = col.getNodeByPath("./dir/subdir");
assertNotNull(node);
assertEquals("subdir", node.getName());
}
@Test
public void delete() throws Exception {
MCRDirectory dir = col.createDir("dir");
MCRDirectory subdir = dir.createDir("subdir");
subdir.createFile("readme.txt");
dir.delete();
assertEquals(0, col.getNumChildren());
assertFalse(col.hasChildren());
}
}
| 7,119 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRVersioningMetadataStoreTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRVersioningMetadataStoreTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.PrintWriter;
import java.net.URI;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUsageException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
/**
* JUnit test for MCRVersioningMetadataStore
*
* @author Frank LΓΌtzenkirchen
*/
public class MCRVersioningMetadataStoreTest extends MCRIFS2VersioningTestCase {
@Test
public void createDocument() throws Exception {
Document testXmlDoc = new Document(new Element("root"));
MCRContent testContent = new MCRJDOMContent(testXmlDoc);
MCRVersionedMetadata versionedMetadata = getVersStore().create(testContent);
MCRContent contentFromStore = getVersStore().retrieve(versionedMetadata.getID()).getMetadata();
String contentStrFromStore = contentFromStore.asString();
MCRContent mcrContent = new MCRJDOMContent(testXmlDoc);
String expectedContentStr = mcrContent.asString();
assertNotNull(versionedMetadata);
assertEquals(expectedContentStr, contentStrFromStore);
assertTrue(versionedMetadata.getID() > 0);
assertTrue(versionedMetadata.getRevision() > 0);
MCRVersionedMetadata vm3 = getVersStore().create(new MCRJDOMContent(testXmlDoc));
assertTrue(vm3.getID() > versionedMetadata.getID());
assertTrue(vm3.getRevision() > versionedMetadata.getRevision());
}
@Test
public void createDocumentInt() throws Exception {
int id = getVersStore().getNextFreeID();
assertTrue(id > 0);
Document xml1 = new Document(new Element("root"));
MCRVersionedMetadata vm1 = getVersStore().create(new MCRJDOMContent(xml1), id);
MCRContent xml2 = getVersStore().retrieve(id).getMetadata();
assertNotNull(vm1);
assertEquals(new MCRJDOMContent(xml1).asString(), xml2.asString());
getVersStore().create(new MCRJDOMContent(xml1), id + 1);
MCRContent xml3 = getVersStore().retrieve(id + 1).getMetadata();
assertEquals(new MCRJDOMContent(xml1).asString(), xml3.asString());
}
@Test
public void delete() throws Exception {
System.out.println("TEST DELETE");
Document xml1 = new Document(new Element("root"));
int id = getVersStore().create(new MCRJDOMContent(xml1)).getID();
assertTrue(getVersStore().exists(id));
getVersStore().delete(id);
assertFalse(getVersStore().exists(id));
}
@Test
public void update() throws Exception {
Document xml1 = new Document(new Element("root"));
MCRVersionedMetadata vm = getVersStore().create(new MCRJDOMContent(xml1));
Document xml3 = new Document(new Element("update"));
long rev = vm.getRevision();
vm.update(new MCRJDOMContent(xml3));
assertTrue(vm.getRevision() > rev);
MCRContent xml4 = getVersStore().retrieve(vm.getID()).getMetadata();
assertEquals(new MCRJDOMContent(xml3).asString(), xml4.asString());
}
@Test
public void retrieve() throws Exception {
Document xml1 = new Document(new Element("root"));
int id = getVersStore().create(new MCRJDOMContent(xml1)).getID();
MCRVersionedMetadata sm1 = getVersStore().retrieve(id);
MCRContent xml2 = sm1.getMetadata();
assertEquals(new MCRJDOMContent(xml1).asString(), xml2.asString());
}
@Test
public void versioning() throws Exception {
Document xml1 = new Document(new Element("bingo"));
MCRVersionedMetadata vm = getVersStore().create(new MCRJDOMContent(xml1));
long baseRev = vm.getRevision();
assertTrue(vm.isUpToDate());
List<MCRMetadataVersion> versions = vm.listVersions();
assertNotNull(versions);
assertEquals(1, versions.size());
MCRMetadataVersion mv = versions.get(0);
assertSame(mv.getMetadataObject(), vm);
assertEquals(baseRev, Long.parseLong(mv.getRevision()));
assertEquals(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(), mv.getUser());
assertEquals(MCRMetadataVersion.CREATED, mv.getType());
bzzz();
Document xml2 = new Document(new Element("bango"));
vm.update(new MCRJDOMContent(xml2));
assertTrue(vm.getRevision() > baseRev);
assertTrue(vm.isUpToDate());
versions = vm.listVersions();
assertEquals(2, versions.size());
mv = versions.get(0);
assertEquals(baseRev, Long.parseLong(mv.getRevision()));
mv = versions.get(1);
assertEquals(vm.getRevision(), Long.parseLong(mv.getRevision()));
assertEquals(MCRMetadataVersion.UPDATED, mv.getType());
bzzz();
Document xml3 = new Document(new Element("bongo"));
vm.update(new MCRJDOMContent(xml3));
versions = vm.listVersions();
assertEquals(3, versions.size());
mv = versions.get(0);
assertEquals(baseRev, Long.parseLong(mv.getRevision()));
mv = versions.get(2);
assertEquals(vm.getRevision(), Long.parseLong(mv.getRevision()));
assertTrue(Long.parseLong(versions.get(0).getRevision()) < Long.parseLong(versions.get(1).getRevision()));
assertTrue(Long.parseLong(versions.get(1).getRevision()) < Long.parseLong(versions.get(2).getRevision()));
assertTrue(versions.get(0).getDate().before(versions.get(1).getDate()));
assertTrue(versions.get(1).getDate().before(versions.get(2).getDate()));
xml1 = versions.get(0).retrieve().asXML();
assertNotNull(xml1);
assertEquals("bingo", xml1.getRootElement().getName());
xml2 = versions.get(1).retrieve().asXML();
assertNotNull(xml2);
assertEquals("bango", xml2.getRootElement().getName());
xml3 = versions.get(2).retrieve().asXML();
assertNotNull(xml1);
assertEquals("bongo", xml3.getRootElement().getName());
bzzz();
versions.get(1).restore();
assertTrue(vm.getRevision() > Long.parseLong(versions.get(2).getRevision()));
assertTrue(vm.getLastModified().after(versions.get(2).getDate()));
assertEquals("bango", vm.getMetadata().asXML().getRootElement().getName());
assertEquals(4, vm.listVersions().size());
}
@Test
public void createUpdateDeleteCreate() throws Exception {
Element root = new Element("bingo");
Document xml1 = new Document(root);
MCRVersionedMetadata vm = getVersStore().create(new MCRJDOMContent(xml1));
root.setName("bango");
vm.update(new MCRJDOMContent(xml1));
vm.delete();
root.setName("bongo");
vm = getVersStore().create(new MCRJDOMContent(xml1), vm.getID());
List<MCRMetadataVersion> versions = vm.listVersions();
assertEquals(4, versions.size());
assertEquals(MCRMetadataVersion.CREATED, versions.get(0).getType());
assertEquals(MCRMetadataVersion.UPDATED, versions.get(1).getType());
assertEquals(MCRMetadataVersion.DELETED, versions.get(2).getType());
assertEquals(MCRMetadataVersion.CREATED, versions.get(3).getType());
versions.get(1).restore();
assertEquals("bango", vm.getMetadata().asXML().getRootElement().getName());
}
@Test
public void deletedVersions() throws Exception {
Element root = new Element("bingo");
Document xml1 = new Document(root);
MCRVersionedMetadata vm = getVersStore().create(new MCRJDOMContent(xml1));
assertFalse(vm.isDeleted());
vm.delete();
assertTrue(vm.isDeleted());
assertFalse(getVersStore().exists(vm.getID()));
vm = getVersStore().retrieve(vm.getID());
assertTrue(vm.isDeletedInRepository());
List<MCRMetadataVersion> versions = vm.listVersions();
MCRMetadataVersion v1 = versions.get(0);
MCRMetadataVersion v2 = versions.get(1);
boolean cannotRestoreDeleted = false;
try {
v2.restore();
} catch (MCRUsageException ex) {
cannotRestoreDeleted = true;
}
assertTrue(cannotRestoreDeleted);
v1.restore();
assertFalse(vm.isDeletedInRepository());
assertEquals(root.getName(), vm.getMetadata().asXML().getRootElement().getName());
}
@Test
public void verifyRevPropsFail() throws Exception {
getVersStore().verify();
deletedVersions();
getVersStore().verify();
File baseDIR = new File(URI.create(getVersStore().repURL.toString()));
File revProp = new File(baseDIR.toURI().resolve("db/revprops/0/2"));
assertTrue("is not a file " + revProp, revProp.isFile());
revProp.setWritable(true);
new PrintWriter(revProp).close();
revProp.setWritable(false);
try {
getVersStore().verify();
} catch (MCRPersistenceException e) {
return;
}
fail("Verify finished without error");
}
@Test
public void verifyRevFail() throws Exception {
getVersStore().verify();
deletedVersions();
getVersStore().verify();
File baseDIR = new File(URI.create(getVersStore().repURL.toString()));
File revProp = new File(baseDIR.toURI().resolve("db/revs/0/2"));
assertTrue("is not a file " + revProp, revProp.isFile());
new PrintWriter(revProp).close();
try {
getVersStore().verify();
} catch (MCRPersistenceException e) {
return;
}
fail("Verify finished without error");
}
}
| 10,758 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataStoreTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRMetadataStoreTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
/**
* JUnit test for MCRMetadataStore
*
* @author Frank LΓΌtzenkirchen
*/
public class MCRMetadataStoreTest extends MCRIFS2MetadataTestCase {
@Test
public void createDocument() throws Exception {
Document xml1 = new Document(new Element("root"));
MCRStoredMetadata sm = getMetaDataStore().create(new MCRJDOMContent(xml1));
assertNotNull(sm);
int id1 = sm.getID();
assertTrue(id1 > 0);
MCRStoredMetadata sm2 = getMetaDataStore().retrieve(id1);
MCRContent xml2 = sm2.getMetadata();
assertEquals(new MCRJDOMContent(xml1).asString(), xml2.asString());
int id2 = getMetaDataStore().create(new MCRJDOMContent(xml1)).getID();
assertTrue(id2 > id1);
}
@Test
public void isEmpty() throws Exception {
assertTrue(getMetaDataStore().isEmpty());
Document xml1 = new Document(new Element("root"));
MCRStoredMetadata sm = getMetaDataStore().create(new MCRJDOMContent(xml1));
assertFalse(getMetaDataStore().isEmpty());
getMetaDataStore().delete(sm.id);
assertTrue(getMetaDataStore().isEmpty());
}
@Test
public void createDocumentInt() throws Exception {
Document xml1 = new Document(new Element("root"));
try {
getMetaDataStore().create(new MCRJDOMContent(xml1), 0);
fail("metadata store allows to save with id \"0\".");
} catch (Exception e) {
//test passed
}
int id = getMetaDataStore().getNextFreeID();
assertTrue(id > 0);
MCRStoredMetadata sm1 = getMetaDataStore().create(new MCRJDOMContent(xml1), id);
assertNotNull(sm1);
MCRContent xml2 = getMetaDataStore().retrieve(id).getMetadata();
assertEquals(new MCRJDOMContent(xml1).asString(), xml2.asString());
getMetaDataStore().create(new MCRJDOMContent(xml1), id + 1);
MCRContent xml3 = getMetaDataStore().retrieve(id + 1).getMetadata();
assertEquals(new MCRJDOMContent(xml1).asString(), xml3.asString());
}
@Test
public void delete() throws Exception {
Document xml1 = new Document(new Element("root"));
int id = getMetaDataStore().create(new MCRJDOMContent(xml1)).getID();
assertTrue(getMetaDataStore().exists(id));
getMetaDataStore().delete(id);
assertFalse(getMetaDataStore().exists(id));
assertNull(getMetaDataStore().retrieve(id));
}
@Test
public void update() throws Exception {
Document xml1 = new Document(new Element("root"));
MCRStoredMetadata sm = getMetaDataStore().create(new MCRJDOMContent(xml1));
Document xml2 = new Document(new Element("update"));
sm.update(new MCRJDOMContent(xml2));
MCRContent xml3 = getMetaDataStore().retrieve(sm.getID()).getMetadata();
assertEquals(new MCRJDOMContent(xml2).asString(), xml3.asString());
}
@Test
public void retrieve() throws Exception {
Document xml1 = new Document(new Element("root"));
int id = getMetaDataStore().create(new MCRJDOMContent(xml1)).getID();
MCRStoredMetadata sm1 = getMetaDataStore().retrieve(id);
MCRContent xml2 = sm1.getMetadata();
assertEquals(new MCRJDOMContent(xml1).asString(), xml2.asString());
}
@Test
public void lastModified() throws Exception {
Document xml1 = new Document(new Element("root"));
Date date1 = new Date();
synchronized (this) {
wait(1000);
}
MCRStoredMetadata sm = getMetaDataStore().create(new MCRJDOMContent(xml1));
Date date2 = sm.getLastModified();
assertTrue(date2.after(date1));
synchronized (this) {
wait(1000);
}
Document xml2 = new Document(new Element("root"));
sm.update(new MCRJDOMContent(xml2));
assertTrue(sm.getLastModified().after(date2));
@SuppressWarnings("deprecation")
Date date = new Date(109, 1, 1);
sm.setLastModified(date);
sm = getMetaDataStore().retrieve(sm.getID());
assertEquals(date, sm.getLastModified());
}
@Test
public void exists() throws Exception {
int id = getMetaDataStore().getNextFreeID();
assertFalse(getMetaDataStore().exists(id));
Document xml1 = new Document(new Element("root"));
getMetaDataStore().create(new MCRJDOMContent(xml1), id);
assertTrue(getMetaDataStore().exists(id));
getMetaDataStore().delete(id);
assertFalse(getMetaDataStore().exists(id));
}
@Test
public void getNextFreeID() throws Exception {
int id1 = getMetaDataStore().getNextFreeID();
assertTrue(id1 >= 0);
assertFalse(getMetaDataStore().exists(id1));
Document xml1 = new Document(new Element("root"));
int id2 = getMetaDataStore().create(new MCRJDOMContent(xml1)).getID();
assertTrue(id2 > id1);
assertTrue(getMetaDataStore().getNextFreeID() > id2);
}
@Test
public void listIDs() throws Exception {
Iterator<Integer> IDs = getMetaDataStore().listIDs(true);
while (IDs.hasNext()) {
getMetaDataStore().delete(IDs.next());
}
assertFalse(getMetaDataStore().exists(1));
assertFalse(getMetaDataStore().listIDs(true).hasNext());
assertFalse(getMetaDataStore().listIDs(false).hasNext());
Document xml1 = new Document(new Element("root"));
getMetaDataStore().create(new MCRJDOMContent(xml1));
getMetaDataStore().create(new MCRJDOMContent(xml1));
getMetaDataStore().create(new MCRJDOMContent(xml1));
ArrayList<Integer> l1 = new ArrayList<>();
IDs = getMetaDataStore().listIDs(true);
while (IDs.hasNext()) {
int id = IDs.next();
if (!l1.isEmpty()) {
assertTrue(id > l1.get(l1.size() - 1));
}
l1.add(id);
}
assertTrue(l1.size() == 3);
ArrayList<Integer> l2 = new ArrayList<>();
IDs = getMetaDataStore().listIDs(false);
while (IDs.hasNext()) {
int id = IDs.next();
if (!l2.isEmpty()) {
assertTrue(id < l2.get(l2.size() - 1));
}
l2.add(id);
}
assertTrue(l2.size() == 3);
Collections.sort(l2);
assertEquals(l1, l2);
}
}
| 7,687 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileStoreTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRFileStoreTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.Test;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.MCRStringContent;
/**
* JUnit test for MCRFileStore
*
* @author Frank LΓΌtzenkirchen
*/
public class MCRFileStoreTest extends MCRIFS2TestCase {
@Test
public void create() throws Exception {
MCRFileCollection col = getStore().create();
assertNotNull(col);
assertTrue(col.getID() > 0);
}
@Test
public void createInt() throws Exception {
int id1 = getStore().getNextFreeID();
MCRFileCollection col1 = getStore().create(id1);
assertNotNull(col1);
assertEquals(id1, col1.getID());
assertTrue(getStore().exists(id1));
MCRFileCollection col2 = getStore().create(id1 + 1);
assertNotNull(col2);
assertEquals(id1 + 1, col2.getID());
assertTrue(getStore().exists(id1 + 1));
}
@Test
public void delete() throws Exception {
MCRFileCollection col = getStore().create();
assertTrue(getStore().exists(col.getID()));
getStore().delete(col.getID());
assertFalse(getStore().exists(col.getID()));
MCRFileCollection col2 = getStore().retrieve(col.getID());
assertNull(col2);
MCRFileCollection col3 = getStore().create();
col3.delete();
assertFalse(getStore().exists(col3.getID()));
}
@Test
public void retrieve() throws Exception {
MCRFileCollection col1 = getStore().create();
MCRFileCollection col2 = getStore().retrieve(col1.getID());
assertNotNull(col2);
assertEquals(col1.getID(), col2.getID());
assertEquals(col1.getLastModified(), col2.getLastModified());
MCRFileCollection col3 = getStore().retrieve(col1.getID() + 1);
assertNull(col3);
}
@Test
public void exists() throws Exception {
int id = getStore().getNextFreeID();
assertFalse(getStore().exists(id));
getStore().create(id);
assertTrue(getStore().exists(id));
}
@Test
public void getNextFreeID() throws Exception {
int id1 = getStore().getNextFreeID();
assertTrue(id1 >= 0);
assertFalse(getStore().exists(id1));
int id2 = getStore().create().getID();
assertTrue(id2 > id1);
int id3 = getStore().getNextFreeID();
assertTrue(id3 > id2);
}
@Test
public void listIDs() throws Exception {
Iterator<Integer> IDs = getStore().listIDs(true);
while (IDs.hasNext()) {
getStore().delete(IDs.next());
}
assertFalse(getStore().exists(1));
assertFalse(getStore().listIDs(true).hasNext());
assertFalse(getStore().listIDs(false).hasNext());
int expectedNumOfFileCollections = 3;
createFileCollection(expectedNumOfFileCollections);
ArrayList<Integer> l1 = new ArrayList<>();
IDs = getStore().listIDs(true);
assertTrue("IDs iterator has no next element? ", IDs.hasNext());
while (IDs.hasNext()) {
int id = IDs.next();
if (!l1.isEmpty()) {
assertTrue(id > l1.get(l1.size() - 1));
}
l1.add(id);
}
assertEquals("ID list size", expectedNumOfFileCollections, l1.size());
ArrayList<Integer> l2 = new ArrayList<>();
IDs = getStore().listIDs(false);
while (IDs.hasNext()) {
int id = IDs.next();
if (!l2.isEmpty()) {
assertTrue(id < l2.get(l2.size() - 1));
}
l2.add(id);
}
assertTrue(l2.size() == 3);
Collections.sort(l2);
assertEquals(l1, l2);
}
private void createFileCollection(int numOfCollections) throws Exception {
for (int i = 0; i < numOfCollections; i++) {
MCRFileCollection fileCollection = getStore().create();
int collectionID = fileCollection.getID();
assertTrue("File collection with ID " + collectionID + " does not exists.",
getStore().exists(collectionID));
}
}
@Test
public void basicFunctionality() throws Exception {
Date first = new Date();
synchronized (this) {
wait(1000);
}
MCRFileCollection col = getStore().create();
assertNotNull(col);
assertTrue(col.getID() > 0);
Date created = col.getLastModified();
assertFalse(first.after(created));
bzzz();
MCRFile build = col.createFile("build.xml");
assertNotNull(build);
Date modified = col.getLastModified();
assertTrue(modified.after(created));
assertEquals(1, col.getNumChildren());
assertEquals(1, col.getChildren().count());
assertEquals(0, build.getSize());
assertTrue(created.before(build.getLastModified()));
build.setContent(new MCRJDOMContent(new Element("project")));
assertTrue(build.getSize() > 0);
assertNotNull(build.getContent().asByteArray());
bzzz();
MCRDirectory dir = col.createDir("documentation");
assertEquals(2, col.getNumChildren());
assertTrue(modified.before(col.getLastModified()));
byte[] content = "Hello World!".getBytes(StandardCharsets.UTF_8);
dir.createFile("readme.txt").setContent(new MCRByteContent(content, System.currentTimeMillis()));
MCRFile child = (MCRFile) dir.getChild("readme.txt");
assertNotNull(child);
assertEquals(content.length, child.getSize());
}
@Test
public void labels() throws Exception {
MCRFileCollection col = getStore().create();
assertTrue(col.getLabels().isEmpty());
assertNull(col.getCurrentLabel());
col.setLabel("de", "deutsch");
col.setLabel("en", "english");
String curr = MCRSessionMgr.getCurrentSession().getCurrentLanguage();
String label = col.getLabel(curr);
assertEquals(label, col.getCurrentLabel());
assertEquals(2, col.getLabels().size());
assertEquals("english", col.getLabel("en"));
MCRFileCollection col2 = getStore().retrieve(col.getID());
assertEquals(2, col2.getLabels().size());
col.clearLabels();
assertTrue(col.getLabels().isEmpty());
}
@Test
public void repairMetadata() throws Exception {
MCRFileCollection col = getStore().create();
Document xml1 = col.getMetadata().clone();
col.repairMetadata();
Document xml2 = col.getMetadata().clone();
xml1 = col.getMetadata().clone();
assertTrue(equals(xml1, xml2));
MCRDirectory dir = col.createDir("foo");
xml1 = col.getMetadata().clone();
assertFalse(equals(xml1, xml2));
dir.delete();
xml1 = col.getMetadata().clone();
assertTrue(equals(xml1, xml2));
MCRDirectory dir2 = col.createDir("dir");
MCRFile file1 = col.createFile("test1.txt");
file1.setContent(new MCRStringContent("Test 1"));
MCRFile readme = dir2.createFile("readme.txt");
readme.setContent(new MCRStringContent("Hallo Welt!"));
MCRFile file3 = col.createFile("test2.txt");
file3.setContent(new MCRStringContent("Test 2"));
file3.setLabel("de", "Die Testdatei");
xml2 = col.getMetadata().clone();
col.repairMetadata();
xml1 = col.getMetadata().clone();
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(xml1, System.out);
xout.output(xml2, System.out);
assertTrue(equals(xml1, xml2));
file3.clearLabels();
xml2 = col.getMetadata().clone();
Files.delete(col.path.resolve("mcrdata.xml"));
col = getStore().retrieve(col.getID());
xml1 = col.getMetadata().clone();
assertTrue(equals(xml1, xml2));
Files.delete(col.path.resolve("test1.txt"));
Path tmp = col.path.resolve("test3.txt");
new MCRStringContent("Hallo Welt!").sendTo(tmp);
col.repairMetadata();
String xml3 = new MCRJDOMContent(col.getMetadata()).asString();
assertFalse(xml3.contains("name=\"test1.txt\""));
assertTrue(xml3.contains("name=\"test3.txt\""));
}
private boolean equals(Document a, Document b) throws Exception {
sortChildren(a.getRootElement());
sortChildren(b.getRootElement());
String sa = new MCRJDOMContent(a).asString();
String sb = new MCRJDOMContent(b).asString();
return sa.equals(sb);
}
private void sortChildren(Element parent) {
@SuppressWarnings("unchecked")
List<Element> children = parent.getChildren();
if (children == null || children.size() == 0) {
return;
}
ArrayList<Element> copy = new ArrayList<>();
copy.addAll(children);
copy.sort((a, b) -> {
String sa = a.getName() + "/" + a.getAttributeValue("name");
String sb = b.getName() + "/" + b.getAttributeValue("name");
return sa.compareTo(sb);
});
parent.removeContent();
parent.addContent(copy);
for (Element child : copy) {
sortChildren(child);
}
}
}
| 10,669 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/MCRFileTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import org.apache.commons.io.IOUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRFileContent;
import org.mycore.common.content.MCRJDOMContent;
/**
* JUnit test for MCRFile
*
* @author Frank LΓΌtzenkirchen
*/
public class MCRFileTest extends MCRIFS2TestCase {
private MCRFileCollection col;
@Override
public void setUp() throws Exception {
super.setUp();
col = getStore().create();
}
@Test
public void fileName() throws Exception {
MCRFile file = col.createFile("foo.txt");
Date created = file.getLastModified();
assertEquals("foo.txt", file.getName());
assertEquals("txt", file.getExtension());
bzzz();
file.renameTo("readme");
assertEquals("readme", file.getName());
assertEquals("", file.getExtension());
assertTrue(file.getLastModified() + " is not after " + created, file.getLastModified().after(created));
}
@SuppressWarnings("deprecation")
@Test
public void setLastModified() throws Exception {
MCRFile file = col.createFile("foo.txt");
Date other = new Date(109, 1, 1);
file.setLastModified(other);
assertEquals(other, file.getLastModified());
}
@Test
public void getMD5() throws Exception {
MCRFile file = col.createFile("foo.txt");
assertEquals(MCRFile.MD5_OF_EMPTY_FILE, file.getMD5());
byte[] content = "Hello World".getBytes(StandardCharsets.UTF_8);
file.setContent(new MCRByteContent(content, System.currentTimeMillis()));
assertFalse(MCRFile.MD5_OF_EMPTY_FILE.equals(file.getMD5()));
MCRFileCollection col2 = getStore().retrieve(col.getID());
MCRFile child = (MCRFile) col2.getChild("foo.txt");
assertEquals(file.getMD5(), child.getMD5());
}
@Test
public void delete() throws Exception {
MCRFile file = col.createFile("foo.txt");
file.delete();
assertNull(col.getChild("foo.txt"));
}
@Test
public void children() throws Exception {
MCRFile file = col.createFile("foo.txt");
assertNull(file.getChild("foo"));
assertEquals(0, file.getChildren().count());
assertFalse(file.hasChildren());
assertEquals(0, file.getNumChildren());
}
@Test
public void contentFile() throws Exception {
MCRFile file = col.createFile("foo.txt");
File src = File.createTempFile("foo", "txt");
src.deleteOnExit();
byte[] content = "Hello World".getBytes(StandardCharsets.UTF_8);
try (FileOutputStream fo = new FileOutputStream(src)) {
IOUtils.copy(new ByteArrayInputStream(content), fo);
}
file.setContent(new MCRFileContent(src));
assertFalse(MCRFile.MD5_OF_EMPTY_FILE.equals(file.getMD5()));
assertEquals(11, file.getSize());
file.getContent().sendTo(src);
assertEquals(11, src.length());
}
@Test
public void contentXML() throws Exception {
MCRFile file = col.createFile("foo.xml");
Document xml = new Document(new Element("root"));
file.setContent(new MCRJDOMContent(xml));
assertFalse(MCRFile.MD5_OF_EMPTY_FILE.equals(file.getMD5()));
Document xml2 = file.getContent().asXML();
assertEquals("root", xml2.getRootElement().getName());
}
@Test
public void randomAccessContent() throws Exception {
MCRFile file = col.createFile("foo.txt");
byte[] content = "Hello World".getBytes(StandardCharsets.UTF_8);
file.setContent(new MCRByteContent(content, System.currentTimeMillis()));
try (SeekableByteChannel rac = file.getRandomAccessContent()) {
rac.position(6);
ByteBuffer dst = ByteBuffer.allocate(Character.BYTES);
rac.read(dst);
char c = new String(dst.array(), StandardCharsets.UTF_8).charAt(0);
assertEquals('W', c);
}
}
@Test
public void type() throws Exception {
MCRFile file = col.createFile("foo.txt");
assertTrue(file.isFile());
assertFalse(file.isDirectory());
}
@Test
public void labels() throws Exception {
MCRFile file = col.createFile("foo.txt");
assertTrue(file.getLabels().isEmpty());
assertNull(file.getCurrentLabel());
file.setLabel("de", "deutsch");
file.setLabel("en", "english");
String curr = MCRSessionMgr.getCurrentSession().getCurrentLanguage();
String label = file.getLabel(curr);
assertEquals(label, file.getCurrentLabel());
assertEquals(2, file.getLabels().size());
assertEquals("english", file.getLabel("en"));
MCRFileCollection col2 = getStore().retrieve(col.getID());
MCRFile child = (MCRFile) col2.getChild("foo.txt");
assertEquals(2, child.getLabels().size());
file.clearLabels();
assertTrue(file.getLabels().isEmpty());
}
}
| 6,270 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoreCenterTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/test/MCRStoreCenterTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.mycore.datamodel.ifs2.MCRStore;
import org.mycore.datamodel.ifs2.MCRStore.MCRStoreConfig;
import org.mycore.datamodel.ifs2.MCRStoreAlreadyExistsException;
import org.mycore.datamodel.ifs2.MCRStoreCenter;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
public class MCRStoreCenterTest {
@Before
public void init() {
MCRStoreCenter.instance().clear();
}
@Test
public void heapOp() throws Exception {
MCRStoreCenter storeHeap = MCRStoreCenter.instance();
FakeStoreConfig config = new FakeStoreConfig("heapOp");
storeHeap.addStore(config.getID(), new FakeStore(config));
String storeID = config.getID();
FakeStore fakeStore = storeHeap.getStore(storeID);
assertNotNull("The store should be not null.", fakeStore);
assertEquals("Fake Store", fakeStore.getMsg());
assertTrue("Could not find store with ID: " + storeID, storeHeap.getCurrentStores(FakeStore.class)
.filter(s -> storeID.equals(s.getID()))
.findAny().isPresent());
assertTrue("Could not remove store with ID: " + storeID, storeHeap.removeStore(storeID));
assertNull("There should be no store with ID: " + storeID, storeHeap.<FakeStore>getStore(storeID));
}
@Test(expected = MCRStoreAlreadyExistsException.class)
public void addStoreTwice() throws Exception {
MCRStoreCenter storeHeap = MCRStoreCenter.instance();
FakeStoreConfig config = new FakeStoreConfig("addStoreTwice");
FakeStore fakeStore = new FakeStore(config);
storeHeap.addStore(config.getID(), fakeStore);
storeHeap.addStore(config.getID(), fakeStore);
}
class FakeStoreConfig implements MCRStoreConfig {
private final Path baseDir;
FakeStoreConfig(String id) {
String fsName = MCRStoreCenterTest.class.getSimpleName() + "." + id;
URI jimfsURI = URI.create("jimfs://" + fsName);
FileSystem fileSystem;
try {
fileSystem = FileSystems.getFileSystem(jimfsURI);
} catch (FileSystemNotFoundException e) {
fileSystem = Jimfs.newFileSystem(fsName, Configuration.unix());
}
baseDir = fileSystem.getPath("/");
}
@Override
public String getID() {
return "fake";
}
@Override
public String getPrefix() {
return "fake_";
}
@Override
public String getBaseDir() {
return baseDir.toUri().toString();
}
@Override
public String getSlotLayout() {
return "4-4-2";
}
}
private String getPropName(String storeID, String propType) {
return new MessageFormat("MCR.IFS2.Store.{0}.{1}", Locale.ROOT).format(new Object[] { storeID, propType });
}
public static class FakeStore extends MCRStore {
private String msg = "Fake Store";
public FakeStore(MCRStoreConfig config) {
init(config);
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMsg() {
return msg;
}
}
}
| 4,455 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoreManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/ifs2/test/MCRStoreManagerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.test;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Map;
import org.junit.Test;
import org.mycore.datamodel.ifs2.MCRFileStore;
import org.mycore.datamodel.ifs2.MCRStore.MCRStoreConfig;
import org.mycore.datamodel.ifs2.MCRStoreManager;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
public class MCRStoreManagerTest {
@Test
public void createMCRFileStore() throws Exception {
StoreConfig config = new StoreConfig();
MCRFileStore fileStore = MCRStoreManager.createStore(config, MCRFileStore.class);
assertNotNull("MCRStoreManager could not create Filestore.", fileStore);
}
class StoreConfig implements MCRStoreConfig {
private final Path baseDir;
StoreConfig() throws IOException {
String fsName = MCRStoreManagerTest.class.getSimpleName();
URI jimfsURI = URI.create("jimfs://" + fsName);
FileSystem fileSystem = Jimfs.newFileSystem(fsName, Configuration.unix());
try {
fileSystem = FileSystems.getFileSystem(jimfsURI);
} catch (FileSystemNotFoundException e) {
fileSystem = FileSystems.newFileSystem(jimfsURI, Map.of("fileSystem", fileSystem));
}
baseDir = fileSystem.getPath("/");
}
@Override
public String getID() {
return "Test";
}
@Override
public String getPrefix() {
return getID() + "_";
}
@Override
public String getBaseDir() {
return baseDir.toUri().toString();
}
@Override
public String getSlotLayout() {
return "4-4-2";
}
}
}
| 2,687 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageResolverTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/datamodel/language/MCRLanguageResolverTest.java | package org.mycore.datamodel.language;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import javax.xml.transform.TransformerException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
public class MCRLanguageResolverTest extends MCRTestCase {
@Test
public void resolve() throws TransformerException {
// german code
MCRLanguageResolver languageResolver = new MCRLanguageResolver();
JDOMSource jdomSource = (JDOMSource) languageResolver.resolve("language:de", "");
Document document = jdomSource.getDocument();
assertNotNull(document);
assertNotNull(document.getRootElement());
Element languageElement = document.getRootElement();
assertEquals(2, languageElement.getChildren().size());
// empty code
assertThrows(IllegalArgumentException.class, () -> {
languageResolver.resolve("language:", "");
});
}
}
| 1,115 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJPATestCase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRJPATestCase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.PrintStream;
import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.mycore.backend.hibernate.MCRHibernateConfigHelper;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.backend.jpa.MCRJPABootstrapper;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
import jakarta.persistence.RollbackException;
public class MCRJPATestCase extends MCRTestCase {
private EntityManager entityManager;
protected Optional<EntityManager> getEntityManager() {
return Optional.ofNullable(entityManager);
}
protected static void printResultSet(ResultSet resultSet, PrintStream out) throws SQLException {
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
Table t = new Table(columns);
for (int i = 1; i <= columns; i++) {
t.addValue(metaData.getColumnName(i));
}
while (resultSet.next()) {
for (int i = 1; i <= columns; i++) {
String value = resultSet.getString(i);
t.addValue(value != null ? value : "null");
}
}
t.print(out);
}
private static void exportSchema(String action) throws IOException {
Map<String, Object> schemaProperties = new HashMap<>();
schemaProperties.put("jakarta.persistence.schema-generation.database.action", action);
try (StringWriter output = new StringWriter()) {
if (LogManager.getLogger().isDebugEnabled()) {
schemaProperties.put("jakarta.persistence.schema-generation.scripts.action", action);
schemaProperties.put("jakarta.persistence.schema-generation.scripts." + action + "-target", output);
}
Persistence.generateSchema(getCurrentComponentName(), schemaProperties);
LogManager.getLogger().debug(() -> "invoked '" + action + "' sql script:\n" + output);
}
}
@Before()
@Override
public void setUp() throws Exception {
// Configure logging etc.
super.setUp();
LogManager.getLogger().debug("Setup JPA");
MCRJPABootstrapper.initializeJPA(getCurrentComponentName());
exportSchema();
MCRHibernateConfigHelper
.checkEntityManagerFactoryConfiguration(MCREntityManagerProvider.getEntityManagerFactory());
try {
LogManager.getLogger().debug("Prepare hibernate test", new RuntimeException());
entityManager = MCREntityManagerProvider.getCurrentEntityManager();
beginTransaction();
entityManager.clear();
} catch (RuntimeException e) {
LogManager.getLogger().error("Error while setting up JPA JUnit test.", e);
entityManager = null;
throw e;
}
}
public void exportSchema() throws IOException {
doSchemaOperation(schema -> "create schema " + schema);
exportSchema("create");
}
private void doSchemaOperation(Function<String, String> schemaFunction) {
EntityManager currentEntityManager = MCREntityManagerProvider.getCurrentEntityManager();
EntityTransaction transaction = currentEntityManager.getTransaction();
try {
transaction.begin();
getDefaultSchema().ifPresent(
schemaFunction
.andThen(currentEntityManager::createNativeQuery)
.andThen(Query::executeUpdate)::apply);
} finally {
if (transaction.isActive()) {
if (transaction.getRollbackOnly()) {
transaction.rollback();
} else {
transaction.commit();
}
}
}
}
protected static Optional<String> getDefaultSchema() {
return Optional.ofNullable(MCREntityManagerProvider
.getEntityManagerFactory()
.getProperties()
.get("hibernate.default_schema"))
.map(Object::toString)
.map(schema -> quoteSchema() ? '"' + schema + '"' : schema);
}
protected static boolean quoteSchema() {
return Optional.ofNullable(MCREntityManagerProvider
.getEntityManagerFactory()
.getProperties()
.get("hibernate.globally_quoted_identifiers"))
.map(Object::toString)
.map(Boolean::parseBoolean)
.orElse(Boolean.FALSE);
}
public void dropSchema() throws IOException {
exportSchema("drop");
doSchemaOperation(schema -> "drop schema " + schema);
}
public MCRJPATestCase() {
super();
}
@After
public void tearDown() throws Exception {
try {
endTransaction();
} finally {
if (entityManager != null) {
entityManager.close();
dropSchema();
}
super.tearDown();
entityManager = null;
}
}
protected void beginTransaction() {
getEntityManager().ifPresent(em -> em.getTransaction().begin());
}
protected void endTransaction() {
getEntityManager().ifPresent(em -> {
EntityTransaction tx = em.getTransaction();
if (tx != null && tx.isActive()) {
if (tx.getRollbackOnly()) {
tx.rollback();
} else {
try {
tx.commit();
} catch (RollbackException e) {
if (tx.isActive()) {
tx.rollback();
}
throw e;
}
}
}
});
}
protected void startNewTransaction() {
endTransaction();
beginTransaction();
// clear from cache
getEntityManager().ifPresent(EntityManager::clear);
}
protected static String getTableName(String table) {
return getDefaultSchema().map(s -> s + ".").orElse("") + table;
}
protected static void printTable(String table) {
queryTable(table, (resultSet) -> {
try {
printResultSet(resultSet, System.out);
} catch (SQLException e) {
LogManager.getLogger().warn("Error while printing result set for table " + table, e);
}
});
}
protected static void queryTable(String table, Consumer<ResultSet> consumer) {
executeQuery("SELECT * FROM " + getTableName(table), consumer);
}
protected static void executeQuery(String query, Consumer<ResultSet> consumer) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.unwrap(Session.class).doWork(connection -> {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(query);
consumer.accept(resultSet);
} catch (SQLException e) {
LogManager.getLogger().warn("Error while querying '" + query + "'", e);
}
});
}
protected static void executeUpdate(String sql) {
executeUpdate(sql, (ignore) -> {
});
}
protected static void executeUpdate(String sql, Consumer<Integer> consumer) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.unwrap(Session.class).doWork(connection -> {
try (Statement statement = connection.createStatement()) {
int updateCount = statement.executeUpdate(sql);
consumer.accept(updateCount);
} catch (SQLException e) {
LogManager.getLogger().warn("Error while update '" + sql + "'", e);
}
});
}
}
| 9,042 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCalendarTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRCalendarTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.ibm.icu.util.BuddhistCalendar;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.CopticCalendar;
import com.ibm.icu.util.EthiopicCalendar;
import com.ibm.icu.util.GregorianCalendar;
import com.ibm.icu.util.HebrewCalendar;
import com.ibm.icu.util.IslamicCalendar;
import com.ibm.icu.util.JapaneseCalendar;
/**
* This class is a JUnit test case for org.mycore.common.MCRCalendar.
*
* @author Jens Kupferschmidt
*/
public class MCRCalendarTest extends MCRTestCase {
/*
* Test method for 'org.mycore.datamodel.metadata.MCRCalendar.getDateToFormattedString()'
*/
@Test
public void getDateToFormattedString() {
GregorianCalendar default_calendar = new GregorianCalendar();
default_calendar.set(1964, 1, 24);
String dstring;
Calendar cal;
// gregorian without format
cal = (GregorianCalendar) default_calendar.clone();
dstring = MCRCalendar.getCalendarDateToFormattedString(cal);
assertEquals("calendar without format", "1964-02-24 AD", dstring);
// gregorian with format
cal = (GregorianCalendar) default_calendar.clone();
dstring = MCRCalendar.getCalendarDateToFormattedString(cal, "dd.MM.yyyy G");
assertEquals("calendar with format dd.MM.yyyy G", "24.02.1964 AD", dstring);
// gregorian with format
cal = (GregorianCalendar) default_calendar.clone();
dstring = MCRCalendar.getCalendarDateToFormattedString(cal, "yyyy-MM-dd");
assertEquals("gregorian with format yyyy-MM-dd", "1964-02-24", dstring);
}
@Test
public void testParseGregorianDate() {
Calendar cal;
// 04.10.1582 AD (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("04.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), Calendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299160);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299160");
// 05.10.1582 AD (gregorian) -> 15.10.1582 (https://en.wikipedia.org/wiki/Inter_gravissimas)
cal = MCRCalendar.getHistoryDateAsCalendar("05.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), Calendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299161);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299161");
// 06.10.1582 AD (gregorian) -> 16.10.1582 in the ICU implementation
cal = MCRCalendar.getHistoryDateAsCalendar("06.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 16);
assertEquals(cal.get(Calendar.MONTH), Calendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299162);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299162");
// 15.10.1582 AD (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("15.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), Calendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299161);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299161");
// 16.10.1582 AD (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("16.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 16);
assertEquals(cal.get(Calendar.MONTH), Calendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299162);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299162");
// 01.01.1800 AD (gregorian) with missing day and last=false
cal = MCRCalendar.getHistoryDateAsCalendar("1.1800", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), Calendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1800);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2378497);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2378497");
// 31.01.1800 AD (gregorian) with missing day and last=true
cal = MCRCalendar.getHistoryDateAsCalendar("1/1800", true, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 31);
assertEquals(cal.get(Calendar.MONTH), Calendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1800);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2378527);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2378527");
// 09.01.1800 AD (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("9/1/1800", true, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 9);
assertEquals(cal.get(Calendar.MONTH), Calendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1800);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2378505);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2378505");
// 24.02.1964 AD (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("1964-02-24", true, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 24);
assertEquals(cal.get(Calendar.MONTH), Calendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 1964);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2438450);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2438450");
// 1 BC with last=true (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("1 BC", true, MCRCalendar.TAG_GREGORIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 31);
assertEquals(cal.get(Calendar.MONTH), Calendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1721423);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1721423");
}
@Test
public void testParseJulianDate() {
Calendar cal;
// 02.01.4713 BC (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("02.01.4713 bc", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 2);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 4713);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1");
// 01.01.0814 BC (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("-814", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 814);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1424110);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1424110");
// 01.01.0814 BC (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("-01.01.814", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 814);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1424110);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1424110");
// 15.03.0044 BC (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("BC 15.03.44", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 44);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1705426);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1705426");
// 01.01.0001 BC (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("01.01.0001 BC", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1721058);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1721058");
// 31.12.0001 BC (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("31.12.0001 v. Chr", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 31);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1721423);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1721423");
// 01.01.0000 -> 1.1.1 BC (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("01.01.0000", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1721058);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1721058");
// 01.01.0001 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("01.01.01 AD", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1721424);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1721424");
// 04.10.1582 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("04.10.1582 N. Chr", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299160);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299160");
// 05.10.1582 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("05.10.1582", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 5);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299161);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299161");
// 06.10.1582 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("06.10.1582", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 6);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299162);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299162");
// 15.10.1582 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("15.10.1582", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299171);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299171");
// 16.10.1582 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("16.10.1582", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 16);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2299172);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2299172");
// 28.02.1700 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("28.02.1700", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 28);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 1700);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2342041);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2342041");
// 29.02.1700 AD (julian)
cal = MCRCalendar.getHistoryDateAsCalendar("29.02.1700", false, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 29);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 1700);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.AD);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 2342042);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "2342042");
// 1 BC with last=true (jul)
cal = MCRCalendar.getHistoryDateAsCalendar("1 BC", true, MCRCalendar.TAG_JULIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 31);
assertEquals(cal.get(Calendar.MONTH), Calendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1721423);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1721423");
}
@Test
public void testParseIslamicDate() {
Calendar cal;
// 01.01.0001 h. (islamic)
cal = MCRCalendar.getHistoryDateAsCalendar("01.01.0001 h.", false, MCRCalendar.TAG_ISLAMIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), IslamicCalendar.MUHARRAM);
assertEquals(cal.get(Calendar.YEAR), 1);
// first day of Islamic calendar is 16.7.622 in Gregorian/Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("16.7.622", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(greg), MCRCalendar.getJulianDayNumber(cal));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1948440);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1948440");
// 01.01.800 H. (islamic) -> 24.09.1397 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("1.800 H.", false, MCRCalendar.TAG_ISLAMIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), IslamicCalendar.MUHARRAM);
assertEquals(cal.get(Calendar.YEAR), 800);
greg = MCRCalendar.getHistoryDateAsCalendar("24.09.1397", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 30.01.800 H. (islamic) -> 23.10.1397 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("1.800 H.", true, MCRCalendar.TAG_ISLAMIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 30);
assertEquals(cal.get(Calendar.MONTH), IslamicCalendar.MUHARRAM);
assertEquals(cal.get(Calendar.YEAR), 800);
greg = MCRCalendar.getHistoryDateAsCalendar("23.10.1397", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 29.12.800 H. (islamic) -> 12.09.1398 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("800", true, MCRCalendar.TAG_ISLAMIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 29);
assertEquals(cal.get(Calendar.MONTH), IslamicCalendar.DHU_AL_HIJJAH);
assertEquals(cal.get(Calendar.YEAR), 800);
greg = MCRCalendar.getHistoryDateAsCalendar("12.09.1398", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -1 (isl) -> 15.07.622 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_ISLAMIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 29);
assertEquals(cal.get(Calendar.MONTH), IslamicCalendar.DHU_AL_HIJJAH);
assertEquals(cal.get(Calendar.YEAR), 0);
greg = MCRCalendar.getHistoryDateAsCalendar("15.7.622", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
}
@Test
public void testParseCopticDate() {
Calendar cal;
// 01.01.0001 A.M. (coptic)
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1 a.M.", false, MCRCalendar.TAG_COPTIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), CopticCalendar.TOUT);
assertEquals(cal.get(Calendar.YEAR), 1);
// first day of Coptic calendar is 29.8.284 in Gregorian/Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("29.8.284", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(greg), MCRCalendar.getJulianDayNumber(cal));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1825030);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1825030");
// 01.01.1724 A.M. (coptic) -> 12.09.2007
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1724 A.M.", false, MCRCalendar.TAG_COPTIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), CopticCalendar.TOUT);
assertEquals(cal.get(Calendar.YEAR), 1724);
greg = MCRCalendar.getHistoryDateAsCalendar("12.09.2007", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 05.13.1724 E.E. (coptic) -> 10.09.2008
cal = MCRCalendar.getHistoryDateAsCalendar("1724 a.M.", true, MCRCalendar.TAG_COPTIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 5);
assertEquals(cal.get(Calendar.MONTH), CopticCalendar.NASIE);
assertEquals(cal.get(Calendar.YEAR), 1724);
greg = MCRCalendar.getHistoryDateAsCalendar("10.09.2008", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -5.13.1 (cop) -> 28.8.284
cal = MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_COPTIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 5);
assertEquals(cal.get(Calendar.MONTH), CopticCalendar.NASIE);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("28.8.284", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
}
@Test
public void testParseEthiopianDate() {
Calendar cal;
// 01.01.0001 E.E. (ethiopic)
cal = MCRCalendar.getHistoryDateAsCalendar("1 E.E.", false, MCRCalendar.TAG_ETHIOPIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), EthiopicCalendar.MESKEREM);
assertEquals(cal.get(Calendar.YEAR), 1);
// first day of Ehtiopian calendar is 29.8.8 in Gregorian/Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("29.8.8", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(greg), MCRCalendar.getJulianDayNumber(cal));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1724221);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1724221");
// 05.13.2000 E.E. (ethiopic) -> 10.09.2008 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("2000 E.E.", true, MCRCalendar.TAG_ETHIOPIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 5);
assertEquals(cal.get(Calendar.MONTH), EthiopicCalendar.PAGUMEN);
assertEquals(cal.get(Calendar.YEAR), 2000);
assertEquals(cal.get(Calendar.ERA), 1);
greg = MCRCalendar.getHistoryDateAsCalendar("10.09.2008", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// years before 0 are represented in Amete Alem format (starting with count from 5500 BC)
cal = MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_ETHIOPIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 5);
assertEquals(cal.get(Calendar.MONTH), EthiopicCalendar.PAGUMEN);
assertEquals(cal.get(Calendar.YEAR), 5500);
assertEquals(cal.get(Calendar.ERA), 0);
greg = MCRCalendar.getHistoryDateAsCalendar("28.8.8", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
}
@Test
public void testParseHebrewDate() {
Calendar cal;
// 1.1.1 (hebrew)
cal = MCRCalendar.getHistoryDateAsCalendar("1", false, MCRCalendar.TAG_HEBREW);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), HebrewCalendar.TISHRI);
assertEquals(cal.get(Calendar.YEAR), 1);
// first day of Hebrew calendar is 7.10.3761 BC in Gregorian/Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("7.10.3761 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 347998);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "347998");
// 04.10.1582 (hebrew) - 29.04.2178 BC
cal = MCRCalendar.getHistoryDateAsCalendar("04.10.1582", false, MCRCalendar.TAG_HEBREW);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), HebrewCalendar.SIVAN);
assertEquals(cal.get(Calendar.YEAR), 1582);
greg = MCRCalendar.getHistoryDateAsCalendar("17.05.2179 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 18.01.5343 (hebrew) -> 04.10.1582 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("18.01.5343", false, MCRCalendar.TAG_HEBREW);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 18);
assertEquals(cal.get(Calendar.MONTH), HebrewCalendar.TISHRI);
assertEquals(cal.get(Calendar.YEAR), 5343);
greg = MCRCalendar.getHistoryDateAsCalendar("04.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 19.01.5343 (hebrew) -> 15.10.1582 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("19.01.5343", false, MCRCalendar.TAG_HEBREW);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 19);
assertEquals(cal.get(Calendar.MONTH), HebrewCalendar.TISHRI);
assertEquals(cal.get(Calendar.YEAR), 5343);
greg = MCRCalendar.getHistoryDateAsCalendar("15.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 19.01.5343 (hebrew) -> 16.10.1582 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("20.01.5343", false, MCRCalendar.TAG_HEBREW);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 20);
assertEquals(cal.get(Calendar.MONTH), HebrewCalendar.TISHRI);
assertEquals(cal.get(Calendar.YEAR), 5343);
greg = MCRCalendar.getHistoryDateAsCalendar("16.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 01.01.1800 (hebrew) with missing day and last=false
cal = MCRCalendar.getHistoryDateAsCalendar("1.1800", false, MCRCalendar.TAG_HEBREW);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), HebrewCalendar.TISHRI);
assertEquals(cal.get(Calendar.YEAR), 1800);
greg = MCRCalendar.getHistoryDateAsCalendar("09.09.1962 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -1 (hebrew) not supported
assertThrows(MCRException.class,
() -> MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_HEBREW));
}
@Test
public void testParseBuddhistDate() {
Calendar cal;
// 1.1.1 (buddhist)
cal = MCRCalendar.getHistoryDateAsCalendar("1", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1);
// first day of Buddhist calendar is 1.1.543 BC in Gregorian/Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("1.1.543 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1523093);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1523093");
// year 0
cal = MCRCalendar.getHistoryDateAsCalendar("0", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 0);
greg = MCRCalendar.getHistoryDateAsCalendar("1.1.544 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// year -1
cal = MCRCalendar.getHistoryDateAsCalendar("-1.1.1", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 0);
greg = MCRCalendar.getHistoryDateAsCalendar("1.1.544 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// year -100
cal = MCRCalendar.getHistoryDateAsCalendar("-100", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), -99);
greg = MCRCalendar.getHistoryDateAsCalendar("1.1.643 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 04.10.2125 (buddhist) -> year 1582 in gregorian calendar
cal = MCRCalendar.getHistoryDateAsCalendar("04.10.2125", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 2125);
greg = MCRCalendar.getHistoryDateAsCalendar("04.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 05.10.2125 (buddhist) -> 15.10.1582 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("05.10.2125", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 2125);
greg = MCRCalendar.getHistoryDateAsCalendar("05.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 06.10.2125 (buddhist) -> 15.10.1582 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("06.10.2125", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 2125);
greg = MCRCalendar.getHistoryDateAsCalendar("15.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 15.10.2125 (buddhist) -> 15.10.1582 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("15.10.2125", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 2125);
greg = MCRCalendar.getHistoryDateAsCalendar("15.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 16.10.2125 (buddhist) -> 15.10.1582 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("16.10.2125", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 16);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 2125);
greg = MCRCalendar.getHistoryDateAsCalendar("16.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 01.01.1800 (buddhist) with missing day and last=false -> 01.01.257 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("1.1800", false, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1800);
greg = MCRCalendar.getHistoryDateAsCalendar("01.01.1257", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 24.02.1964 (buddhist) -> 24.04142 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("1964-02-24", true, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 24);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 1964);
greg = MCRCalendar.getHistoryDateAsCalendar("24.02.1421", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 24.02.1964 BE (buddhist) -> 24.02.2507 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("1964-02-24 B.E.", true, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 24);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), -1963);
greg = MCRCalendar.getHistoryDateAsCalendar("24.02.2507 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -1 (buddhist) -> 24.02.2507 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_BUDDHIST);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 31);
assertEquals(cal.get(Calendar.MONTH), BuddhistCalendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 0);
greg = MCRCalendar.getHistoryDateAsCalendar("31.12.544 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
}
@Test
public void testParsePersianDate() {
Calendar cal;
// 01.01.0001 (persian) -> 22.3.622 greg
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 21);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 622);
// first day of Persian calendar is 21.3.622 in Gregorian/Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("21.3.622", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1948323);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1948323");
// 01.01.800 (persian)
cal = MCRCalendar.getHistoryDateAsCalendar("1.800", false, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 21);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 1421);
greg = MCRCalendar.getHistoryDateAsCalendar("21.03.1421", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 31.01.800 (persian)
cal = MCRCalendar.getHistoryDateAsCalendar("1.800", true, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 20);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.APRIL);
assertEquals(cal.get(Calendar.YEAR), 1421);
greg = MCRCalendar.getHistoryDateAsCalendar("20.04.1421", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 29.12.800 (persian)
cal = MCRCalendar.getHistoryDateAsCalendar("800", true, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 20);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 1422);
greg = MCRCalendar.getHistoryDateAsCalendar("20.03.1422", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// gregorian calendar reform on October, 5th 1582 -> skip days between 5 and 15
cal = MCRCalendar.getHistoryDateAsCalendar("12.7.961", false, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
greg = MCRCalendar.getHistoryDateAsCalendar("04.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("13.7.961", false, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
greg = MCRCalendar.getHistoryDateAsCalendar("15.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("14.7.961", false, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 16);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
greg = MCRCalendar.getHistoryDateAsCalendar("16.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -1.1.1 (pers) -> 22.03.621 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("-1", false, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 21);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 621);
greg = MCRCalendar.getHistoryDateAsCalendar("21.03.621", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -29.12.1 (pers) -> 21.03.621 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_PERSIC);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 21);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 622);
greg = MCRCalendar.getHistoryDateAsCalendar("21.03.622", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
}
@Test
public void testParseArmenianDate() {
Calendar cal;
// 01.01.0001 (armenian)
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 13);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JULY);
assertEquals(cal.get(Calendar.YEAR), 552);
// first day of Armenian calendar is 13.7.552 in Gregorian/11.7.552 in Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("13.7.552", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1922870);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1922870");
cal = MCRCalendar.getHistoryDateAsCalendar("1.2.1", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 12);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.AUGUST);
assertEquals(cal.get(Calendar.YEAR), 552);
greg = MCRCalendar.getHistoryDateAsCalendar("12.08.552", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("5.13.1", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 12);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JULY);
assertEquals(cal.get(Calendar.YEAR), 553);
greg = MCRCalendar.getHistoryDateAsCalendar("12.07.553", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("2.9.48", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 28);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 600);
greg = MCRCalendar.getHistoryDateAsCalendar("28.02.600", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("3.9.48", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 29);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 600);
greg = MCRCalendar.getHistoryDateAsCalendar("29.02.600", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("4.9.48", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 600);
greg = MCRCalendar.getHistoryDateAsCalendar("01.03.600", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1462", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 26);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JULY);
assertEquals(cal.get(Calendar.YEAR), 2012);
greg = MCRCalendar.getHistoryDateAsCalendar("26.07.2012", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.101", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 18);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JUNE);
assertEquals(cal.get(Calendar.YEAR), 652);
greg = MCRCalendar.getHistoryDateAsCalendar("18.06.652", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1031", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 29);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1581);
greg = MCRCalendar.getHistoryDateAsCalendar("29.10.1581", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// checks for gregorian calendar switch in 1582
// 11.12.1031 arm -> 4.10.1582 greg
cal = MCRCalendar.getHistoryDateAsCalendar("11.12.1031", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
greg = MCRCalendar.getHistoryDateAsCalendar("04.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 12.12.1031 arm -> 15.10.1582 greg
cal = MCRCalendar.getHistoryDateAsCalendar("12.12.1031", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
greg = MCRCalendar.getHistoryDateAsCalendar("15.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 13.12.1031 arm -> 16.10.1582 greg
cal = MCRCalendar.getHistoryDateAsCalendar("13.12.1031", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 16);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.OCTOBER);
assertEquals(cal.get(Calendar.YEAR), 1582);
greg = MCRCalendar.getHistoryDateAsCalendar("16.10.1582", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 12.500 (last=false) -> 1.12.500 -> 8.2.1052 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("12.500", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 1052);
greg = MCRCalendar.getHistoryDateAsCalendar("04.02.1052", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 12.500 (last=true) -> 30.12.500 -> 8.3.1052 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("12.500", true, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 4);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 1052);
greg = MCRCalendar.getHistoryDateAsCalendar("04.03.1052", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 500 (last=false) -> 1.1.500 -> 15.3.1051 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("500", false, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 11);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 1051);
greg = MCRCalendar.getHistoryDateAsCalendar("11.03.1051", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 500 (last=true) -> 5.13.500 -> 13.3.1052 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("500", true, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 9);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 1052);
greg = MCRCalendar.getHistoryDateAsCalendar("09.03.1052", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -1 (last=true) -> 5.13.-1 -> 12.07.552 (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_ARMENIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 12);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.JULY);
assertEquals(cal.get(Calendar.YEAR), 552);
greg = MCRCalendar.getHistoryDateAsCalendar("12.07.552", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
}
@Test
public void testParseEgyptianDate() {
Calendar cal;
// 01.01.0001 (egyptian)
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 18);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 747);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
// first day of Egyptian calendar is 18.2.747 BC in Gregorian/Julian calendar
Calendar greg = MCRCalendar.getHistoryDateAsCalendar("18.2.747 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumber(cal), 1448630);
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), "1448630");
// 1.1 -> 30.1.1 in Gregorian date: 19.3.747 BC
cal = MCRCalendar.getHistoryDateAsCalendar("1.1 A.N.", true, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 19);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 747);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("19.03.747 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 10.1 (last=false) -> 1.10.1 in Gregorian date: 14.12.747 BC
cal = MCRCalendar.getHistoryDateAsCalendar("10.1 A.N.", false, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 15);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.NOVEMBER);
assertEquals(cal.get(Calendar.YEAR), 747);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("15.11.747 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 10.1 (last=true) -> 30.10.1 in Gregorian date: 14.12.747 BC
cal = MCRCalendar.getHistoryDateAsCalendar("10.1 A.N.", true, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 14);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 747);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("14.12.747 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 1.2.1 -> in Gregorian date: 20.3.747 BC
cal = MCRCalendar.getHistoryDateAsCalendar("1.2.1 A.N.", false, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 20);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.MARCH);
assertEquals(cal.get(Calendar.YEAR), 747);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("20.03.747 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 13.1 (last=false) -> 1.13.1 (in Gregorian date: 17.2.746)
cal = MCRCalendar.getHistoryDateAsCalendar("13.1 A.N.", false, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 13);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 746);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("13.02.746 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// 1 (last=true) -> 5.13.1 (in Gregorian date: 17.2.746)
cal = MCRCalendar.getHistoryDateAsCalendar("1 A.N.", true, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 17);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 746);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("17.02.746 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
// -1 (last=true) -> 17.02.747 BC (greg)
cal = MCRCalendar.getHistoryDateAsCalendar("-1", true, MCRCalendar.TAG_EGYPTIAN);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 17);
assertEquals(cal.get(Calendar.MONTH), GregorianCalendar.FEBRUARY);
assertEquals(cal.get(Calendar.YEAR), 747);
assertEquals(cal.get(Calendar.ERA), GregorianCalendar.BC);
greg = MCRCalendar.getHistoryDateAsCalendar("17.02.747 BC", false, MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getJulianDayNumber(cal), MCRCalendar.getJulianDayNumber(greg));
assertEquals(MCRCalendar.getJulianDayNumberAsString(cal), MCRCalendar.getJulianDayNumberAsString(greg));
}
@Test
public void testParseJapaneseDate() {
Calendar cal;
// Meiji era: 8.9.1868 - 29.07.1912
cal = MCRCalendar.getHistoryDateAsCalendar("8.9.M1", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 8);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.SEPTEMBER);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.MEIJI);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("8.9.1868", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("29.7.M45", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 29);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.JULY);
assertEquals(cal.get(Calendar.YEAR), 45);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.MEIJI);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("29.7.1912", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("30.7.M45", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 30);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.JULY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.TAISHO);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("30.7.1912", false, MCRCalendar.TAG_GREGORIAN)));
// Taisho era: 30.7.1912-24.12.1926
cal = MCRCalendar.getHistoryDateAsCalendar("30.7.T1", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 30);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.JULY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.TAISHO);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("30.7.1912", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("24.12.T15", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 24);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 15);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.TAISHO);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("24.12.1926", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("25.12.T15", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 25);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.SHOWA);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("25.12.1926", false, MCRCalendar.TAG_GREGORIAN)));
// Showa era: 25.12.1926-07.01.1989
cal = MCRCalendar.getHistoryDateAsCalendar("25.12.S1", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 25);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.DECEMBER);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.SHOWA);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("25.12.1926", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("7.1.S64", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 7);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 64);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.SHOWA);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("7.1.1989", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("8.1.S64", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 8);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.HEISEI);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("8.1.1989", false, MCRCalendar.TAG_GREGORIAN)));
// Heisei era: 08.01.1989-30.04.2019
cal = MCRCalendar.getHistoryDateAsCalendar("8.1.H1", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 8);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.JANUARY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.HEISEI);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("8.1.1989", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("30.4.H31", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 30);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.APRIL);
assertEquals(cal.get(Calendar.YEAR), 31);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.HEISEI);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("30.4.2019", false, MCRCalendar.TAG_GREGORIAN)));
cal = MCRCalendar.getHistoryDateAsCalendar("1.5.H31", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.MAY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.REIWA);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("1.5.2019", false, MCRCalendar.TAG_GREGORIAN)));
// Reiwa era: 01.05.2019 - present
cal = MCRCalendar.getHistoryDateAsCalendar("1.5.R1", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.MAY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.REIWA);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("1.5.2019", false, MCRCalendar.TAG_GREGORIAN)));
// check ISO format
cal = MCRCalendar.getHistoryDateAsCalendar("R1-5-1", true, MCRCalendar.TAG_JAPANESE);
assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
assertEquals(cal.get(Calendar.MONTH), JapaneseCalendar.MAY);
assertEquals(cal.get(Calendar.YEAR), 1);
assertEquals(cal.get(Calendar.ERA), JapaneseCalendar.REIWA);
assertEquals(MCRCalendar.getJulianDayNumber(cal),
MCRCalendar.getJulianDayNumber(
MCRCalendar.getHistoryDateAsCalendar("1.5.2019", false, MCRCalendar.TAG_GREGORIAN)));
}
/*
* Test method for 'org.mycore.datamodel.metadata.MCRCalendar.getHistoryDateAsCalendar(String, boolean, String)'
*/
@Test
public void getHistoryDateAsCalendar() {
String cstring, dstring;
cstring = MCRCalendar.getCalendarDateToFormattedString(new GregorianCalendar());
Calendar cal;
/* check julian calendar implementation */
// all entries are empty
try {
cal = MCRCalendar.getHistoryDateAsCalendar(null, false, MCRCalendar.CalendarType.Islamic);
} catch (MCRException e) {
cal = new GregorianCalendar();
}
dstring = MCRCalendar.getCalendarDateToFormattedString(cal);
assertEquals("Date is not the current date.", cstring, dstring);
// 0A.01.0001 BC (wrong gregorian)
try {
cal = MCRCalendar.getHistoryDateAsCalendar("-0A.01.0001", false, MCRCalendar.TAG_JULIAN);
} catch (MCRException e) {
cal = new GregorianCalendar();
}
dstring = MCRCalendar.getCalendarDateToFormattedString(cal);
assertEquals("common", cstring, dstring);
/* syntax expanding check */
// 1 (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("1", false, MCRCalendar.TAG_JULIAN);
dstring = MCRCalendar.getJulianDayNumberAsString(cal);
assertEquals("common", "1721424", dstring);
// 1.1 (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("1.1", true, MCRCalendar.TAG_JULIAN);
dstring = MCRCalendar.getJulianDayNumberAsString(cal);
assertEquals("common", "1721454", dstring);
// 1.1.1 (gregorian)
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_JULIAN);
dstring = MCRCalendar.getJulianDayNumberAsString(cal);
assertEquals("common", "1721424", dstring);
// 1.1.1 QU(gregorian)
try {
cal = MCRCalendar.getHistoryDateAsCalendar("1.1.1 QU", false, MCRCalendar.TAG_JULIAN);
} catch (MCRException e) {
cal = new GregorianCalendar();
}
dstring = MCRCalendar.getCalendarDateToFormattedString(cal);
assertEquals("common", cstring, dstring);
// - infinity (julian)
cal.set(Calendar.JULIAN_DAY, MCRCalendar.MIN_JULIAN_DAY_NUMBER);
dstring = MCRCalendar.getJulianDayNumberAsString(cal);
assertEquals("julian: 01.01.4713 BC", "0", dstring);
// + infinity (julian)
cal.set(Calendar.JULIAN_DAY, MCRCalendar.MAX_JULIAN_DAY_NUMBER);
dstring = MCRCalendar.getJulianDayNumberAsString(cal);
assertEquals("julian: 28.01.4000 AD", "3182057", dstring);
}
/*
* Test method for 'org.mycore.datamodel.metadata.MCRCalendar.getJulianDayNumberAsString(Calendar)'
*/
@Test
public void getDateToFormattedStringForCalendar() {
Calendar calendar;
String dstring;
// 15.03.44 BC (julian)
calendar = MCRCalendar.getHistoryDateAsCalendar("-15.3.44", true, MCRCalendar.TAG_JULIAN);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyyy G");
assertEquals("is not julian date 15.03.44 BC", "15.03.0044 BC", dstring);
// 15.03.44 BC (gregorian)
calendar = MCRCalendar.getHistoryDateAsCalendar("-15.3.44", true, MCRCalendar.TAG_GREGORIAN);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyyy G");
assertEquals("is not gregorian date 15.03.44 BC", "15.03.0044 BC", dstring);
// 29.02.1700 (julian)
calendar = MCRCalendar.getHistoryDateAsCalendar("29.02.1700", true, MCRCalendar.TAG_JULIAN);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyyy G");
assertEquals("is not julian date 29.02.1700 AD", "29.02.1700 AD", dstring);
// 29.02.1700 (gregorian) -> no leap year in gregorian calendar
assertThrows(MCRException.class,
() -> MCRCalendar.getHistoryDateAsCalendar("29.02.1700", true, MCRCalendar.TAG_GREGORIAN));
// 30.01.800 H. (islamic)
calendar = MCRCalendar.getHistoryDateAsCalendar("30.1.800 H.", true, MCRCalendar.TAG_ISLAMIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyy");
assertEquals("is not islamic date 30.01.0800 H.", "30.01.800 h.", dstring);
// 01.01.800 H. (islamic)
calendar = MCRCalendar.getHistoryDateAsCalendar("1.800 H.", false, MCRCalendar.TAG_ISLAMIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyy");
assertEquals("is not islamic date 01.01.0800 H.", "01.01.800 h.", dstring);
// 30.01.800 H. (islamic)
calendar = MCRCalendar.getHistoryDateAsCalendar("1.800 H.", true, MCRCalendar.TAG_ISLAMIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyy");
assertEquals("is not islamic date 30.01.0800 H.", "30.01.800 h.", dstring);
// 01.01.800 H. (islamic)
calendar = MCRCalendar.getHistoryDateAsCalendar("800", false, MCRCalendar.TAG_ISLAMIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyy");
assertEquals("is not islamic date 01.01.0800 H.", "01.01.800 h.", dstring);
// 29.12.800 H. (islamic)
calendar = MCRCalendar.getHistoryDateAsCalendar("800", true, MCRCalendar.TAG_ISLAMIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyy");
assertEquals("is not islamic date 29.12.0800 H.", "29.12.800 h.", dstring);
// 29.12.800 H. (islamic)
calendar = MCRCalendar.getHistoryDateAsCalendar("800 H.", true, MCRCalendar.TAG_ISLAMIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyy");
assertEquals("is not islamic date 29.12.0800 H.", "29.12.800 h.", dstring);
// 01.01.1724 A.M. (coptic)
calendar = MCRCalendar.getHistoryDateAsCalendar("1724", false, MCRCalendar.TAG_COPTIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyyy");
assertEquals("is not coptic date 01.01.1724 A.M.", "01.01.1724 A.M.", dstring);
// 01.01.2000 A.M. (ethiopic)
calendar = MCRCalendar.getHistoryDateAsCalendar("2000", true, MCRCalendar.TAG_ETHIOPIC);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyyy");
assertEquals("is not ethiopic date 05.13.2000 E.E.", "05.13.2000 E.E.", dstring);
calendar = MCRCalendar.getHistoryDateAsCalendar("1.1.500", false, MCRCalendar.TAG_ARMENIAN);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yyyy");
assertEquals("is not armenian date 11.03.1051", "11.03.1051", dstring);
calendar = MCRCalendar.getHistoryDateAsCalendar("5.7.H2", false, MCRCalendar.TAG_JAPANESE);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.Y");
assertEquals("is not japanese date 05.07.1990", "05.07.1990", dstring);
calendar = MCRCalendar.getHistoryDateAsCalendar("2.7.20", false, MCRCalendar.TAG_BUDDHIST);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.yy");
assertEquals("is not japanese date 02.07.20", "02.07.20", dstring);
calendar = MCRCalendar.getHistoryDateAsCalendar("2.7.20", false, MCRCalendar.TAG_BUDDHIST);
dstring = MCRCalendar.getCalendarDateToFormattedString(calendar, "dd.MM.Y");
assertEquals("is not buddhist date 02.07.-523", "02.07.-523", dstring);
}
@Test
public void testIsoFormat() {
assertFalse(MCRCalendar.isoFormat("23.03.2022"));
assertFalse(MCRCalendar.isoFormat("23/03/2022"));
assertTrue(MCRCalendar.isoFormat("23-03-2022"));
assertFalse(MCRCalendar.isoFormat("-23.03.2022"));
assertFalse(MCRCalendar.isoFormat("-23/03/2022"));
assertTrue(MCRCalendar.isoFormat("-23-03-2022"));
assertFalse(MCRCalendar.isoFormat("800"));
}
@Test
public void testDelimiter() {
assertEquals(MCRCalendar.delimiter("23.03.2022"), ".");
assertEquals(MCRCalendar.delimiter("23/03/2022"), "/");
assertEquals(MCRCalendar.delimiter("23-03-2022"), "-");
assertEquals(MCRCalendar.delimiter("-23.03.2022"), ".");
assertEquals(MCRCalendar.delimiter("-23/03/2022"), "/");
assertEquals(MCRCalendar.delimiter("-23-03-2022"), "-");
assertEquals(MCRCalendar.delimiter("800"), ".");
}
@Test
public void testBeforeZero() {
assertFalse(MCRCalendar.beforeZero("23.03.2022", MCRCalendar.CalendarType.Gregorian));
assertFalse(MCRCalendar.beforeZero("23/03/2022", MCRCalendar.CalendarType.Gregorian));
assertFalse(MCRCalendar.beforeZero("23-03-2022", MCRCalendar.CalendarType.Gregorian));
assertTrue(MCRCalendar.beforeZero("-23.03.2022", MCRCalendar.CalendarType.Gregorian));
assertTrue(MCRCalendar.beforeZero("-23/03/2022", MCRCalendar.CalendarType.Gregorian));
assertTrue(MCRCalendar.beforeZero("-23-03-2022", MCRCalendar.CalendarType.Gregorian));
assertFalse(MCRCalendar.beforeZero("23-03-2022 AD", MCRCalendar.CalendarType.Gregorian));
assertFalse(MCRCalendar.beforeZero("AD 23-03-2022", MCRCalendar.CalendarType.Gregorian));
assertTrue(MCRCalendar.beforeZero("23-03-2022 BC", MCRCalendar.CalendarType.Gregorian));
assertTrue(MCRCalendar.beforeZero("BC 23-03-2022", MCRCalendar.CalendarType.Gregorian));
}
@Test
public void testGetLastDayOfMonth() {
assertEquals(MCRCalendar.getLastDayOfMonth(GregorianCalendar.JANUARY, 2000, MCRCalendar.CalendarType.Gregorian),
31);
assertEquals(
MCRCalendar.getLastDayOfMonth(GregorianCalendar.FEBRUARY, 2000, MCRCalendar.CalendarType.Gregorian),
29);
assertEquals(
MCRCalendar.getLastDayOfMonth(GregorianCalendar.FEBRUARY, 2001, MCRCalendar.CalendarType.Gregorian),
28);
assertEquals(MCRCalendar.getLastDayOfMonth(GregorianCalendar.MARCH, 2000, MCRCalendar.CalendarType.Gregorian),
31);
assertEquals(MCRCalendar.getLastDayOfMonth(GregorianCalendar.APRIL, 2000, MCRCalendar.CalendarType.Gregorian),
30);
assertEquals(
MCRCalendar.getLastDayOfMonth(GregorianCalendar.FEBRUARY, 1700, MCRCalendar.CalendarType.Gregorian),
28);
assertEquals(MCRCalendar.getLastDayOfMonth(GregorianCalendar.FEBRUARY, 1700, MCRCalendar.CalendarType.Julian),
29);
assertEquals(MCRCalendar.getLastDayOfMonth(CopticCalendar.NASIE, 2000, MCRCalendar.CalendarType.Coptic),
5);
assertEquals(MCRCalendar.getLastDayOfMonth(11, 2000, MCRCalendar.CalendarType.Egyptian),
30);
assertEquals(MCRCalendar.getLastDayOfMonth(12, 2000, MCRCalendar.CalendarType.Egyptian),
5);
assertEquals(MCRCalendar.getLastDayOfMonth(11, 2000, MCRCalendar.CalendarType.Armenian),
30);
assertEquals(MCRCalendar.getLastDayOfMonth(12, 2000, MCRCalendar.CalendarType.Armenian),
5);
}
@Test
public void testIsLeapYear() {
assertTrue(MCRCalendar.isLeapYear(2000, MCRCalendar.CalendarType.Gregorian));
assertFalse(MCRCalendar.isLeapYear(1999, MCRCalendar.CalendarType.Gregorian));
assertFalse(MCRCalendar.isLeapYear(1582, MCRCalendar.CalendarType.Gregorian));
assertFalse(MCRCalendar.isLeapYear(1900, MCRCalendar.CalendarType.Gregorian));
assertTrue(MCRCalendar.isLeapYear(1900, MCRCalendar.CalendarType.Julian));
}
@Test
public void testGetCalendarTypeString() {
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_ARMENIAN)),
MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_BUDDHIST)),
MCRCalendar.TAG_BUDDHIST);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_COPTIC)),
MCRCalendar.TAG_COPTIC);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_ETHIOPIC)),
MCRCalendar.TAG_ETHIOPIC);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_GREGORIAN)),
MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_JULIAN)),
MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_HEBREW)),
MCRCalendar.TAG_HEBREW);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_ISLAMIC)),
MCRCalendar.TAG_ISLAMIC);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1H1", false, MCRCalendar.TAG_JAPANESE)),
MCRCalendar.TAG_JAPANESE);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_PERSIC)),
MCRCalendar.TAG_GREGORIAN);
assertEquals(MCRCalendar.getCalendarTypeString(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_EGYPTIAN)),
MCRCalendar.TAG_GREGORIAN);
}
@Test
public void testGetGregorianCalendarOfACalendar() {
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_ARMENIAN)),
MCRCalendar.getHistoryDateAsCalendar("13.7.552", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_BUDDHIST)),
MCRCalendar.getHistoryDateAsCalendar("1.1.543 BC", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_COPTIC)),
MCRCalendar.getHistoryDateAsCalendar("29.8.284", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_ETHIOPIC)),
MCRCalendar.getHistoryDateAsCalendar("29.8.8", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_GREGORIAN)),
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_JULIAN)),
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_HEBREW)),
MCRCalendar.getHistoryDateAsCalendar("-7.10.3761", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_ISLAMIC)),
MCRCalendar.getHistoryDateAsCalendar("16.7.622", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.H1", false, MCRCalendar.TAG_JAPANESE)),
MCRCalendar.getHistoryDateAsCalendar("1.1.1989", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_PERSIC)),
MCRCalendar.getHistoryDateAsCalendar("21.3.622", false, MCRCalendar.TAG_GREGORIAN));
compareCalendarDates(MCRCalendar.getGregorianCalendarOfACalendar(
MCRCalendar.getHistoryDateAsCalendar("1.1.1", false, MCRCalendar.TAG_EGYPTIAN)),
MCRCalendar.getHistoryDateAsCalendar("18.2.747 BC", false, MCRCalendar.TAG_GREGORIAN));
}
private void compareCalendarDates(Calendar actual, Calendar expected) {
assertEquals(actual.get(Calendar.YEAR), expected.get(Calendar.YEAR));
assertEquals(actual.get(Calendar.MONTH), expected.get(Calendar.MONTH));
assertEquals(actual.get(Calendar.DAY_OF_MONTH), expected.get(Calendar.DAY_OF_MONTH));
assertEquals(actual.get(Calendar.ERA), expected.get(Calendar.ERA));
}
}
| 85,431 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoreTestCase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRStoreTestCase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.nio.file.Path;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
public abstract class MCRStoreTestCase extends MCRJPATestCase {
private static MCRXMLMetadataManager store;
@Rule
public TemporaryFolder storeBaseDir = new TemporaryFolder();
@Rule
public TemporaryFolder svnBaseDir = new TemporaryFolder();
@Before
public void setUp() throws Exception {
super.setUp();
store = MCRXMLMetadataManager.instance();
store.reload();
}
public Path getStoreBaseDir() {
return storeBaseDir.getRoot().toPath();
}
public Path getSvnBaseDir() {
return svnBaseDir.getRoot().toPath();
}
public static MCRXMLMetadataManager getStore() {
return store;
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Store.BaseDir", storeBaseDir.getRoot().getAbsolutePath());
testProperties.put("MCR.Metadata.Store.SVNBase", svnBaseDir.getRoot().toURI().toString());
return testProperties;
}
}
| 2,016 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageDetectorTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRLanguageDetectorTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MCRLanguageDetectorTest extends MCRTestCase {
@Test
public void testLanguageDetection() {
assertEquals("de",
MCRLanguageDetector.detectLanguage("Das Leben ist eher kurz als lang, und wir stehen alle mittenmang"));
assertEquals("en",
MCRLanguageDetector.detectLanguage("MyCoRe is the best repository software currently available"));
assertEquals("fr",
MCRLanguageDetector.detectLanguage("Tout vient Γ point Γ qui sait attendre"));
assertEquals("de",
MCRLanguageDetector.detectLanguage("Ein simples Ξ² macht noch keinen Griechen aus Dir."));
assertEquals("el",
MCRLanguageDetector.detectLanguage("Φοβοῦ ΟΞΏα½ΊΟ ΞΞ±Ξ½Ξ±ΞΏα½ΊΟ ΞΊΞ±α½Ά Ξ΄αΏΆΟΞ± ΟΞΟΞΏΞ½ΟΞ±Ο"));
}
}
| 1,629 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUtilsTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRUtilsTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import org.apache.logging.log4j.LogManager;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRUtilsTest extends MCRTestCase {
private static final String TEST = "Hello World!";
private static final String TEST_SHA1 = "2ef7bde608ce5404e97d5f042f95f89f1c232871";
private static final String TEST_MD5 = "ed076287532e86365e841e92bfc50d8c";
@Rule
public TemporaryFolder baseDir = new TemporaryFolder();
@Rule
public TemporaryFolder evilDir = new TemporaryFolder();
/**
* Test method for {@link org.mycore.common.MCRUtils#asSHA1String(int, byte[], String)}.
*/
@Test
public final void testAsSHA1String() {
try {
String sha1String = MCRUtils.asSHA1String(1, null, TEST);
assertEquals("SHA-1 string has not the right length", TEST_SHA1.length(), sha1String.length());
assertEquals("SHA-1 string does not match", TEST_SHA1, sha1String);
} catch (NoSuchAlgorithmException e) {
LogManager.getLogger(this.getClass()).warn("SHA-1 algorithm not available");
}
}
/**
* Test method for {@link org.mycore.common.MCRUtils#asMD5String(int, byte[], String)}.
*/
@Test
public final void testAsMD5String() {
try {
String md5String = MCRUtils.asMD5String(1, null, TEST);
assertEquals("MD5 string has not the right length", TEST_MD5.length(), md5String.length());
assertEquals("MD5 string does not match", TEST_MD5, md5String);
} catch (NoSuchAlgorithmException e) {
LogManager.getLogger(this.getClass()).warn("MD5 algorithm not available");
}
}
@Test(expected = MCRException.class)
public final void testResolveEvil() {
MCRUtils.safeResolve(baseDir.getRoot().toPath(), evilDir.getRoot().toPath());
}
@Test
public final void testResolve() {
Path path = baseDir.getRoot().toPath();
Path resolve = MCRUtils.safeResolve(path, "foo", "bar");
Assert.assertEquals(path.resolve("foo").resolve("bar"), resolve);
}
}
| 3,074 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestCase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRTestCase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.URL;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.mycore.common.config.MCRConfigurationException;
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.Metadata.Type.test", string = "true")
})
public class MCRTestCase {
@ClassRule
public static TemporaryFolder junitFolder = new TemporaryFolder();
@Rule
public MCRTestAnnotationWatcher<MCRTestConfiguration> configurationTestWatcher
= new MCRTestAnnotationWatcher<>(MCRTestConfiguration.class);
@BeforeClass
public static void initBaseDir() throws IOException {
MCRTestCaseHelper.beforeClass(junitFolder);
}
/**
* Initializes {@link org.mycore.common.config.MCRConfiguration2} with an empty property file.
* This can be used to test MyCoRe classes without any properties set, using default. You may set specific
* properties for a test case by, in this order of precedence:
* <ol>
* <li>
* Annotating the test class (or its superclasses) with {{@link MCRTestConfiguration}}.
* </li>
* <li>
* Overwriting {@link MCRTestCase#getTestProperties()} in the test class.
* </li>
* <li>
* Annotating the test method with {{@link MCRTestConfiguration}}.
* </li>
* <li>
* Calling {@link org.mycore.common.config.MCRConfiguration2#set(String, String)} inside of the test method.
* </li>
* </ol>
*/
@Before
public void setUp() throws Exception {
initSystemProperties();
Map<String, String> testProperties = getCombinedTestProperties();
MCRTestCaseHelper.before(testProperties);
}
private Map<String, String> getCombinedTestProperties() {
Map<String, String> testProperties = new HashMap<>();
getClassLevelTestConfigurations().descendingIterator().forEachRemaining(
testConfiguration -> extendTestProperties(testProperties, testConfiguration));
testProperties.putAll(getTestProperties());
getMethodLevelTestConfiguration().ifPresent(
testConfiguration -> extendTestProperties(testProperties, testConfiguration));
return testProperties;
}
private Deque<MCRTestConfiguration> getClassLevelTestConfigurations() {
Deque<MCRTestConfiguration> testConfigurations = new ArrayDeque<>();
for (Class<?> t = this.getClass(); t != Object.class; t = t.getSuperclass()) {
Optional.ofNullable(t.getAnnotation(MCRTestConfiguration.class))
.ifPresent(testConfigurations::add);
}
return testConfigurations;
}
protected Map<String, String> getTestProperties() {
return new HashMap<>();
}
private Optional<MCRTestConfiguration> getMethodLevelTestConfiguration() {
return configurationTestWatcher.getAnnotation();
}
private void extendTestProperties(Map<String, String> testProperties, MCRTestConfiguration testConfiguration) {
Arrays.stream(testConfiguration.properties())
.forEach(testProperty -> extendTestProperties(testProperties, testProperty));
}
private static void extendTestProperties(Map<String, String> testProperties, MCRTestProperty testProperty) {
String stringValue = testProperty.string();
boolean nonDefaultString = !Objects.equals(stringValue, "");
Class<?> classNameOfValue = testProperty.classNameOf();
boolean nonDefaultClassNameOf = Void.class != classNameOfValue;
if (nonDefaultString && nonDefaultClassNameOf) {
throw new MCRConfigurationException("MCRTestProperty can have either a string- or a classNameOf-value");
} else if (nonDefaultString) {
testProperties.put(testProperty.key(), stringValue);
} else if (nonDefaultClassNameOf) {
testProperties.put(testProperty.key(), classNameOfValue.getName());
} else {
throw new MCRConfigurationException("MCRTestProperty must have either a string- or a classNameOf-value");
}
}
@After
public void tearDown() throws Exception {
MCRTestCaseHelper.after();
}
/**
* Creates a temporary properties file if the system variable MCR.Configuration.File is not set.
*
* @author Marcel Heusinger <marcel.heusinger[at]uni-due.de>
*/
protected void initSystemProperties() {
String currentComponent = getCurrentComponentName();
System.setProperty("MCRRuntimeComponentDetector.underTesting", currentComponent);
}
protected static String getCurrentComponentName() {
String userDir = System.getProperty("user.dir");
return Paths.get(userDir).getFileName().toString();
}
protected boolean isDebugEnabled() {
return false;
}
/**
* Waits 1,1 seconds and does nothing
*/
protected void bzzz() {
synchronized (this) {
try {
wait(1100);
} catch (InterruptedException e) {
}
}
}
/**
* Retrieve the resource file<br> Example: /Classname/recource.file
*
* @param fileName
* @return the resource file as InputStream
*/
protected InputStream getResourceAsStream(String fileName) {
String fileLocation = buildFileLocation(fileName);
System.out.println("File location: " + fileLocation);
return Class.class.getResourceAsStream(fileLocation);
}
/**
* Retrieve the resource file as URI. Example: /Classname/recource.file
*
* @param fileName
* @return the resource file as URL
*/
protected URL getResourceAsURL(String fileName) {
String fileLocation = buildFileLocation(fileName);
System.out.println("File location: " + fileLocation);
return getClass().getResource(fileLocation);
}
private String buildFileLocation(String fileName) {
return new MessageFormat("/{0}/{1}", Locale.ROOT).format(
new Object[] { this.getClass().getSimpleName(), fileName });
}
}
| 7,298 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRTestConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface MCRTestConfiguration {
MCRTestProperty[] properties();
}
| 1,134 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Table.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/Table.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.PrintStream;
import java.util.Vector;
public class Table {
private int currentCol;
private int[] colSize;
private int columns;
Vector<String> values;
public Table(int columns) {
currentCol = 0;
this.columns = columns;
colSize = new int[columns];
values = new Vector<>();
}
public void addValue(String value) {
if (value.length() > colSize[currentCol % columns]) {
colSize[currentCol % columns] = value.length();
}
values.add(value);
currentCol++;
}
public void print(PrintStream out) {
int rows = values.size() / columns;
StringBuilder sb = new StringBuilder();
for (int r = 0; r < rows; r++) {
sb.delete(0, sb.length() + 1);
for (int c = 0; c < columns; c++) {
String value = values.get(r * columns + c);
sb.append(" ".repeat(Math.max(0, colSize[c] - value.length() + 1)));
sb.append(value);
}
out.println(sb);
}
}
}
| 1,839 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestAnnotationWatcher.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRTestAnnotationWatcher.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.annotation.Annotation;
import java.util.Optional;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class MCRTestAnnotationWatcher<A extends Annotation> extends TestWatcher {
private final Class<A> annotationType;
private volatile A annotation;
public MCRTestAnnotationWatcher(Class<A> annotationType) {
this.annotationType = annotationType;
}
protected void starting(Description d) {
this.annotation = d.getAnnotation(annotationType);
}
public Optional<A> getAnnotation() {
return Optional.ofNullable(this.annotation);
}
}
| 1,390 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestCaseTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRTestCaseTest.java | package org.mycore.common;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.config.MCRConfiguration2;
@MCRTestConfiguration(properties = {
//overwrite property of MCRTestCase
@MCRTestProperty(key = "MCR.Metadata.Type.test", string = "false"),
//overwrite property of config/mycore.properties
@MCRTestProperty(key = "MCR.NameOfProject", string = MCRTestCaseTest.PROJECT_NAME)
})
public final class MCRTestCaseTest extends MCRTestCase {
final static String PROJECT_NAME = "MyCoRe Test";
@Test
public void testConfigAnnotationOverwrite() {
Assert.assertFalse(MCRConfiguration2.getBoolean("MCR.Metadata.Type.test").get());
}
@Test
public void testConfigPropertiesOverwrite() {
Assert.assertEquals(PROJECT_NAME, MCRConfiguration2.getStringOrThrow("MCR.NameOfProject"));
}
@Test
public void testConfigProperties() {
Assert.assertNotNull(MCRConfiguration2.getStringOrThrow("MCR.CommandLineInterface.SystemName"));
}
}
| 1,021 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestCaseHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRTestCaseHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.rules.TemporaryFolder;
import org.mycore.common.config.MCRComponent;
import org.mycore.common.config.MCRConfigurationBase;
import org.mycore.common.config.MCRConfigurationLoader;
import org.mycore.common.config.MCRConfigurationLoaderFactory;
import org.mycore.common.config.MCRRuntimeComponentDetector;
public class MCRTestCaseHelper {
public static void beforeClass(TemporaryFolder junitFolder) throws IOException {
if (System.getProperties().getProperty("MCR.Home") == null) {
File baseDir = junitFolder.newFolder("mcrhome");
System.out.println("Setting MCR.Home=" + baseDir.getAbsolutePath());
System.getProperties().setProperty("MCR.Home", baseDir.getAbsolutePath());
}
if (System.getProperties().getProperty("MCR.AppName") == null) {
String currentComponentName = getCurrentComponentName();
System.out.println("Setting MCR.AppName=" + currentComponentName);
System.getProperties().setProperty("MCR.AppName", getCurrentComponentName());
}
File configDir = new File(System.getProperties().getProperty("MCR.Home"),
System.getProperties().getProperty("MCR.AppName"));
System.out.println("Creating config directory: " + configDir);
configDir.mkdirs();
}
public static void before(Map<String, String> testProperties) {
String mcrComp = MCRRuntimeComponentDetector.getMyCoReComponents().stream().map(MCRComponent::toString).collect(
Collectors.joining(", "));
String appMod = MCRRuntimeComponentDetector.getApplicationModules()
.stream()
.map(MCRComponent::toString)
.collect(Collectors.joining(", "));
System.out.printf("MyCoRe components detected: %s\nApplications modules detected: %s\n",
mcrComp.isEmpty() ? "'none'" : mcrComp, appMod.isEmpty() ? "'none'" : appMod);
MCRConfigurationLoader configurationLoader = MCRConfigurationLoaderFactory.getConfigurationLoader();
HashMap<String, String> baseProperties = new HashMap<>(configurationLoader.load());
baseProperties.putAll(testProperties);
MCRConfigurationBase.initialize(configurationLoader.loadDeprecated(), baseProperties, true);
MCRSessionMgr.unlock();
}
public static void after() {
MCRConfigurationBase.initialize(Collections.emptyMap(), Collections.emptyMap(), true);
MCRSessionMgr.releaseCurrentSession();
}
public static String getCurrentComponentName() {
String userDir = System.getProperty("user.dir");
return Paths.get(userDir).getFileName().toString();
}
}
| 3,621 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPropertiesResolverTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRPropertiesResolverTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
import org.mycore.common.config.MCRConfiguration2;
public class MCRPropertiesResolverTest {
@Test
public void resolve() {
MCRConfiguration2.set("Sample.basedir", "/home/user/base");
MCRConfiguration2.set("Sample.subdir", "%Sample.basedir%/subdir");
MCRConfiguration2.set("Sample.file", "%Sample.subdir%/file.txt");
MCRPropertiesResolver resolver = new MCRPropertiesResolver(MCRConfiguration2.getPropertiesMap());
assertEquals("/home/user/base", resolver.resolve("%Sample.basedir%"));
assertEquals("/home/user/base/subdir", resolver.resolve("%Sample.subdir%"));
assertEquals("/home/user/base/subdir/file.txt", resolver.resolve("%Sample.file%"));
}
@Test
public void resolveAll() {
MCRConfiguration2.set("Sample.basedir", "/home/user/base");
MCRConfiguration2.set("Sample.subdir", "%Sample.basedir%/subdir");
MCRConfiguration2.set("Sample.file", "%Sample.subdir%/file.txt");
Map<String, String> p = MCRConfiguration2.getPropertiesMap();
MCRPropertiesResolver resolver = new MCRPropertiesResolver(p);
Map<String, String> resolvedProperties = resolver.resolveAll(p);
assertEquals("/home/user/base/subdir", resolvedProperties.get("Sample.subdir"));
assertEquals("/home/user/base/subdir/file.txt", resolvedProperties.get("Sample.file"));
}
@Test
public void selfReference() {
MCRConfiguration2.set("a", "%a%,hallo");
MCRConfiguration2.set("b", "hallo,%b%,welt");
MCRConfiguration2.set("c", "%b%,%a%");
Map<String, String> p = MCRConfiguration2.getPropertiesMap();
MCRPropertiesResolver resolver = new MCRPropertiesResolver(p);
assertEquals("hallo", resolver.resolve("%a%"));
assertEquals("hallo,welt", resolver.resolve("%b%"));
assertEquals("hallo,welt,hallo", resolver.resolve("%c%"));
}
}
| 2,757 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestProperty.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRTestProperty.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Target({})
@Retention(RetentionPolicy.RUNTIME)
public @interface MCRTestProperty {
String key();
String string() default "";
Class<?> classNameOf() default Void.class;
}
| 1,113 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTextResolverTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRTextResolverTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.Hashtable;
import org.junit.Test;
import org.mycore.common.MCRTextResolver.CircularDependencyExecption;
import org.mycore.common.MCRTextResolver.ResolveDepth;
import org.mycore.common.MCRTextResolver.Term;
public class MCRTextResolverTest extends MCRTestCase {
@Test
public void variables() {
Hashtable<String, String> variablesTable = new Hashtable<>();
variablesTable.put("f1", "v1");
variablesTable.put("f2", "v2");
variablesTable.put("f3", "v3");
variablesTable.put("f4", "v4 - {f1}");
variablesTable.put("f5", "[{f1}[_{e1}]]");
variablesTable.put("f6", "[[[[{f3}]]]]");
variablesTable.put("num", "10");
variablesTable.put("add", "5");
variablesTable.put("x_10_5", "value1");
variablesTable.put("x_10", "value2");
MCRTextResolver resolver = new MCRTextResolver(variablesTable);
// some simple variables tests
assertEquals("v1", resolver.resolve("{f1}"));
assertEquals("v2 & v3", resolver.resolve("{f2} & {f3}"));
// internal variables
assertEquals("v4 - v1", resolver.resolve("{f4}"));
// conditions
assertEquals("v1_v2", resolver.resolve("{f1}[_{f2}][_{e1}]"));
// internal conditions
assertEquals("", resolver.resolve("{f5}"));
// advanced condition tests
assertEquals("v3", resolver.resolve("{f6}"));
// escaping char test
assertEquals("[{v1}] \\", resolver.resolve("\\[\\{{f1}\\}\\] \\\\"));
// resolving variables in an other variable
assertEquals("value1", resolver.resolve("{x_{num}[_{add}]}"));
assertEquals("value2", resolver.resolve("{x_{num}[_{add2}]}"));
// uncompleted variable
assertEquals("{f1 v2", resolver.resolve("{f1 [{f2}]"));
}
@Test
public void addRemove() {
Hashtable<String, String> variablesTable = new Hashtable<>();
variablesTable.put("f1", "v1");
variablesTable.put("f2", "v2");
variablesTable.put("f3", "v3");
MCRTextResolver resolver = new MCRTextResolver(variablesTable);
resolver.addVariable("f4", "v4");
assertEquals("v1, v2, v3, v4", resolver.resolve("{f1}, {f2}, {f3}, {f4}"));
resolver.removeVariable("f2");
resolver.removeVariable("f3");
assertEquals("v1, v4", resolver.resolve("[{f1}][, {f2}][, {f3}][, {f4}]"));
assertEquals(true, resolver.containsVariable("f1"));
assertEquals(false, resolver.containsVariable("f2"));
}
@Test
public void resolveDepth() {
MCRTextResolver resolver = new MCRTextResolver();
resolver.addVariable("var1", "test1 & [{var2}]");
resolver.addVariable("var2", "test2");
assertEquals("test1 & test2", resolver.resolve("{var1}"));
resolver.setResolveDepth(ResolveDepth.NoVariables);
assertEquals("test1 & [{var2}]", resolver.resolve("{var1}"));
assertEquals(ResolveDepth.NoVariables, resolver.getResolveDepth());
}
@Test
public void terms() throws Exception {
MCRTextResolver resolver = new MCRTextResolver();
resolver.registerTerm(UppercaseTerm.class);
resolver.setRetainText(false);
resolver.addVariable("var1", "test");
assertEquals("Das ist ein TEST.", resolver.resolve("Das ist ein${ {var1}}$."));
resolver.unregisterTerm(UppercaseTerm.class);
assertEquals("Das ist ein$$.", resolver.resolve("Das ist ein${ {var1}}$."));
}
@Test
public void retainText() {
MCRTextResolver resolver = new MCRTextResolver();
assertEquals("Hello {variable}", resolver.resolve("Hello {variable}"));
resolver.setRetainText(false);
assertEquals("Hello ", resolver.resolve("Hello {variable}"));
}
@Test
public void circularDependency() {
MCRTextResolver resolver = new MCRTextResolver();
resolver.addVariable("a", "{b}");
resolver.addVariable("b", "{c}");
resolver.addVariable("c", "{a}");
try {
resolver.resolve("{a}");
} catch (CircularDependencyExecption cde) {
return;
}
assertFalse("No circular dependency occurred", true);
}
public static class UppercaseTerm extends Term {
public UppercaseTerm(MCRTextResolver textResolver) {
super(textResolver);
}
@Override
public String getEndEnclosingString() {
return "}$";
}
@Override
public String getStartEnclosingString() {
return "${";
}
@Override
protected boolean resolveInternal(String text, int pos) {
if (text.startsWith(getEndEnclosingString(), pos)) {
String value = termBuffer.toString().toUpperCase();
termBuffer = new StringBuffer(value);
return true;
}
char c = text.charAt(pos);
termBuffer.append(c);
return false;
}
}
}
| 5,888 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStreamUtilsTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRStreamUtilsTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
public class MCRStreamUtilsTest {
@Before
public void setUp() {
}
@Test
public void test() {
//see https://commons.wikimedia.org/wiki/File%3ASorted_binary_tree_preorder.svg for tree image
String[] nodes = { "F", "B", "A", "D", "C", "E", "G", "I", "H" };
HashMap<String, String[]> children = new HashMap<>();
children.put("F", new String[] { "B", "G" });
children.put("B", new String[] { "A", "D" });
children.put("D", new String[] { "C", "E" });
children.put("G", new String[] { "I" });
children.put("I", new String[] { "H" });
children.put("A", new String[0]);
children.put("C", new String[0]);
children.put("E", new String[0]);
children.put("H", new String[0]);
ArrayList<String> sortedNodes = new ArrayList<>(Arrays.asList(nodes));
sortedNodes.sort(String.CASE_INSENSITIVE_ORDER);
String[] nodesPreOrder = MCRStreamUtils
.flatten("F", ((Function<String, String[]>) children::get).andThen(Arrays::asList),
Collection::parallelStream)
.collect(Collectors.toList())
.toArray(new String[nodes.length]);
assertEquals("Node count differs", nodes.length, nodesPreOrder.length);
for (int i = 0; i < nodes.length; i++) {
assertEquals("unexpected node", nodes[i], nodesPreOrder[i]);
}
}
}
| 2,448 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSessionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRSessionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRSessionTest extends MCRTestCase {
private static final MCRSystemUserInformation SUPER_USER_INSTANCE = MCRSystemUserInformation.getSuperUserInstance();
private static final MCRSystemUserInformation GUEST_INSTANCE = MCRSystemUserInformation.getGuestInstance();
private MCRSession session;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
super.setUp();
this.session = new MCRSession();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
this.session.close();
super.tearDown();
}
@Test
public void testIsGuestDefault() {
assertEquals(GUEST_INSTANCE, session.getUserInformation());
}
@Test
public void loginSuperUser() {
session.setUserInformation(SUPER_USER_INSTANCE);
assertEquals(SUPER_USER_INSTANCE, session.getUserInformation());
}
@Test
public void downGradeUser() {
MCRUserInformation otherUser = getSimpleUserInformation("JUnit");
session.setUserInformation(SUPER_USER_INSTANCE);
session.setUserInformation(otherUser);
assertEquals(otherUser, session.getUserInformation());
session.setUserInformation(GUEST_INSTANCE);
assertEquals(GUEST_INSTANCE, session.getUserInformation());
}
@Test(expected = IllegalArgumentException.class)
public void upgradeFail() {
MCRUserInformation otherUser = getSimpleUserInformation("JUnit");
session.setUserInformation(otherUser);
session.setUserInformation(SUPER_USER_INSTANCE);
}
private static MCRUserInformation getSimpleUserInformation(String userID) {
return new MCRUserInformation() {
@Override
public boolean isUserInRole(String role) {
return false;
}
@Override
public String getUserID() {
return userID;
}
@Override
public String getUserAttribute(String attribute) {
return null;
}
};
}
}
| 3,076 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCoreVersionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/MCRCoreVersionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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 static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRCoreVersionTest extends MCRTestCase {
/**
* Test method for {@link org.mycore.common.MCRCoreVersion#getVersion()}.
*/
@Test
public void getVersion() {
assertTrue("Length of version string is zero.", MCRCoreVersion.getVersion().length() > 0);
}
/**
* Test method for {@link org.mycore.common.MCRCoreVersion#getRevision()}.
*/
@Test
public void getRevision() {
assertTrue("Revision is not a SHA1 hash: " + MCRCoreVersion.getRevision(),
MCRCoreVersion.getRevision().matches("[a-fA-F0-9]{40}"));
}
}
| 1,465 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserInformationLookupTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/log4j2/lookups/MCRUserInformationLookupTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.log4j2.lookups;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.junit.Test;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRTestCase;
import org.mycore.common.MCRUserInformation;
public class MCRUserInformationLookupTest extends MCRTestCase {
@Test
public final void testLookupString() {
MCRUserInformationLookup lookup = new MCRUserInformationLookup();
assertNull("User information should not be available", lookup.lookup("id"));
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
assertEquals(MCRSystemUserInformation.getGuestInstance().getUserID(), lookup.lookup("id"));
assertNull("Guest user should have no role", lookup.lookup("role:admin:editor:submitter"));
mcrSession.setUserInformation(new MCRUserInformation() {
@Override
public boolean isUserInRole(String role) {
return !role.startsWith("a");
}
@Override
public String getUserID() {
return "junit";
}
@Override
public String getUserAttribute(String attribute) {
return null;
}
});
String[] testRoles = { "admin", "editor", "submitter" };
String expRole = testRoles[1];
assertTrue("Current user should be in role " + expRole, mcrSession.getUserInformation().isUserInRole(expRole));
assertEquals(expRole,
lookup.lookup("role:" + Arrays.asList(testRoles).stream().collect(Collectors.joining(","))));
}
}
| 2,565 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurableInstanceHelperNestedTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRConfigurableInstanceHelperNestedTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.MCRTestConfiguration;
import org.mycore.common.MCRTestProperty;
import org.mycore.common.config.annotation.MCRInstance;
import org.mycore.common.config.annotation.MCRInstanceList;
import org.mycore.common.config.annotation.MCRInstanceMap;
import org.mycore.common.config.annotation.MCRProperty;
public class MCRConfigurableInstanceHelperNestedTest extends MCRTestCase {
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedClass.class),
@MCRTestProperty(key = "Foo.Nested", classNameOf = NestedClass.class),
@MCRTestProperty(key = "Foo.Nested.Property1", string = "Value1"),
@MCRTestProperty(key = "Foo.Nested.Property2", string = "Value2")
})
public void nested() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithNestedClass instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.nested);
assertEquals("Value1", instance.nested.string1);
assertEquals("Value2", instance.nested.string2);
}
@Test(expected = MCRConfigurationException.class)
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedClass.class),
})
public void nestedNotPresent() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
MCRConfigurableInstanceHelper.getInstance(configuration);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithOptionalNestedClass.class),
@MCRTestProperty(key = "Foo.Nested", classNameOf = NestedClass.class),
@MCRTestProperty(key = "Foo.Nested.Property1", string = "Value1"),
@MCRTestProperty(key = "Foo.Nested.Property2", string = "Value2")
})
public void nestedOptional() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithOptionalNestedClass instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.nested);
assertEquals("Value1", instance.nested.string1);
assertEquals("Value2", instance.nested.string2);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithOptionalNestedClass.class),
})
public void nestedOptionalNotPresent() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithOptionalNestedClass instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNull(instance.nested);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedNestedClass.class),
@MCRTestProperty(key = "Foo.Nested", classNameOf = TestClassWithNestedClass.class),
@MCRTestProperty(key = "Foo.Nested.Nested", classNameOf = NestedClass.class),
@MCRTestProperty(key = "Foo.Nested.Nested.Property1", string = "Value1"),
@MCRTestProperty(key = "Foo.Nested.Nested.Property2", string = "Value2")
})
public void nestedNested() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithNestedNestedClass instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.nested);
assertNotNull(instance.nested.nested);
assertEquals("Value1", instance.nested.nested.string1);
assertEquals("Value2", instance.nested.nested.string2);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedMap.class),
@MCRTestProperty(key = "Foo.EntryA", classNameOf = OneKindOfEntry.class),
@MCRTestProperty(key = "Foo.EntryA.OneProperty", string = "OneValue"),
@MCRTestProperty(key = "Foo.EntryB", classNameOf = OtherKindOfEntry.class),
@MCRTestProperty(key = "Foo.EntryB.OtherProperty", string = "OtherValue"),
})
public void nestedMap() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithNestedMap instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.map);
assertEquals(2, instance.map.size());
Entry oneEntry = instance.map.get("EntryA");
assertNotNull(oneEntry);
assertEquals(OneKindOfEntry.class, oneEntry.getClass());
assertEquals("OneValue", oneEntry.get());
Entry otherEntry = instance.map.get("EntryB");
assertNotNull(otherEntry);
assertEquals(OtherKindOfEntry.class, otherEntry.getClass());
assertEquals("OtherValue", otherEntry.get());
}
@Test(expected = MCRConfigurationException.class)
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedMap.class),
})
public void nestedMapNotPresent() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
MCRConfigurableInstanceHelper.getInstance(configuration);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithOptionalNestedMap.class),
@MCRTestProperty(key = "Foo.EntryA", classNameOf = OneKindOfEntry.class),
@MCRTestProperty(key = "Foo.EntryA.OneProperty", string = "OneValue"),
@MCRTestProperty(key = "Foo.EntryB", classNameOf = OtherKindOfEntry.class),
@MCRTestProperty(key = "Foo.EntryB.OtherProperty", string = "OtherValue"),
})
public void nestedOptionalMap() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithOptionalNestedMap instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.map);
assertEquals(2, instance.map.size());
Entry oneEntry = instance.map.get("EntryA");
assertNotNull(oneEntry);
assertEquals(OneKindOfEntry.class, oneEntry.getClass());
assertEquals("OneValue", oneEntry.get());
Entry otherEntry = instance.map.get("EntryB");
assertNotNull(otherEntry);
assertEquals(OtherKindOfEntry.class, otherEntry.getClass());
assertEquals("OtherValue", otherEntry.get());
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithOptionalNestedMap.class),
})
public void nestedOptionalMapNotPresent() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithOptionalNestedMap instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.map);
assertEquals(0, instance.map.size());
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedMapWithPrefix.class),
@MCRTestProperty(key = "Foo.Map1.Entry", classNameOf = OneKindOfEntry.class),
@MCRTestProperty(key = "Foo.Map1.Entry.OneProperty", string = "OneValue"),
@MCRTestProperty(key = "Foo.Map2.Entry", classNameOf = OtherKindOfEntry.class),
@MCRTestProperty(key = "Foo.Map2.Entry.OtherProperty", string = "OtherValue"),
})
public void nestedMapWithPrefix() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithNestedMapWithPrefix instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.map1);
assertNotNull(instance.map2);
assertEquals(1, instance.map1.size());
assertEquals(1, instance.map2.size());
Entry oneEntry = instance.map1.get("Entry");
assertNotNull(oneEntry);
assertEquals(OneKindOfEntry.class, oneEntry.getClass());
assertEquals("OneValue", oneEntry.get());
Entry otherEntry = instance.map2.get("Entry");
assertNotNull(otherEntry);
assertEquals(OtherKindOfEntry.class, otherEntry.getClass());
assertEquals("OtherValue", otherEntry.get());
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedList.class),
@MCRTestProperty(key = "Foo.23", classNameOf = OneKindOfEntry.class),
@MCRTestProperty(key = "Foo.23.OneProperty", string = "OneValue"),
@MCRTestProperty(key = "Foo.42", classNameOf = OtherKindOfEntry.class),
@MCRTestProperty(key = "Foo.42.OtherProperty", string = "OtherValue"),
})
public void nestedList() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithNestedList instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.list);
assertEquals(2, instance.list.size());
Entry oneEntry = instance.list.get(0);
assertNotNull(oneEntry);
assertEquals(OneKindOfEntry.class, oneEntry.getClass());
assertEquals("OneValue", oneEntry.get());
Entry otherEntry = instance.list.get(1);
assertNotNull(otherEntry);
assertEquals(OtherKindOfEntry.class, otherEntry.getClass());
assertEquals("OtherValue", otherEntry.get());
}
@Test(expected = MCRConfigurationException.class)
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedList.class),
})
public void nestedListNotPresent() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
MCRConfigurableInstanceHelper.getInstance(configuration);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithOptionalNestedList.class),
@MCRTestProperty(key = "Foo.23", classNameOf = OneKindOfEntry.class),
@MCRTestProperty(key = "Foo.23.OneProperty", string = "OneValue"),
@MCRTestProperty(key = "Foo.42", classNameOf = OtherKindOfEntry.class),
@MCRTestProperty(key = "Foo.42.OtherProperty", string = "OtherValue"),
})
public void nestedOptionalList() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithOptionalNestedList instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.list);
assertEquals(2, instance.list.size());
Entry oneEntry = instance.list.get(0);
assertNotNull(oneEntry);
assertEquals(OneKindOfEntry.class, oneEntry.getClass());
assertEquals("OneValue", oneEntry.get());
Entry otherEntry = instance.list.get(1);
assertNotNull(otherEntry);
assertEquals(OtherKindOfEntry.class, otherEntry.getClass());
assertEquals("OtherValue", otherEntry.get());
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithOptionalNestedList.class),
})
public void nestedOptionalListNotPresent() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithOptionalNestedList instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.list);
assertEquals(0, instance.list.size());
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithNestedListWithPrefix.class),
@MCRTestProperty(key = "Foo.List1.23", classNameOf = OneKindOfEntry.class),
@MCRTestProperty(key = "Foo.List1.23.OneProperty", string = "OneValue"),
@MCRTestProperty(key = "Foo.List2.23", classNameOf = OtherKindOfEntry.class),
@MCRTestProperty(key = "Foo.List2.23.OtherProperty", string = "OtherValue"),
})
public void nestedListWithPrefix() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithNestedListWithPrefix instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertNotNull(instance.list1);
assertNotNull(instance.list2);
assertEquals(1, instance.list1.size());
assertEquals(1, instance.list2.size());
Entry oneEntry = instance.list1.get(0);
assertNotNull(oneEntry);
assertEquals(OneKindOfEntry.class, oneEntry.getClass());
assertEquals("OneValue", oneEntry.get());
Entry otherEntry = instance.list2.get(0);
assertNotNull(otherEntry);
assertEquals(OtherKindOfEntry.class, otherEntry.getClass());
assertEquals("OtherValue", otherEntry.get());
}
public static class NestedClass {
@MCRProperty(name = "Property1")
public String string1;
@MCRProperty(name = "Property2")
public String string2;
}
public static class TestClassWithNestedClass {
@MCRInstance(name = "Nested", valueClass = NestedClass.class)
public NestedClass nested;
}
public static class TestClassWithOptionalNestedClass {
@MCRInstance(name = "Nested", valueClass = NestedClass.class, required = false)
public NestedClass nested;
}
public static class TestClassWithNestedNestedClass {
@MCRInstance(name = "Nested", valueClass = TestClassWithNestedClass.class)
public TestClassWithNestedClass nested;
}
public static abstract class Entry {
public abstract String get();
}
public static class OneKindOfEntry extends Entry {
@MCRProperty(name = "OneProperty")
public String string;
@Override
public String get() {
return string;
}
}
public static class OtherKindOfEntry extends Entry {
@MCRProperty(name = "OtherProperty")
public String string;
@Override
public String get() {
return string;
}
}
public static class TestClassWithNestedMap {
@MCRInstanceMap(valueClass = Entry.class)
public Map<String, Entry> map;
}
public static class TestClassWithOptionalNestedMap {
@MCRInstanceMap(valueClass = Entry.class, required = false)
public Map<String, Entry> map;
}
public static class TestClassWithNestedMapWithPrefix {
@MCRInstanceMap(name = "Map1", valueClass = Entry.class)
public Map<String, Entry> map1;
@MCRInstanceMap(name = "Map2", valueClass = Entry.class)
public Map<String, Entry> map2;
}
public static class TestClassWithNestedList {
@MCRInstanceList(valueClass = Entry.class)
public List<Entry> list;
}
public static class TestClassWithOptionalNestedList {
@MCRInstanceList(valueClass = Entry.class, required = false)
public List<Entry> list;
}
public static class TestClassWithNestedListWithPrefix {
@MCRInstanceList(name = "List1", valueClass = Entry.class)
public List<Entry> list1;
@MCRInstanceList(name = "List2", valueClass = Entry.class)
public List<Entry> list2;
}
}
| 17,159 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInstanceNameTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRInstanceNameTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
public class MCRInstanceNameTest extends MCRTestCase {
@Test
public void nameWithoutSuffix() {
MCRInstanceName name = MCRInstanceName.of("Foo.Bar");
assertEquals("Foo.Bar", name.actual());
assertEquals("Foo.Bar", name.canonical());
assertEquals(MCRInstanceName.Suffix.NONE, name.suffix());
}
@Test
public void subNameWithoutSuffix() {
MCRInstanceName name = MCRInstanceName.of("Foo.Bar").subName("Baz");
assertEquals("Foo.Bar.Baz", name.actual());
assertEquals("Foo.Bar.Baz", name.canonical());
assertEquals(MCRInstanceName.Suffix.NONE, name.suffix());
}
@Test
public void nameWithUpperCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("Foo.Bar.Class");
assertEquals("Foo.Bar.Class", name.actual());
assertEquals("Foo.Bar", name.canonical());
assertEquals(MCRInstanceName.Suffix.UPPER_CASE, name.suffix());
}
@Test
public void subNameWithUpperCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("Foo.Bar.Class").subName("Baz");
assertEquals("Foo.Bar.Baz.Class", name.actual());
assertEquals("Foo.Bar.Baz", name.canonical());
assertEquals(MCRInstanceName.Suffix.UPPER_CASE, name.suffix());
}
@Test
public void nameWithLowerCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("Foo.Bar.class");
assertEquals("Foo.Bar.class", name.actual());
assertEquals("Foo.Bar", name.canonical());
assertEquals(MCRInstanceName.Suffix.LOWER_CASE, name.suffix());
}
@Test
public void subNameWithLowerCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("Foo.Bar.class").subName("Baz");
assertEquals("Foo.Bar.Baz.class", name.actual());
assertEquals("Foo.Bar.Baz", name.canonical());
assertEquals(MCRInstanceName.Suffix.LOWER_CASE, name.suffix());
}
@Test
public void emptyNameWithoutSuffix() {
MCRInstanceName name = MCRInstanceName.of("");
assertEquals("", name.actual());
assertEquals("", name.canonical());
assertEquals(MCRInstanceName.Suffix.NONE, name.suffix());
}
@Test
public void subEmptyNameWithoutSuffix() {
MCRInstanceName name = MCRInstanceName.of("").subName("Baz");
assertEquals("Baz", name.actual());
assertEquals("Baz", name.canonical());
assertEquals(MCRInstanceName.Suffix.NONE, name.suffix());
}
@Test
public void emptyNameWithUpperCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("Class");
assertEquals("Class", name.actual());
assertEquals("", name.canonical());
assertEquals(MCRInstanceName.Suffix.UPPER_CASE, name.suffix());
}
@Test
public void subEmptyNameWithUpperCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("Class").subName("Baz");
assertEquals("Baz.Class", name.actual());
assertEquals("Baz", name.canonical());
assertEquals(MCRInstanceName.Suffix.UPPER_CASE, name.suffix());
}
@Test
public void emptyNameWithLowerCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("class");
assertEquals("class", name.actual());
assertEquals("", name.canonical());
assertEquals(MCRInstanceName.Suffix.LOWER_CASE, name.suffix());
}
@Test
public void subEmptyNameWithLowerCaseSuffix() {
MCRInstanceName name = MCRInstanceName.of("class").subName("Baz");
assertEquals("Baz.class", name.actual());
assertEquals("Baz", name.canonical());
assertEquals(MCRInstanceName.Suffix.LOWER_CASE, name.suffix());
}
}
| 4,588 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurableInstanceHelperConfigTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRConfigurableInstanceHelperConfigTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.annotation.MCRPostConstruction;
import org.mycore.common.config.annotation.MCRProperty;
public class MCRConfigurableInstanceHelperConfigTest extends MCRTestCase {
public static final String INSTANCE_NAME_PREFIX = "MCR.CIH.";
private static final String INSTANCE_1_NAME = INSTANCE_NAME_PREFIX + "Test1";
private static final String INSTANCE_2_NAME = INSTANCE_NAME_PREFIX + "Test2";
private static final String DEFAULT_KEY = "DefaultKey";
private static final String DEFAULT_VALUE = "DefaultValue";
private static final String ASSIGNED_KEY = "AssignedKey";
private static final String ASSIGNED_VALUE = "AssignedValue";
private static final String UNASSIGNED_KEY = "UnassignedKey";
private static final String KEY_REQUIRED_FIELD = "KeyRequiredField";
private static final String VALUE_REQUIRED_FIELD = "ValueRequiredField";
private static final String KEY_REQUIRED_FIELD_WITH_DEFAULT = "KeyRequiredFieldWithDefault";
private static final String KEY_ABSENT_OPTIONAL_FIELD = "KeyAbsentOptionalField";
private static final String KEY_PRESENT_OPTIONAL_FIELD = "KeyPresentOptionalField";
private static final String VALUE_PRESENT_OPTIONAL_FIELD = "ValuePresentOptionalField";
private static final String KEY_ABSENT_OPTIONAL_FIELD_WITH_DEFAULT = "KeyAbsentOptionalFieldWithDefault";
private static final String KEY_PRESENT_OPTIONAL_FIELD_WITH_DEFAULT = "KeyPresentOptionalFieldWithDefault";
private static final String VALUE_PRESENT_OPTIONAL_FIELD_WITH_DEFAULT = "ValuePresentOptionalFieldWithDefault";
private static final String KEY_ABSOLUTE_FIELD = "KeyAbsoluteField";
private static final String VALUE_ABSOLUTE_FIELD = "ValueAbsoluteField";
private static final String KEY_REQUIRED_METHOD = "KeyRequiredMethod";
private static final String VALUE_REQUIRED_METHOD = "ValueRequiredMethod";
private static final String KEY_REQUIRED_METHOD_WITH_DEFAULT = "KeyRequiredMethodWithDefault";
private static final String KEY_ABSENT_OPTIONAL_METHOD = "KeyAbsentOptionalMethod";
private static final String KEY_PRESENT_OPTIONAL_METHOD = "KeyPresentOptionalMethod";
private static final String VALUE_PRESENT_OPTIONAL_METHOD = "ValuePresentOptionalMethod";
private static final String KEY_ABSENT_OPTIONAL_METHOD_WITH_DEFAULT = "KeyAbsentOptionalMethodWithDefault";
private static final String KEY_PRESENT_OPTIONAL_METHOD_DEFAULT = "KeyPresentOptionalMethodWithDefault";
private static final String VALUE_PRESENT_OPTIONAL_METHOD_DEFAULT = "ValuePresentOptionalMethodWithDefault";
private static final String KEY_ABSOLUTE_METHOD = "KeyAbsoluteMethod";
private static final String VALUE_ABSOLUTE_METHOD = "ValueAbsoluteMethod";
private static final String KEY_CONVERTING_METHOD = "KeyConvertingMethod";
private static final String VALUE_CONVERTING_METHOD = "ValueConvertingMethod";
private static final String KEY_ORDERED_METHOD = "KeyOrderedMethod";
private static final String VALUE_ORDERED_METHOD = "ValueOrderedMethod";
private static final String KEY_ORDERED_METHOD_1 = "KeyOrderedMethod1";
private static final String VALUE_ORDERED_METHOD_1 = "ValueOrderedMethod1";
private static final String KEY_ORDERED_METHOD_2 = "KeyOrderedMethod2";
private static final String VALUE_ORDERED_METHOD_2 = "ValueOrderedMethod2";
public static final List<String> VALUES_ORDERED_METHOD = Arrays.asList(
VALUE_ORDERED_METHOD,
VALUE_ORDERED_METHOD_1,
VALUE_ORDERED_METHOD_2);
private static final String VALUE_ORDERED_POST_CONSTRUCTION = "ValueOrderedPostConstruction";
private static final String VALUE_ORDERED_POST_CONSTRUCTION_1 = "ValueOrderedPostConstruction1";
private static final String VALUE_ORDERED_POST_CONSTRUCTION_2 = "ValueOrderedPostConstruction2";
public static final List<String> VALUES_ORDERED_POST_CONSTRUCTION = Arrays.asList(
VALUE_ORDERED_POST_CONSTRUCTION,
VALUE_ORDERED_POST_CONSTRUCTION_1,
VALUE_ORDERED_POST_CONSTRUCTION_2);
public static final List<String> VALUES_ORDERED_OVERALL = Stream.concat(
VALUES_ORDERED_METHOD.stream(),
VALUES_ORDERED_POST_CONSTRUCTION.stream()).toList();
@Test
public void test() {
Map<String, ?> instances = MCRConfiguration2.getInstances(INSTANCE_NAME_PREFIX);
assertEquals("Except two instances!", 2, instances.size());
testInstance(INSTANCE_1_NAME, false);
testInstance(INSTANCE_2_NAME, true);
}
private void testInstance(String instanceName, boolean withClassSuffix) {
String fullInstanceName = withClassSuffix(instanceName, withClassSuffix);
List<String> list = MCRConfiguration2.getInstantiatablePropertyKeys(fullInstanceName).toList();
assertTrue("Properties should contain " + instanceName, list.contains(fullInstanceName));
Optional<ConfigurableTestInstance> instance = MCRConfigurableInstanceHelper.getInstance(fullInstanceName);
assertTrue("Test " + fullInstanceName + " should be present", instance.isPresent());
validateFields(instance.get());
validateMethods(instance.get());
validatePostConstruction(instance.get(), fullInstanceName);
}
void validateFields(ConfigurableTestInstance instance) {
assertTrue("The map field should contain the assigned test key",
instance.map.containsKey(ASSIGNED_KEY));
assertEquals("The assigned test property should be present in map field",
ASSIGNED_VALUE, instance.map.get(ASSIGNED_KEY));
assertFalse("The unassigned test property should not be present in map field",
instance.map.containsKey(UNASSIGNED_KEY));
assertEquals("The required field should match",
VALUE_REQUIRED_FIELD, instance.required);
assertEquals("The required field with default should match",
DEFAULT_VALUE, instance.requiredWithDefault);
assertNull("The absent optional field should be null",
instance.absentOptional);
assertEquals("The present optional field should match",
VALUE_PRESENT_OPTIONAL_FIELD, instance.presentOptional);
assertEquals("The absent optional field with default should match",
DEFAULT_VALUE, instance.absentOptionalWithDefault);
assertEquals("The present optional field with default should match",
VALUE_PRESENT_OPTIONAL_FIELD_WITH_DEFAULT, instance.presentOptionalWithDefault);
assertEquals("The absolute field should match",
VALUE_ABSOLUTE_FIELD, instance.absolute);
}
void validateMethods(ConfigurableTestInstance instance) {
assertTrue("The map method value should contain the assigned test key",
instance.getMap().containsKey(ASSIGNED_KEY));
assertEquals("The assigned test property should be present in map method value",
ASSIGNED_VALUE, instance.getMap().get(ASSIGNED_KEY));
assertFalse("The unassigned test property should not be present in map method value",
instance.getMap().containsKey(UNASSIGNED_KEY));
assertEquals("The required method value should match",
VALUE_REQUIRED_METHOD, instance.getRequired());
assertEquals("The required method value with default should match",
DEFAULT_VALUE, instance.getRequiredWithDefault());
assertNull("The absent optional method value should be null",
instance.getAbsentOptional());
assertEquals("The present optional method value should match",
VALUE_PRESENT_OPTIONAL_METHOD, instance.getPresentOptional());
assertEquals("The absent optional method value with default should match",
DEFAULT_VALUE, instance.getAbsentOptionalWithDefault());
assertEquals("The present optional method value with default should match",
VALUE_PRESENT_OPTIONAL_METHOD_DEFAULT, instance.getPresentOptionalWithDefault());
assertEquals("The absolute method value should match",
VALUE_ABSOLUTE_METHOD, instance.getAbsolute());
assertEquals("The converting method value should match",
VALUE_CONVERTING_METHOD.length(), instance.getConverting());
assertEquals("The ordered method values should match",
VALUES_ORDERED_METHOD, instance.getOrderedMethodValues());
}
void validatePostConstruction(ConfigurableTestInstance instance, String fullInstanceName) {
assertEquals("Post construction value should match",
fullInstanceName, instance.postConstructionProperty);
assertEquals("The ordered post construction values should match",
VALUES_ORDERED_POST_CONSTRUCTION, instance.getOrderedPostConstructionValues());
assertEquals("The ordered method and post construction values should match",
VALUES_ORDERED_OVERALL, instance.getOrderedOverallValues());
}
@Override
protected Map<String, String> getTestProperties() {
final Map<String, String> testProperties = super.getTestProperties();
testProperties.put(DEFAULT_KEY, DEFAULT_VALUE);
testProperties.put(KEY_ABSOLUTE_FIELD, VALUE_ABSOLUTE_FIELD);
testProperties.put(KEY_ABSOLUTE_METHOD, VALUE_ABSOLUTE_METHOD);
configureInstance(testProperties, INSTANCE_1_NAME, false);
configureInstance(testProperties, INSTANCE_2_NAME, true);
return testProperties;
}
private void configureInstance(Map<String, String> testProperties, String instanceName, boolean withClassSuffix) {
String fullInstanceName = withClassSuffix(instanceName, withClassSuffix);
testProperties.put(fullInstanceName, ConfigurableTestInstance.class.getName());
testProperties.put(instanceName + "." + ASSIGNED_KEY, ASSIGNED_VALUE);
testProperties.put(instanceName + "." + KEY_REQUIRED_FIELD, VALUE_REQUIRED_FIELD);
testProperties.put(instanceName + "." + KEY_PRESENT_OPTIONAL_FIELD, VALUE_PRESENT_OPTIONAL_FIELD);
testProperties.put(instanceName + "." + KEY_PRESENT_OPTIONAL_FIELD_WITH_DEFAULT,
VALUE_PRESENT_OPTIONAL_FIELD_WITH_DEFAULT);
testProperties.put(instanceName + "." + KEY_REQUIRED_METHOD, VALUE_REQUIRED_METHOD);
testProperties.put(instanceName + "." + KEY_PRESENT_OPTIONAL_METHOD, VALUE_PRESENT_OPTIONAL_METHOD);
testProperties.put(instanceName + "." + KEY_PRESENT_OPTIONAL_METHOD_DEFAULT,
VALUE_PRESENT_OPTIONAL_METHOD_DEFAULT);
testProperties.put(instanceName + "." + KEY_CONVERTING_METHOD, VALUE_CONVERTING_METHOD);
testProperties.put(instanceName + "." + KEY_ORDERED_METHOD, VALUE_ORDERED_METHOD);
testProperties.put(instanceName + "." + KEY_ORDERED_METHOD_1, VALUE_ORDERED_METHOD_1);
testProperties.put(instanceName + "." + KEY_ORDERED_METHOD_2, VALUE_ORDERED_METHOD_2);
}
private String withClassSuffix(String instanceName, boolean withClassSuffix) {
return instanceName + (withClassSuffix ? ".Class" : "");
}
public static class ConfigurableTestInstance {
@MCRProperty(name = "*")
public Map<String, String> map;
@MCRProperty(name = KEY_REQUIRED_FIELD)
public String required;
@MCRProperty(name = KEY_REQUIRED_FIELD_WITH_DEFAULT, defaultName = DEFAULT_KEY)
public String requiredWithDefault;
@MCRProperty(name = KEY_ABSENT_OPTIONAL_FIELD, required = false)
public String absentOptional;
@MCRProperty(name = KEY_PRESENT_OPTIONAL_FIELD, required = false)
public String presentOptional;
@MCRProperty(name = KEY_ABSENT_OPTIONAL_FIELD_WITH_DEFAULT, defaultName = DEFAULT_KEY, required = false)
public String absentOptionalWithDefault;
@MCRProperty(name = KEY_PRESENT_OPTIONAL_FIELD_WITH_DEFAULT, defaultName = DEFAULT_KEY, required = false)
public String presentOptionalWithDefault;
@MCRProperty(name = KEY_ABSOLUTE_FIELD, absolute = true)
public String absolute;
private Map<String, String> mapMethodValue;
private String requiredMethodValue;
private String requiredMethodValueWithDefault;
private String absentOptionalMethodValue;
private String presentOptionalMethodValue;
private String absentOptionalMethodValueWithDefault;
private String presentOptionalMethodValueWithDefault;
private String absoluteMethodValue;
private int convertingMethodValue;
private final List<String> orderedMethodValues = new ArrayList<>(3);
public String postConstructionProperty;
private final List<String> orderedPostConstructionValues = new ArrayList<>(3);
private final List<String> orderedOverallValues = new ArrayList<>(6);
public Map<String, String> getMap() {
return mapMethodValue;
}
@MCRProperty(name = "*")
public void setMap(Map<String, String> mapValue) {
this.mapMethodValue = mapValue;
}
public String getRequired() {
return requiredMethodValue;
}
@MCRProperty(name = KEY_REQUIRED_METHOD)
public void setRequired(String requiredValue) {
this.requiredMethodValue = requiredValue;
}
public String getRequiredWithDefault() {
return requiredMethodValueWithDefault;
}
@MCRProperty(name = KEY_REQUIRED_METHOD_WITH_DEFAULT, defaultName = DEFAULT_KEY)
public void setRequiredWithDefault(String requiredValueWithDefault) {
this.requiredMethodValueWithDefault = requiredValueWithDefault;
}
public String getAbsentOptional() {
return absentOptionalMethodValue;
}
@MCRProperty(name = KEY_ABSENT_OPTIONAL_METHOD, required = false)
public void setAbsentOptional(String absentOptionalValue) {
this.absentOptionalMethodValue = absentOptionalValue;
}
public String getPresentOptional() {
return presentOptionalMethodValue;
}
@MCRProperty(name = KEY_PRESENT_OPTIONAL_METHOD, required = false)
public void setOPresentOptional(String presentOptionalValue) {
this.presentOptionalMethodValue = presentOptionalValue;
}
public String getAbsentOptionalWithDefault() {
return absentOptionalMethodValueWithDefault;
}
@MCRProperty(name = KEY_ABSENT_OPTIONAL_METHOD_WITH_DEFAULT, defaultName = DEFAULT_KEY, required = false)
public void setAbsentOptionalWithDefault(String absentOptionalValueWithDefault) {
this.absentOptionalMethodValueWithDefault = absentOptionalValueWithDefault;
}
public String getPresentOptionalWithDefault() {
return presentOptionalMethodValueWithDefault;
}
@MCRProperty(name = KEY_PRESENT_OPTIONAL_METHOD_DEFAULT, defaultName = DEFAULT_KEY, required = false)
public void setPresentOptionalWithDefault(String presentOptionalValueWithDefault) {
this.presentOptionalMethodValueWithDefault = presentOptionalValueWithDefault;
}
public String getAbsolute() {
return absoluteMethodValue;
}
@MCRProperty(name = KEY_ABSOLUTE_METHOD, absolute = true)
public void setAbsolute(String absoluteValue) {
this.absoluteMethodValue = absoluteValue;
}
public int getConverting() {
return convertingMethodValue;
}
@MCRProperty(name = KEY_CONVERTING_METHOD)
public void setConverting(String convertingValue) {
this.convertingMethodValue = convertingValue.length();
}
@MCRProperty(name = KEY_ORDERED_METHOD_2, order = 2)
public void setOrdered2(String orderedValue) {
addOrdered(orderedValue);
}
@MCRProperty(name = KEY_ORDERED_METHOD_1, order = 1)
public void setOrdered1(String orderedValue) {
addOrdered(orderedValue);
}
@MCRProperty(name = KEY_ORDERED_METHOD)
public void setOrdered(String orderedValue) {
addOrdered(orderedValue);
}
private void addOrdered(String orderedValue) {
this.orderedMethodValues.add(orderedValue);
this.orderedOverallValues.add(orderedValue);
}
public List<String> getOrderedMethodValues() {
return orderedMethodValues;
}
@MCRPostConstruction
public void callPostConstruction(String property) throws MCRConfigurationException {
postConstructionProperty = property;
}
@MCRPostConstruction(order = 2)
public void callPostConstructionOrdered2() {
addPostConstructionOrdered(VALUE_ORDERED_POST_CONSTRUCTION_2);
}
@MCRPostConstruction(order = 1)
public void callPostConstructionOrdered1() {
addPostConstructionOrdered(VALUE_ORDERED_POST_CONSTRUCTION_1);
}
@MCRPostConstruction
public void callPostConstructionOrdered() {
addPostConstructionOrdered(VALUE_ORDERED_POST_CONSTRUCTION);
}
private void addPostConstructionOrdered(String ordered) {
this.orderedPostConstructionValues.add(ordered);
this.orderedOverallValues.add(ordered);
}
public List<String> getOrderedPostConstructionValues() {
return orderedPostConstructionValues;
}
public List<String> getOrderedOverallValues() {
return orderedOverallValues;
}
}
}
| 18,877 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRConfigurationTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.singletoncollision.MCRConfigurationSingletonCollisionClassA;
import org.mycore.common.config.singletoncollision.MCRConfigurationSingletonCollisionClassB;
/**
* @author Thomas Scheffler (yagee)
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCRConfigurationTest extends MCRTestCase {
public static final String COLLISION_PROPERTY_NAME = "MCR.Configuration.SingletonCollision.PropertyName";
@Test(expected = MCRConfigurationException.class)
public final void testDeprecatedProperties() {
String deprecatedProperty = "MCR.Editor.FileUpload.MaxSize";
MCRConfiguration2.getString(deprecatedProperty);
}
/**
* Generate a Singleton Collision and see if it gets correctly resolved.
* It is limited to 1 minute in case of a recursive operation.
* <p>This checks for the Bug MCR-2806 - Singleton Recursive Update
*
* @author Tobias Lenhardt [Hammer1279]
*/
@Test(timeout = 3600) // 1 minute
public final void testSingletonCollision() {
Pair<String, String> properties = createConflictConfiguration();
Object objectA = MCRConfiguration2.getSingleInstanceOf(properties.getLeft()).orElseThrow();
Object objectB = MCRConfigurationSingletonCollisionClassA.COLLISION_CLASS_B;
assertTrue("Wrong or no class loaded!", objectA instanceof MCRConfigurationSingletonCollisionClassA);
assertTrue("Wrong or no class loaded!", objectB instanceof MCRConfigurationSingletonCollisionClassB);
}
/**
* <p>MCR-2827 check for correct get behavior</p>
* Reuses the collision mapping created for {@link #testSingletonCollision}, so if it fails this is also likely to
* fail.
*
* @author Tobias Lenhardt [Hammer1279]
*/
@Test
public final void testSingletonMapGet() {
Pair<String, String> properties = createConflictConfiguration();
String propertyA = properties.getLeft();
String propertyB = properties.getRight();
String classNameA = MCRConfiguration2.getStringOrThrow(propertyA);
String classNameB = MCRConfiguration2.getStringOrThrow(propertyB);
MCRConfiguration2.getSingleInstanceOf(propertyA).orElseThrow();
assertNotNull(
MCRConfiguration2.instanceHolder.get(new MCRConfiguration2.ConfigSingletonKey(propertyA, classNameA)));
assertNotNull(
MCRConfiguration2.instanceHolder.get(new MCRConfiguration2.ConfigSingletonKey(propertyB, classNameB)));
}
private Pair<String, String> createConflictConfiguration() {
char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();
int limit = 50; // initial size of char arrays
String classNameA = MCRConfigurationSingletonCollisionClassA.class.getName();
String classNameB = MCRConfigurationSingletonCollisionClassB.class.getName();
char[] propertyCharsA = new char[limit];
char[] propertyCharsB = new char[limit];
String propertyA;
String propertyB;
int a;
int b;
int i = 0;
// Generate Conflict
do {
// resize arrays when full
if (i == limit) {
limit = limit * 2;
propertyCharsA = Arrays.copyOf(propertyCharsA, limit);
propertyCharsB = Arrays.copyOf(propertyCharsB, limit);
}
// Generate Random Text
propertyCharsA[i] = letters[(int) (Math.random() * letters.length)];
propertyCharsB[i] = letters[(int) (Math.random() * letters.length)];
/*
* Calculate Slot placement in Map
*
* 1. Step: create a SingletonKey and get its hashCode
* 2. Step: Spread Bits
* 3. Step: get Map slot via Bitwise AND
*
* The 15 here is not a magic number.
* It is to do the calculation assuming we got a size 16 ConcurrentHashMap.
* Usually right after start, it won't be above this size.
* Size 16 is the default size for a ConcurrentHashMap.
*/
propertyA = toSuitableString(propertyCharsA);
a = new MCRConfiguration2.ConfigSingletonKey(propertyA, classNameA).hashCode();
a = spread(a);
a = 15 & a;
propertyB = toSuitableString(propertyCharsB);
b = new MCRConfiguration2.ConfigSingletonKey(propertyB, classNameB).hashCode();
b = spread(b);
b = 15 & b;
i++;
} while (a != b);
LogManager.getLogger().info("Colliding Strings:");
LogManager.getLogger().info(classNameA + " " + propertyA + " => " + a);
LogManager.getLogger().info(classNameB + " " + propertyB + " => " + b);
MCRConfiguration2.set(propertyA, classNameA);
MCRConfiguration2.set(propertyB, classNameB);
MCRConfiguration2.set(COLLISION_PROPERTY_NAME, propertyB);
return Pair.of(propertyA, propertyB);
}
/**
* Internal Method of {@link java.util.concurrent.ConcurrentHashMap}.
*
* @see {@link java.util.concurrent.ConcurrentHashMap#spread(int)}
*/
private int spread(int h) {
return (h ^ (h >>> 16)) & 0x7fffffff /* all usable bits */;
}
private static String toSuitableString(char[] value) {
return String.valueOf(value).trim().replaceAll("\\s+", "");
}
}
| 6,474 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurableInstanceHelperProxyTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRConfigurableInstanceHelperProxyTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.function.Supplier;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.MCRTestConfiguration;
import org.mycore.common.MCRTestProperty;
import org.mycore.common.config.annotation.MCRConfigurationProxy;
import org.mycore.common.config.annotation.MCRProperty;
public class MCRConfigurableInstanceHelperProxyTest extends MCRTestCase {
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithConfigurationProxy.class),
@MCRTestProperty(key = "Foo.Property1", string = "Value1"),
@MCRTestProperty(key = "Foo.Property2", string = "Value2")
})
public void annotated() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithConfigurationProxy instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
assertEquals("Value1-Value2", instance.value());
}
@MCRConfigurationProxy(proxyClass = TestClassWithConfigurationProxy.Factory.class)
public static class TestClassWithConfigurationProxy {
private final String value;
public TestClassWithConfigurationProxy(String value) {
this.value = value;
}
public String value() {
return value;
}
public static class Factory implements Supplier<TestClassWithConfigurationProxy> {
@MCRProperty(name = "Property1")
public String value1;
@MCRProperty(name = "Property2")
public String value2;
@Override
public TestClassWithConfigurationProxy get() {
return new TestClassWithConfigurationProxy(value1 + "-" + value2);
}
}
}
}
| 2,686 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurableInstanceHelperBasicTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRConfigurableInstanceHelperBasicTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertNotNull;
import java.util.function.Supplier;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.MCRTestConfiguration;
import org.mycore.common.MCRTestProperty;
import org.mycore.common.config.annotation.MCRConfigurationProxy;
public class MCRConfigurableInstanceHelperBasicTest extends MCRTestCase {
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithConstructor.class)
})
public void constructorFactory() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithConstructor instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithFactory.class)
})
public void factory() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithFactory instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
}
@Test(expected = MCRConfigurationException.class)
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithoutConstructorOrFactory.class)
})
public void noConstructorOrFactory() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
MCRConfigurableInstanceHelper.getInstance(configuration);
}
@Test(expected = MCRConfigurationException.class)
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithMultipleFactories.class)
})
public void multipleFactories() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
MCRConfigurableInstanceHelper.getInstance(configuration);
}
@Test
@MCRTestConfiguration(
properties = {
@MCRTestProperty(key = "Foo", classNameOf = TestClassWithConfigurationProxy.class),
@MCRTestProperty(key = "Foo.Value", string = "Value")
})
public void proxyFactory() {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo");
TestClassWithConfigurationProxy instance = MCRConfigurableInstanceHelper.getInstance(configuration);
assertNotNull(instance);
}
public static class TestClassWithConstructor {
public TestClassWithConstructor() {
}
}
@SuppressWarnings("InstantiationOfUtilityClass")
public static class TestClassWithFactory {
private TestClassWithFactory() {
}
public static TestClassWithFactory getInstance() {
return new TestClassWithFactory();
}
}
public static class TestClassWithoutConstructorOrFactory {
private TestClassWithoutConstructorOrFactory() {
}
}
@SuppressWarnings({ "InstantiationOfUtilityClass", "unused" })
public static class TestClassWithMultipleFactories {
private TestClassWithMultipleFactories() {
}
public static TestClassWithMultipleFactories getInstanceA() {
return new TestClassWithMultipleFactories();
}
public static TestClassWithMultipleFactories getInstanceB() {
return new TestClassWithMultipleFactories();
}
}
@SuppressWarnings({ "unused" })
@MCRConfigurationProxy(proxyClass = TestClassWithConfigurationProxy.Factory.class)
public static class TestClassWithConfigurationProxy {
public TestClassWithConfigurationProxy() {
}
public static class Factory implements Supplier<TestClassWithConfigurationProxy> {
@Override
public TestClassWithConfigurationProxy get() {
return new TestClassWithConfigurationProxy();
}
}
}
}
| 4,841 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRComponentTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRComponentTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.jar.Manifest;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRComponentTest extends MCRTestCase {
private static final MCRComponent TEST = new MCRComponent("test", getSimpleManifest());
private static final MCRComponent MIR_MODULE = new MCRComponent("mir-module", getSimpleManifest());
private static final MCRComponent ACL_EDITOR2 = new MCRComponent("mycore-acl-editor2", getSimpleManifest());
private static final MCRComponent MYCORE_BASE = new MCRComponent("mycore-base", getSimpleManifest());
/**
* Test method for {@link org.mycore.common.config.MCRComponent#getResourceBase()}.
*/
@Test
public final void testGetResourceBase() {
assertEquals("Did not get correct resource base.", "components/acl-editor2/config/",
ACL_EDITOR2.getResourceBase());
assertEquals("Did not get correct resource base.", "config/", MYCORE_BASE.getResourceBase());
assertEquals("Did not get correct resource base.", "config/mir/", MIR_MODULE.getResourceBase());
assertEquals("Did not get correct resource base.", "config/test/", TEST.getResourceBase());
}
/**
* Test method for {@link org.mycore.common.config.MCRComponent#isMyCoReComponent()}.
*/
@Test
public final void testIsMyCoReComponent() {
assertTrue("Is mycore component.", ACL_EDITOR2.isMyCoReComponent());
assertTrue("Is mycore component.", MYCORE_BASE.isMyCoReComponent());
assertFalse("Is not mycore component.", MIR_MODULE.isMyCoReComponent());
assertFalse("Is not mycore component.", TEST.isMyCoReComponent());
}
/**
* Test method for {@link org.mycore.common.config.MCRComponent#isAppModule()}.
*/
@Test
public final void testIsAppModule() {
assertFalse("Is not app module.", ACL_EDITOR2.isAppModule());
assertFalse("Is not app module.", MYCORE_BASE.isAppModule());
assertTrue("Is app module.", MIR_MODULE.isAppModule());
assertTrue("Is app module.", TEST.isAppModule());
}
/**
* Test method for {@link org.mycore.common.config.MCRComponent#getName()}.
*/
@Test
public final void testGetName() {
assertEquals("Did not name component correctly", "acl-editor2", ACL_EDITOR2.getName());
assertEquals("Did not name component correctly", "base", MYCORE_BASE.getName());
assertEquals("Did not name app module correctly", "mir", MIR_MODULE.getName());
assertEquals("Did not name app module correctly", "test", TEST.getName());
}
private static Manifest getSimpleManifest() {
return new Manifest();
}
}
| 3,618 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfiguration2Test.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRConfiguration2Test.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.MCRTestConfiguration;
import org.mycore.common.MCRTestProperty;
import org.mycore.common.config.annotation.MCRProperty;
import jakarta.inject.Singleton;
/**
* @author Thomas Scheffler (yagee)
*/
public class MCRConfiguration2Test extends MCRTestCase {
@Test(expected = MCRConfigurationException.class)
public final void testDeprecatedProperties() {
String deprecatedProperty = "MCR.Editor.FileUpload.MaxSize";
MCRConfiguration2.getString(deprecatedProperty);
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.Object", classNameOf = TestObject.class),
@MCRTestProperty(key = "MCR.C2.Object.Class", classNameOf = TestObject.class),
@MCRTestProperty(key = "MCR.C2.Object.class", classNameOf = TestObject.class)
})
public final void testObjectInstanceIsReturned() {
assertTrue(MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object").isPresent());
assertTrue(MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object.Class").isPresent());
assertTrue(MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object.class").isPresent());
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.Object", classNameOf = TestObject.class),
@MCRTestProperty(key = "MCR.C2.Object.Foo", string = "Bar")
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testObjectInstanceWithoutSuffixIsConfigured() {
TestObject instance = MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object").get();
assertEquals("Bar", instance.getFoo());
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.Object.Class", classNameOf = TestObject.class),
@MCRTestProperty(key = "MCR.C2.Object.Foo", string = "Bar")
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testObjectInstanceWithUpperCaseSuffixIsConfigured() {
TestObject instance = MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object.Class").get();
assertEquals("Bar", instance.getFoo());
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.Object.class", classNameOf = TestObject.class),
@MCRTestProperty(key = "MCR.C2.Object.Foo", string = "Bar")
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testObjectInstanceWithLowerCaseSuffixIsConfigured() {
TestObject instance = MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object.class").get();
assertEquals("Bar", instance.getFoo());
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.Object", classNameOf = TestObject.class)
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testObjectInstanceIsNotShared() {
TestObject instance1 = MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object").get();
TestObject instance2 = MCRConfiguration2.<TestObject>getInstanceOf("MCR.C2.Object").get();
assertNotEquals(instance1, instance2);
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.SameObject", classNameOf = TestObject.class)
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testSingleObjectInstanceWithSameKeyIsShared() {
TestObject instance1 = MCRConfiguration2.<TestObject>getSingleInstanceOf("MCR.C2.SameObject").get();
TestObject instance2 = MCRConfiguration2.<TestObject>getSingleInstanceOf("MCR.C2.SameObject").get();
assertEquals(instance1, instance2);
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.DifferentObject1", classNameOf = TestObject.class),
@MCRTestProperty(key = "MCR.C2.DifferentObject2", classNameOf = TestObject.class)
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testSingleObjectInstanceWithDifferentKeyIsNotShared() {
TestObject instance1 = MCRConfiguration2.<TestObject>getSingleInstanceOf("MCR.C2.DifferentObject1").get();
TestObject instance2 = MCRConfiguration2.<TestObject>getSingleInstanceOf("MCR.C2.DifferentObject2").get();
assertNotEquals(instance1, instance2);
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.Singleton", classNameOf = TestSingleton.class),
@MCRTestProperty(key = "MCR.C2.Singleton.Foo", string = "Bar")
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testSingletonInstanceIsShared() {
TestSingleton instance1 = MCRConfiguration2.<TestSingleton>getInstanceOf("MCR.C2.Singleton").get();
TestSingleton instance2 = MCRConfiguration2.<TestSingleton>getInstanceOf("MCR.C2.Singleton").get();
assertSame(instance1, instance2);
}
@Test
@MCRTestConfiguration(properties = {
@MCRTestProperty(key = "MCR.C2.Singleton", classNameOf = TestSingleton.class),
@MCRTestProperty(key = "MCR.C2.Singleton.Foo", string = "Bar")
})
@SuppressWarnings("OptionalGetWithoutIsPresent")
public final void testSingletonInstanceIsConfigured() {
TestSingleton instance = MCRConfiguration2.<TestSingleton>getInstanceOf("MCR.C2.Singleton").get();
assertEquals("Bar", instance.getFoo());
}
public static final class TestObject {
@MCRProperty(name = "Foo", required = false)
public String foo;
public String getFoo() {
return foo;
}
}
@Singleton
public static final class TestSingleton {
private static final TestSingleton INSTANCE = new TestSingleton();
@MCRProperty(name = "Foo", required = false)
public String foo;
public static TestSingleton getInstance() {
return INSTANCE;
}
public String getFoo() {
return foo;
}
}
}
| 7,032 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInstanceConfigurationTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/MCRInstanceConfigurationTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
public class MCRInstanceConfigurationTest extends MCRTestCase {
@Test
public void configurationWithoutSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
assertEquals("Foo.Bar", configuration.name().actual());
assertEquals("Foo.Bar", configuration.name().canonical());
assertEquals("foo.bar.TestClass", configuration.className());
assertEquals(properties, configuration.fullProperties());
}
@Test
public void configurationWithoutSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Key1", "Value1");
properties.put("Foo.Bar.Key2", "Value2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
assertEquals("Value1", configuration.properties().get("Key1"));
assertEquals("Value2", configuration.properties().get("Key2"));
assertEquals(2, configuration.properties().size());
}
@Test
public void configurationWithoutSuffixKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Class", "ClassValue");
properties.put("Foo.Bar.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
assertFalse(configuration.properties().containsKey(""));
assertEquals("ClassValue", configuration.properties().get("Class"));
assertEquals("ClassValue", configuration.properties().get("class"));
assertEquals(2, configuration.properties().size());
}
@Test
public void configurationWithUpperCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
assertEquals("Foo.Bar.Class", configuration.name().actual());
assertEquals("Foo.Bar", configuration.name().canonical());
assertEquals("foo.bar.TestClass", configuration.className());
assertEquals(properties, configuration.fullProperties());
}
@Test
public void configurationWithUpperCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.Key1", "Value1");
properties.put("Foo.Bar.Key2", "Value2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
assertEquals("Value1", configuration.properties().get("Key1"));
assertEquals("Value2", configuration.properties().get("Key2"));
assertEquals(2, configuration.properties().size());
}
@Test
public void configurationWithUpperCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.class", "ClassValue");
properties.put("Foo.Bar", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
assertFalse(configuration.properties().containsKey(""));
assertFalse(configuration.properties().containsKey("Class"));
assertFalse(configuration.properties().containsKey("class"));
assertEquals(0, configuration.properties().size());
}
@Test
public void configurationWithLowerCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
assertEquals("Foo.Bar.class", configuration.name().actual());
assertEquals("Foo.Bar", configuration.name().canonical());
assertEquals("foo.bar.TestClass", configuration.className());
assertEquals(properties, configuration.fullProperties());
}
@Test
public void configurationWithLowerCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Key1", "Value1");
properties.put("Foo.Bar.Key2", "Value2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
assertEquals("Value1", configuration.properties().get("Key1"));
assertEquals("Value2", configuration.properties().get("Key2"));
assertEquals(2, configuration.properties().size());
}
@Test
public void configurationWithLowerCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Class", "ClassValue");
properties.put("Foo.Bar", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
assertFalse(configuration.properties().containsKey(""));
assertFalse(configuration.properties().containsKey("Class"));
assertFalse(configuration.properties().containsKey("class"));
assertEquals(0, configuration.properties().size());
}
@Test
public void nestedConfigurationWithoutSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz", "foo.bar.NestedTestClass");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertEquals("Foo.Bar.Baz", nestedConfiguration.name().actual());
assertEquals("Foo.Bar.Baz", nestedConfiguration.name().canonical());
assertEquals("foo.bar.NestedTestClass", nestedConfiguration.className());
assertEquals(properties, nestedConfiguration.fullProperties());
}
@Test
public void nestedConfigurationWithoutSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz", "foo.bar.NestedTestClass");
properties.put("Foo.Bar.Baz.Key1", "Value1");
properties.put("Foo.Bar.Baz.Key2", "Value2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertEquals("Value1", nestedConfiguration.properties().get("Key1"));
assertEquals("Value2", nestedConfiguration.properties().get("Key2"));
assertEquals(2, nestedConfiguration.properties().size());
}
@Test
public void nestedConfigurationWithoutSuffixKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz", "foo.bar.NestedTestClass");
properties.put("Foo.Bar.Baz.Class", "ClassValue");
properties.put("Foo.Bar.Baz.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertFalse(nestedConfiguration.properties().containsKey(""));
assertEquals("ClassValue", nestedConfiguration.properties().get("Class"));
assertEquals("ClassValue", nestedConfiguration.properties().get("class"));
assertEquals(2, nestedConfiguration.properties().size());
}
@Test
public void nestedConfigurationWithUpperCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.Class", "foo.bar.NestedTestClass");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertEquals("Foo.Bar.Baz.Class", nestedConfiguration.name().actual());
assertEquals("Foo.Bar.Baz", nestedConfiguration.name().canonical());
assertEquals("foo.bar.NestedTestClass", nestedConfiguration.className());
assertEquals(properties, nestedConfiguration.fullProperties());
}
@Test
public void nestedConfigurationWithUpperCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.Class", "foo.bar.NestedTestClass");
properties.put("Foo.Bar.Baz.Key1", "Value1");
properties.put("Foo.Bar.Baz.Key2", "Value2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertEquals("Value1", nestedConfiguration.properties().get("Key1"));
assertEquals("Value2", nestedConfiguration.properties().get("Key2"));
assertEquals(2, nestedConfiguration.properties().size());
}
@Test
public void nestedConfigurationWithUpperCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.Class", "foo.bar.NestedTestClass");
properties.put("Foo.Bar.Baz.class", "ClassValue");
properties.put("Foo.Bar.Baz", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertFalse(nestedConfiguration.properties().containsKey(""));
assertFalse(nestedConfiguration.properties().containsKey("Class"));
assertFalse(nestedConfiguration.properties().containsKey("class"));
assertEquals(0, nestedConfiguration.properties().size());
}
@Test
public void nestedConfigurationWithLowerCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.class", "foo.bar.NestedTestClass");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertEquals("Foo.Bar.Baz.class", nestedConfiguration.name().actual());
assertEquals("Foo.Bar.Baz", nestedConfiguration.name().canonical());
assertEquals("foo.bar.NestedTestClass", nestedConfiguration.className());
assertEquals(properties, nestedConfiguration.fullProperties());
}
@Test
public void nestedConfigurationWithLowerCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.class", "foo.bar.NestedTestClass");
properties.put("Foo.Bar.Baz.Key1", "Value1");
properties.put("Foo.Bar.Baz.Key2", "Value2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertEquals("Value1", nestedConfiguration.properties().get("Key1"));
assertEquals("Value2", nestedConfiguration.properties().get("Key2"));
assertEquals(2, nestedConfiguration.properties().size());
}
@Test
public void nestedConfigurationWithLowerCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.class", "foo.bar.NestedTestClass");
properties.put("Foo.Bar.Baz.Class", "ClassValue");
properties.put("Foo.Bar.Baz", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertFalse(nestedConfiguration.properties().containsKey(""));
assertFalse(nestedConfiguration.properties().containsKey("Class"));
assertFalse(nestedConfiguration.properties().containsKey("class"));
assertEquals(0, nestedConfiguration.properties().size());
}
@Test
public void nestedConfigurationMapWithoutSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.A", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.B", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.C", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.A", nestedConfigurationA.name().actual());
assertEquals("Foo.Bar.A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("Foo.Bar.B", nestedConfigurationB.name().actual());
assertEquals("Foo.Bar.B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("Foo.Bar.C", nestedConfigurationC.name().actual());
assertEquals("Foo.Bar.C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedConfigurationMapWithoutSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.A", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.A.Key1", "ValueA1");
properties.put("Foo.Bar.A.Key2", "ValueA2");
properties.put("Foo.Bar.B", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.B.Key1", "ValueB1");
properties.put("Foo.Bar.B.Key2", "ValueB2");
properties.put("Foo.Bar.C", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.C.Key1", "ValueC1");
properties.put("Foo.Bar.C.Key2", "ValueC2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("ValueA1", nestedConfigurationA.properties().get("Key1"));
assertEquals("ValueA2", nestedConfigurationA.properties().get("Key2"));
assertEquals(2, nestedConfigurationA.properties().size());
assertEquals("ValueB1", nestedConfigurationB.properties().get("Key1"));
assertEquals("ValueB2", nestedConfigurationB.properties().get("Key2"));
assertEquals(2, nestedConfigurationB.properties().size());
assertEquals("ValueC1", nestedConfigurationC.properties().get("Key1"));
assertEquals("ValueC2", nestedConfigurationC.properties().get("Key2"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithoutSuffixKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.A", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.A.Class", "ClassValue");
properties.put("Foo.Bar.A.class", "ClassValue");
properties.put("Foo.Bar.B", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.B.Class", "ClassValue");
properties.put("Foo.Bar.B.class", "ClassValue");
properties.put("Foo.Bar.C", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.C.Class", "ClassValue");
properties.put("Foo.Bar.C.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertEquals("ClassValue", nestedConfigurationA.properties().get("Class"));
assertEquals("ClassValue", nestedConfigurationA.properties().get("class"));
assertEquals(2, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertEquals("ClassValue", nestedConfigurationB.properties().get("Class"));
assertEquals("ClassValue", nestedConfigurationB.properties().get("class"));
assertEquals(2, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertEquals("ClassValue", nestedConfigurationC.properties().get("Class"));
assertEquals("ClassValue", nestedConfigurationC.properties().get("class"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithUpperCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.A.Class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.B.Class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.C.Class", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.A.Class", nestedConfigurationA.name().actual());
assertEquals("Foo.Bar.A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("Foo.Bar.B.Class", nestedConfigurationB.name().actual());
assertEquals("Foo.Bar.B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("Foo.Bar.C.Class", nestedConfigurationC.name().actual());
assertEquals("Foo.Bar.C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedConfigurationMapWithUpperCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.A.Class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.A.Key1", "ValueA1");
properties.put("Foo.Bar.A.Key2", "ValueA2");
properties.put("Foo.Bar.B.Class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.B.Key1", "ValueB1");
properties.put("Foo.Bar.B.Key2", "ValueB2");
properties.put("Foo.Bar.C.Class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.C.Key1", "ValueC1");
properties.put("Foo.Bar.C.Key2", "ValueC2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("ValueA1", nestedConfigurationA.properties().get("Key1"));
assertEquals("ValueA2", nestedConfigurationA.properties().get("Key2"));
assertEquals(2, nestedConfigurationA.properties().size());
assertEquals("ValueB1", nestedConfigurationB.properties().get("Key1"));
assertEquals("ValueB2", nestedConfigurationB.properties().get("Key2"));
assertEquals(2, nestedConfigurationB.properties().size());
assertEquals("ValueC1", nestedConfigurationC.properties().get("Key1"));
assertEquals("ValueC2", nestedConfigurationC.properties().get("Key2"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithUpperCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.A.Class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.A.class", "ClassValue");
properties.put("Foo.Bar.A", "ClassValue");
properties.put("Foo.Bar.B.Class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.B.class", "ClassValue");
properties.put("Foo.Bar.B", "ClassValue");
properties.put("Foo.Bar.C.Class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.C.class", "ClassValue");
properties.put("Foo.Bar.C", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertFalse(nestedConfigurationA.properties().containsKey("Class"));
assertFalse(nestedConfigurationA.properties().containsKey("class"));
assertEquals(0, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertFalse(nestedConfigurationB.properties().containsKey("Class"));
assertFalse(nestedConfigurationB.properties().containsKey("class"));
assertEquals(0, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertFalse(nestedConfigurationC.properties().containsKey("Class"));
assertFalse(nestedConfigurationC.properties().containsKey("class"));
assertEquals(0, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithLowerCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.A.class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.B.class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.C.class", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.A.class", nestedConfigurationA.name().actual());
assertEquals("Foo.Bar.A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("Foo.Bar.B.class", nestedConfigurationB.name().actual());
assertEquals("Foo.Bar.B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("Foo.Bar.C.class", nestedConfigurationC.name().actual());
assertEquals("Foo.Bar.C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedConfigurationMapWithLowerCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.A.class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.A.Key1", "ValueA1");
properties.put("Foo.Bar.A.Key2", "ValueA2");
properties.put("Foo.Bar.B.class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.B.Key1", "ValueB1");
properties.put("Foo.Bar.B.Key2", "ValueB2");
properties.put("Foo.Bar.C.class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.C.Key1", "ValueC1");
properties.put("Foo.Bar.C.Key2", "ValueC2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("ValueA1", nestedConfigurationA.properties().get("Key1"));
assertEquals("ValueA2", nestedConfigurationA.properties().get("Key2"));
assertEquals(2, nestedConfigurationA.properties().size());
assertEquals("ValueB1", nestedConfigurationB.properties().get("Key1"));
assertEquals("ValueB2", nestedConfigurationB.properties().get("Key2"));
assertEquals(2, nestedConfigurationB.properties().size());
assertEquals("ValueC1", nestedConfigurationC.properties().get("Key1"));
assertEquals("ValueC2", nestedConfigurationC.properties().get("Key2"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithLowerCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.A.class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.A.Class", "ClassValue");
properties.put("Foo.Bar.A", "ClassValue");
properties.put("Foo.Bar.B.class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.B.Class", "ClassValue");
properties.put("Foo.Bar.B", "ClassValue");
properties.put("Foo.Bar.C.class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.C.Class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertFalse(nestedConfigurationA.properties().containsKey("Class"));
assertFalse(nestedConfigurationA.properties().containsKey("class"));
assertEquals(0, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertFalse(nestedConfigurationB.properties().containsKey("Class"));
assertFalse(nestedConfigurationB.properties().containsKey("class"));
assertEquals(0, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertFalse(nestedConfigurationC.properties().containsKey("Class"));
assertFalse(nestedConfigurationC.properties().containsKey("class"));
assertEquals(0, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithPrefixWithoutSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.B", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.C", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.Baz.A", nestedConfigurationA.name().actual());
assertEquals("Foo.Bar.Baz.A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("Foo.Bar.Baz.B", nestedConfigurationB.name().actual());
assertEquals("Foo.Bar.Baz.B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("Foo.Bar.Baz.C", nestedConfigurationC.name().actual());
assertEquals("Foo.Bar.Baz.C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedConfigurationMapWithPrefixWithoutSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.A.Key1", "ValueA1");
properties.put("Foo.Bar.Baz.A.Key2", "ValueA2");
properties.put("Foo.Bar.Baz.B", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.B.Key1", "ValueB1");
properties.put("Foo.Bar.Baz.B.Key2", "ValueB2");
properties.put("Foo.Bar.Baz.C", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.Baz.C.Key1", "ValueC1");
properties.put("Foo.Bar.Baz.C.Key2", "ValueC2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("ValueA1", nestedConfigurationA.properties().get("Key1"));
assertEquals("ValueA2", nestedConfigurationA.properties().get("Key2"));
assertEquals(2, nestedConfigurationA.properties().size());
assertEquals("ValueB1", nestedConfigurationB.properties().get("Key1"));
assertEquals("ValueB2", nestedConfigurationB.properties().get("Key2"));
assertEquals(2, nestedConfigurationB.properties().size());
assertEquals("ValueC1", nestedConfigurationC.properties().get("Key1"));
assertEquals("ValueC2", nestedConfigurationC.properties().get("Key2"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithPrefixWithoutSuffixKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.A.Class", "ClassValue");
properties.put("Foo.Bar.Baz.A.class", "ClassValue");
properties.put("Foo.Bar.Baz.B", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.B.Class", "ClassValue");
properties.put("Foo.Bar.Baz.B.class", "ClassValue");
properties.put("Foo.Bar.Baz.C", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.Baz.C.Class", "ClassValue");
properties.put("Foo.Bar.Baz.C.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertEquals("ClassValue", nestedConfigurationA.properties().get("Class"));
assertEquals("ClassValue", nestedConfigurationA.properties().get("class"));
assertEquals(2, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertEquals("ClassValue", nestedConfigurationB.properties().get("Class"));
assertEquals("ClassValue", nestedConfigurationB.properties().get("class"));
assertEquals(2, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertEquals("ClassValue", nestedConfigurationC.properties().get("Class"));
assertEquals("ClassValue", nestedConfigurationC.properties().get("class"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithPrefixWithUpperCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A.Class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.B.Class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.C.Class", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.Baz.A.Class", nestedConfigurationA.name().actual());
assertEquals("Foo.Bar.Baz.A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("Foo.Bar.Baz.B.Class", nestedConfigurationB.name().actual());
assertEquals("Foo.Bar.Baz.B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("Foo.Bar.Baz.C.Class", nestedConfigurationC.name().actual());
assertEquals("Foo.Bar.Baz.C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedConfigurationMapWithPrefixWithUpperCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A.Class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.A.Key1", "ValueA1");
properties.put("Foo.Bar.Baz.A.Key2", "ValueA2");
properties.put("Foo.Bar.Baz.B.Class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.B.Key1", "ValueB1");
properties.put("Foo.Bar.Baz.B.Key2", "ValueB2");
properties.put("Foo.Bar.Baz.C.Class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.Baz.C.Key1", "ValueC1");
properties.put("Foo.Bar.Baz.C.Key2", "ValueC2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("ValueA1", nestedConfigurationA.properties().get("Key1"));
assertEquals("ValueA2", nestedConfigurationA.properties().get("Key2"));
assertEquals(2, nestedConfigurationA.properties().size());
assertEquals("ValueB1", nestedConfigurationB.properties().get("Key1"));
assertEquals("ValueB2", nestedConfigurationB.properties().get("Key2"));
assertEquals(2, nestedConfigurationB.properties().size());
assertEquals("ValueC1", nestedConfigurationC.properties().get("Key1"));
assertEquals("ValueC2", nestedConfigurationC.properties().get("Key2"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithPrefixWithUpperCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A.Class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.A.class", "ClassValue");
properties.put("Foo.Bar.Baz.A", "ClassValue");
properties.put("Foo.Bar.Baz.B.Class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.B.class", "ClassValue");
properties.put("Foo.Bar.Baz.B", "ClassValue");
properties.put("Foo.Bar.Baz.C.Class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.Baz.C.class", "ClassValue");
properties.put("Foo.Bar.Baz.C", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertFalse(nestedConfigurationA.properties().containsKey("Class"));
assertFalse(nestedConfigurationA.properties().containsKey("class"));
assertEquals(0, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertFalse(nestedConfigurationB.properties().containsKey("Class"));
assertFalse(nestedConfigurationB.properties().containsKey("class"));
assertEquals(0, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertFalse(nestedConfigurationC.properties().containsKey("Class"));
assertFalse(nestedConfigurationC.properties().containsKey("class"));
assertEquals(0, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithPrefixWithLowerCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A.class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.B.class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.C.class", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.Baz.A.class", nestedConfigurationA.name().actual());
assertEquals("Foo.Bar.Baz.A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("Foo.Bar.Baz.B.class", nestedConfigurationB.name().actual());
assertEquals("Foo.Bar.Baz.B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("Foo.Bar.Baz.C.class", nestedConfigurationC.name().actual());
assertEquals("Foo.Bar.Baz.C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedConfigurationMapWithPrefixWithLowerCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A.class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.A.Key1", "ValueA1");
properties.put("Foo.Bar.Baz.A.Key2", "ValueA2");
properties.put("Foo.Bar.Baz.B.class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.B.Key1", "ValueB1");
properties.put("Foo.Bar.Baz.B.Key2", "ValueB2");
properties.put("Foo.Bar.Baz.C.class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.Baz.C.Key1", "ValueC1");
properties.put("Foo.Bar.Baz.C.Key2", "ValueC2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("ValueA1", nestedConfigurationA.properties().get("Key1"));
assertEquals("ValueA2", nestedConfigurationA.properties().get("Key2"));
assertEquals(2, nestedConfigurationA.properties().size());
assertEquals("ValueB1", nestedConfigurationB.properties().get("Key1"));
assertEquals("ValueB2", nestedConfigurationB.properties().get("Key2"));
assertEquals(2, nestedConfigurationB.properties().size());
assertEquals("ValueC1", nestedConfigurationC.properties().get("Key1"));
assertEquals("ValueC2", nestedConfigurationC.properties().get("Key2"));
assertEquals(2, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationMapWithPrefixWithLowerCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.bar.TestClass");
properties.put("Foo.Bar.Baz.A.class", "foo.bar.NestedTestClassA");
properties.put("Foo.Bar.Baz.A.Class", "ClassValue");
properties.put("Foo.Bar.Baz.A", "ClassValue");
properties.put("Foo.Bar.Baz.B.class", "foo.bar.NestedTestClassB");
properties.put("Foo.Bar.Baz.B.Class", "ClassValue");
properties.put("Foo.Bar.Baz.B", "ClassValue");
properties.put("Foo.Bar.Baz.C.class", "foo.bar.NestedTestClassC");
properties.put("Foo.Bar.Baz.C.Class", "ClassValue");
properties.put("Foo.Bar.Baz.C", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertFalse(nestedConfigurationA.properties().containsKey("Class"));
assertFalse(nestedConfigurationA.properties().containsKey("class"));
assertEquals(0, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertFalse(nestedConfigurationB.properties().containsKey("Class"));
assertFalse(nestedConfigurationB.properties().containsKey("class"));
assertEquals(0, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertFalse(nestedConfigurationC.properties().containsKey("Class"));
assertFalse(nestedConfigurationC.properties().containsKey("class"));
assertEquals(0, nestedConfigurationC.properties().size());
}
@Test
public void nestedConfigurationListWithoutSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.Bar.TestClass");
properties.put("Foo.Bar.10", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.20", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.30", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.10", nestedConfiguration0.name().actual());
assertEquals("Foo.Bar.10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("Foo.Bar.20", nestedConfiguration1.name().actual());
assertEquals("Foo.Bar.20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("Foo.Bar.30", nestedConfiguration2.name().actual());
assertEquals("Foo.Bar.30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedConfigurationListWithoutSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.Bar.TestClass");
properties.put("Foo.Bar.10", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.10.KeyA", "Value0A");
properties.put("Foo.Bar.10.KeyB", "Value0B");
properties.put("Foo.Bar.20", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.20.KeyA", "Value1A");
properties.put("Foo.Bar.20.KeyB", "Value1B");
properties.put("Foo.Bar.30", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.30.KeyA", "Value2A");
properties.put("Foo.Bar.30.KeyB", "Value2B");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Value0A", nestedConfiguration0.properties().get("KeyA"));
assertEquals("Value0B", nestedConfiguration0.properties().get("KeyB"));
assertEquals(2, nestedConfiguration0.properties().size());
assertEquals("Value1A", nestedConfiguration1.properties().get("KeyA"));
assertEquals("Value1B", nestedConfiguration1.properties().get("KeyB"));
assertEquals(2, nestedConfiguration1.properties().size());
assertEquals("Value2A", nestedConfiguration2.properties().get("KeyA"));
assertEquals("Value2B", nestedConfiguration2.properties().get("KeyB"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithoutSuffixKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.Bar.TestClass");
properties.put("Foo.Bar.10", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.10.Class", "ClassValue");
properties.put("Foo.Bar.10.class", "ClassValue");
properties.put("Foo.Bar.20", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.20.Class", "ClassValue");
properties.put("Foo.Bar.20.class", "ClassValue");
properties.put("Foo.Bar.30", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.30.Class", "ClassValue");
properties.put("Foo.Bar.30.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertEquals("ClassValue", nestedConfiguration0.properties().get("Class"));
assertEquals("ClassValue", nestedConfiguration0.properties().get("class"));
assertEquals(2, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertEquals("ClassValue", nestedConfiguration1.properties().get("Class"));
assertEquals("ClassValue", nestedConfiguration1.properties().get("class"));
assertEquals(2, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertEquals("ClassValue", nestedConfiguration2.properties().get("Class"));
assertEquals("ClassValue", nestedConfiguration2.properties().get("class"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithUpperCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.Bar.TestClass");
properties.put("Foo.Bar.10.Class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.20.Class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.30.Class", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.10.Class", nestedConfiguration0.name().actual());
assertEquals("Foo.Bar.10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("Foo.Bar.20.Class", nestedConfiguration1.name().actual());
assertEquals("Foo.Bar.20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("Foo.Bar.30.Class", nestedConfiguration2.name().actual());
assertEquals("Foo.Bar.30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedConfigurationListWithUpperCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.Bar.TestClass");
properties.put("Foo.Bar.10.Class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.10.KeyA", "Value0A");
properties.put("Foo.Bar.10.KeyB", "Value0B");
properties.put("Foo.Bar.20.Class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.20.KeyA", "Value1A");
properties.put("Foo.Bar.20.KeyB", "Value1B");
properties.put("Foo.Bar.30.Class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.30.KeyA", "Value2A");
properties.put("Foo.Bar.30.KeyB", "Value2B");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Value0A", nestedConfiguration0.properties().get("KeyA"));
assertEquals("Value0B", nestedConfiguration0.properties().get("KeyB"));
assertEquals(2, nestedConfiguration0.properties().size());
assertEquals("Value1A", nestedConfiguration1.properties().get("KeyA"));
assertEquals("Value1B", nestedConfiguration1.properties().get("KeyB"));
assertEquals(2, nestedConfiguration1.properties().size());
assertEquals("Value2A", nestedConfiguration2.properties().get("KeyA"));
assertEquals("Value2B", nestedConfiguration2.properties().get("KeyB"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithUpperCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.Bar.TestClass");
properties.put("Foo.Bar.10.Class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.10.class", "ClassValue");
properties.put("Foo.Bar.10", "ClassValue");
properties.put("Foo.Bar.20.Class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.20.class", "ClassValue");
properties.put("Foo.Bar.20", "ClassValue");
properties.put("Foo.Bar.30.Class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.30.class", "ClassValue");
properties.put("Foo.Bar.30", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertFalse(nestedConfiguration0.properties().containsKey("Class"));
assertFalse(nestedConfiguration0.properties().containsKey("class"));
assertEquals(0, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertFalse(nestedConfiguration1.properties().containsKey("Class"));
assertFalse(nestedConfiguration1.properties().containsKey("class"));
assertEquals(0, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertFalse(nestedConfiguration2.properties().containsKey("Class"));
assertFalse(nestedConfiguration2.properties().containsKey("class"));
assertEquals(0, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithLowerCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.Bar.TestClass");
properties.put("Foo.Bar.10.class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.20.class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.30.class", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.10.class", nestedConfiguration0.name().actual());
assertEquals("Foo.Bar.10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("Foo.Bar.20.class", nestedConfiguration1.name().actual());
assertEquals("Foo.Bar.20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("Foo.Bar.30.class", nestedConfiguration2.name().actual());
assertEquals("Foo.Bar.30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedConfigurationListWithLowerCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.Bar.TestClass");
properties.put("Foo.Bar.10.class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.10.KeyA", "Value0A");
properties.put("Foo.Bar.10.KeyB", "Value0B");
properties.put("Foo.Bar.20.class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.20.KeyA", "Value1A");
properties.put("Foo.Bar.20.KeyB", "Value1B");
properties.put("Foo.Bar.30.class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.30.KeyA", "Value2A");
properties.put("Foo.Bar.30.KeyB", "Value2B");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Value0A", nestedConfiguration0.properties().get("KeyA"));
assertEquals("Value0B", nestedConfiguration0.properties().get("KeyB"));
assertEquals(2, nestedConfiguration0.properties().size());
assertEquals("Value1A", nestedConfiguration1.properties().get("KeyA"));
assertEquals("Value1B", nestedConfiguration1.properties().get("KeyB"));
assertEquals(2, nestedConfiguration1.properties().size());
assertEquals("Value2A", nestedConfiguration2.properties().get("KeyA"));
assertEquals("Value2B", nestedConfiguration2.properties().get("KeyB"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithLowerCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.Bar.TestClass");
properties.put("Foo.Bar.10.class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.10.Class", "ClassValue");
properties.put("Foo.Bar.10", "ClassValue");
properties.put("Foo.Bar.20.class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.20.Class", "ClassValue");
properties.put("Foo.Bar.20", "ClassValue");
properties.put("Foo.Bar.30.class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.30.Class", "ClassValue");
properties.put("Foo.Bar.30", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertFalse(nestedConfiguration0.properties().containsKey("Class"));
assertFalse(nestedConfiguration0.properties().containsKey("class"));
assertEquals(0, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertFalse(nestedConfiguration1.properties().containsKey("Class"));
assertFalse(nestedConfiguration1.properties().containsKey("class"));
assertEquals(0, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertFalse(nestedConfiguration2.properties().containsKey("Class"));
assertFalse(nestedConfiguration2.properties().containsKey("class"));
assertEquals(0, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithPrefixWithoutSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.20", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.30", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.Baz.10", nestedConfiguration0.name().actual());
assertEquals("Foo.Bar.Baz.10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("Foo.Bar.Baz.20", nestedConfiguration1.name().actual());
assertEquals("Foo.Bar.Baz.20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("Foo.Bar.Baz.30", nestedConfiguration2.name().actual());
assertEquals("Foo.Bar.Baz.30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedConfigurationListWithPrefixWithoutSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.10.KeyA", "Value0A");
properties.put("Foo.Bar.Baz.10.KeyB", "Value0B");
properties.put("Foo.Bar.Baz.20", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.20.KeyA", "Value1A");
properties.put("Foo.Bar.Baz.20.KeyB", "Value1B");
properties.put("Foo.Bar.Baz.30", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.Baz.30.KeyA", "Value2A");
properties.put("Foo.Bar.Baz.30.KeyB", "Value2B");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Value0A", nestedConfiguration0.properties().get("KeyA"));
assertEquals("Value0B", nestedConfiguration0.properties().get("KeyB"));
assertEquals(2, nestedConfiguration0.properties().size());
assertEquals("Value1A", nestedConfiguration1.properties().get("KeyA"));
assertEquals("Value1B", nestedConfiguration1.properties().get("KeyB"));
assertEquals(2, nestedConfiguration1.properties().size());
assertEquals("Value2A", nestedConfiguration2.properties().get("KeyA"));
assertEquals("Value2B", nestedConfiguration2.properties().get("KeyB"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithPrefixWithoutSuffixKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.10.Class", "ClassValue");
properties.put("Foo.Bar.Baz.10.class", "ClassValue");
properties.put("Foo.Bar.Baz.20", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.20.Class", "ClassValue");
properties.put("Foo.Bar.Baz.20.class", "ClassValue");
properties.put("Foo.Bar.Baz.30", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.Baz.30.Class", "ClassValue");
properties.put("Foo.Bar.Baz.30.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertEquals("ClassValue", nestedConfiguration0.properties().get("Class"));
assertEquals("ClassValue", nestedConfiguration0.properties().get("class"));
assertEquals(2, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertEquals("ClassValue", nestedConfiguration1.properties().get("Class"));
assertEquals("ClassValue", nestedConfiguration1.properties().get("class"));
assertEquals(2, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertEquals("ClassValue", nestedConfiguration2.properties().get("Class"));
assertEquals("ClassValue", nestedConfiguration2.properties().get("class"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithPrefixWithUpperCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10.Class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.20.Class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.30.Class", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.Baz.10.Class", nestedConfiguration0.name().actual());
assertEquals("Foo.Bar.Baz.10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("Foo.Bar.Baz.20.Class", nestedConfiguration1.name().actual());
assertEquals("Foo.Bar.Baz.20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("Foo.Bar.Baz.30.Class", nestedConfiguration2.name().actual());
assertEquals("Foo.Bar.Baz.30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedConfigurationListWithPrefixWithUpperCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10.Class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.10.KeyA", "Value0A");
properties.put("Foo.Bar.Baz.10.KeyB", "Value0B");
properties.put("Foo.Bar.Baz.20.Class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.20.KeyA", "Value1A");
properties.put("Foo.Bar.Baz.20.KeyB", "Value1B");
properties.put("Foo.Bar.Baz.30.Class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.Baz.30.KeyA", "Value2A");
properties.put("Foo.Bar.Baz.30.KeyB", "Value2B");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Value0A", nestedConfiguration0.properties().get("KeyA"));
assertEquals("Value0B", nestedConfiguration0.properties().get("KeyB"));
assertEquals(2, nestedConfiguration0.properties().size());
assertEquals("Value1A", nestedConfiguration1.properties().get("KeyA"));
assertEquals("Value1B", nestedConfiguration1.properties().get("KeyB"));
assertEquals(2, nestedConfiguration1.properties().size());
assertEquals("Value2A", nestedConfiguration2.properties().get("KeyA"));
assertEquals("Value2B", nestedConfiguration2.properties().get("KeyB"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithPrefixWithUpperCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.Class", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10.Class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.10.class", "ClassValue");
properties.put("Foo.Bar.Baz.10", "ClassValue");
properties.put("Foo.Bar.Baz.20.Class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.20.class", "ClassValue");
properties.put("Foo.Bar.Baz.20", "ClassValue");
properties.put("Foo.Bar.Baz.30.Class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.Baz.30.class", "ClassValue");
properties.put("Foo.Bar.Baz.30", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.Class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertFalse(nestedConfiguration0.properties().containsKey("Class"));
assertFalse(nestedConfiguration0.properties().containsKey("class"));
assertEquals(0, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertFalse(nestedConfiguration1.properties().containsKey("Class"));
assertFalse(nestedConfiguration1.properties().containsKey("class"));
assertEquals(0, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertFalse(nestedConfiguration2.properties().containsKey("Class"));
assertFalse(nestedConfiguration2.properties().containsKey("class"));
assertEquals(0, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithPrefixWithLowerCaseSuffix() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10.class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.20.class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.30.class", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Foo.Bar.Baz.10.class", nestedConfiguration0.name().actual());
assertEquals("Foo.Bar.Baz.10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("Foo.Bar.Baz.20.class", nestedConfiguration1.name().actual());
assertEquals("Foo.Bar.Baz.20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("Foo.Bar.Baz.30.class", nestedConfiguration2.name().actual());
assertEquals("Foo.Bar.Baz.30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedConfigurationListWithPrefixWithLowerCaseSuffixMovesEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10.class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.10.KeyA", "Value0A");
properties.put("Foo.Bar.Baz.10.KeyB", "Value0B");
properties.put("Foo.Bar.Baz.20.class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.20.KeyA", "Value1A");
properties.put("Foo.Bar.Baz.20.KeyB", "Value1B");
properties.put("Foo.Bar.Baz.30.class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.Baz.30.KeyA", "Value2A");
properties.put("Foo.Bar.Baz.30.KeyB", "Value2B");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Value0A", nestedConfiguration0.properties().get("KeyA"));
assertEquals("Value0B", nestedConfiguration0.properties().get("KeyB"));
assertEquals(2, nestedConfiguration0.properties().size());
assertEquals("Value1A", nestedConfiguration1.properties().get("KeyA"));
assertEquals("Value1B", nestedConfiguration1.properties().get("KeyB"));
assertEquals(2, nestedConfiguration1.properties().size());
assertEquals("Value2A", nestedConfiguration2.properties().get("KeyA"));
assertEquals("Value2B", nestedConfiguration2.properties().get("KeyB"));
assertEquals(2, nestedConfiguration2.properties().size());
}
@Test
public void nestedConfigurationListWithPrefixWithLowerCaseSuffixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Foo.Bar.class", "foo.Bar.TestClass");
properties.put("Foo.Bar.Baz.10.class", "foo.Bar.NestedTestClass0");
properties.put("Foo.Bar.Baz.10.Class", "ClassValue");
properties.put("Foo.Bar.Baz.10", "ClassValue");
properties.put("Foo.Bar.Baz.20.class", "foo.Bar.NestedTestClass1");
properties.put("Foo.Bar.Baz.20.Class", "ClassValue");
properties.put("Foo.Bar.Baz.20", "ClassValue");
properties.put("Foo.Bar.Baz.30.class", "foo.Bar.NestedTestClass2");
properties.put("Foo.Bar.Baz.30.Class", "ClassValue");
properties.put("Foo.Bar.Baz.30", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName("Foo.Bar.class", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertFalse(nestedConfiguration0.properties().containsKey("Class"));
assertFalse(nestedConfiguration0.properties().containsKey("class"));
assertEquals(0, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertFalse(nestedConfiguration1.properties().containsKey("Class"));
assertFalse(nestedConfiguration1.properties().containsKey("class"));
assertEquals(0, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertFalse(nestedConfiguration2.properties().containsKey("Class"));
assertFalse(nestedConfiguration2.properties().containsKey("class"));
assertEquals(0, nestedConfiguration2.properties().size());
}
@Test
public void directConfiguration() {
Map<String, String> properties = new HashMap<>();
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
assertEquals("Class", configuration.name().actual());
assertEquals("", configuration.name().canonical());
assertEquals("foo.bar.TestClass", configuration.className());
assertEquals(properties, configuration.fullProperties());
}
@Test
public void directConfigurationRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Class", "ClassValue");
properties.put("class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
assertFalse(configuration.properties().containsKey(""));
assertFalse(configuration.properties().containsKey("Class"));
assertFalse(configuration.properties().containsKey("class"));
assertEquals(0, configuration.properties().size());
}
@Test
public void nestedDirectConfiguration() {
Map<String, String> properties = new HashMap<>();
properties.put("Baz.Class", "foo.bar.NestedTestClass");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration("Baz");
assertEquals("Baz.Class", nestedConfiguration.name().actual());
assertEquals("Baz", nestedConfiguration.name().canonical());
assertEquals("foo.bar.NestedTestClass", nestedConfiguration.className());
assertEquals(properties, nestedConfiguration.fullProperties());
}
@Test
public void nestedDirectConfigurationMap() {
Map<String, String> properties = new HashMap<>();
properties.put("A.Class", "foo.bar.NestedTestClassA");
properties.put("B.Class", "foo.bar.NestedTestClassB");
properties.put("C.Class", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("A.Class", nestedConfigurationA.name().actual());
assertEquals("A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("B.Class", nestedConfigurationB.name().actual());
assertEquals("B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("C.Class", nestedConfigurationC.name().actual());
assertEquals("C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedDirectConfigurationMapRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("A", "foo.bar.NestedTestClassA");
properties.put("A.Class", "ClassValue");
properties.put("A.class", "ClassValue");
properties.put("B", "foo.bar.NestedTestClassB");
properties.put("B.Class", "ClassValue");
properties.put("B.class", "ClassValue");
properties.put("C", "foo.bar.NestedTestClassC");
properties.put("C.Class", "ClassValue");
properties.put("C.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap();
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertFalse(nestedConfigurationA.properties().containsKey("Class"));
assertFalse(nestedConfigurationA.properties().containsKey("class"));
assertEquals(0, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertFalse(nestedConfigurationB.properties().containsKey("Class"));
assertFalse(nestedConfigurationB.properties().containsKey("class"));
assertEquals(0, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertFalse(nestedConfigurationC.properties().containsKey("Class"));
assertFalse(nestedConfigurationC.properties().containsKey("class"));
assertEquals(0, nestedConfigurationC.properties().size());
}
@Test
public void nestedDirectConfigurationMapWithPrefix() {
Map<String, String> properties = new HashMap<>();
properties.put("Baz.A.Class", "foo.bar.NestedTestClassA");
properties.put("Baz.B.Class", "foo.bar.NestedTestClassB");
properties.put("Baz.C.Class", "foo.bar.NestedTestClassC");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertEquals("Baz.A.Class", nestedConfigurationA.name().actual());
assertEquals("Baz.A", nestedConfigurationA.name().canonical());
assertEquals("foo.bar.NestedTestClassA", nestedConfigurationA.className());
assertEquals(properties, nestedConfigurationA.fullProperties());
assertEquals("Baz.B.Class", nestedConfigurationB.name().actual());
assertEquals("Baz.B", nestedConfigurationB.name().canonical());
assertEquals("foo.bar.NestedTestClassB", nestedConfigurationB.className());
assertEquals(properties, nestedConfigurationB.fullProperties());
assertEquals("Baz.C.Class", nestedConfigurationC.name().actual());
assertEquals("Baz.C", nestedConfigurationC.name().canonical());
assertEquals("foo.bar.NestedTestClassC", nestedConfigurationC.className());
assertEquals(properties, nestedConfigurationC.fullProperties());
}
@Test
public void nestedDirectConfigurationMapWithPrefixRemovesClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Baz.A", "foo.bar.NestedTestClassA");
properties.put("Baz.A.Class", "ClassValue");
properties.put("Baz.A.class", "ClassValue");
properties.put("Baz.B", "foo.bar.NestedTestClassB");
properties.put("Baz.B.Class", "ClassValue");
properties.put("Baz.B.class", "ClassValue");
properties.put("Baz.C", "foo.bar.NestedTestClassC");
properties.put("Baz.C.Class", "ClassValue");
properties.put("Baz.C.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
Map<String, MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationMap("Baz");
MCRInstanceConfiguration nestedConfigurationA = nestedConfigurations.get("A");
MCRInstanceConfiguration nestedConfigurationB = nestedConfigurations.get("B");
MCRInstanceConfiguration nestedConfigurationC = nestedConfigurations.get("C");
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfigurationA.properties().containsKey(""));
assertFalse(nestedConfigurationA.properties().containsKey("Class"));
assertFalse(nestedConfigurationA.properties().containsKey("class"));
assertEquals(0, nestedConfigurationA.properties().size());
assertFalse(nestedConfigurationB.properties().containsKey(""));
assertFalse(nestedConfigurationB.properties().containsKey("Class"));
assertFalse(nestedConfigurationB.properties().containsKey("class"));
assertEquals(0, nestedConfigurationB.properties().size());
assertFalse(nestedConfigurationC.properties().containsKey(""));
assertFalse(nestedConfigurationC.properties().containsKey("Class"));
assertFalse(nestedConfigurationC.properties().containsKey("class"));
assertEquals(0, nestedConfigurationC.properties().size());
}
@Test
public void nestedDirectConfigurationList() {
Map<String, String> properties = new HashMap<>();
properties.put("10.Class", "foo.Bar.NestedTestClass0");
properties.put("20.Class", "foo.Bar.NestedTestClass1");
properties.put("30.Class", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("10.Class", nestedConfiguration0.name().actual());
assertEquals("10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("20.Class", nestedConfiguration1.name().actual());
assertEquals("20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("30.Class", nestedConfiguration2.name().actual());
assertEquals("30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedDirectConfigurationListKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("10", "foo.Bar.NestedTestClass0");
properties.put("10.Class", "ClassValue");
properties.put("10.class", "ClassValue");
properties.put("20", "foo.Bar.NestedTestClass1");
properties.put("20.Class", "ClassValue");
properties.put("20.class", "ClassValue");
properties.put("30", "foo.Bar.NestedTestClass2");
properties.put("30.Class", "ClassValue");
properties.put("30.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList();
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertFalse(nestedConfiguration0.properties().containsKey("Class"));
assertFalse(nestedConfiguration0.properties().containsKey("class"));
assertEquals(0, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertFalse(nestedConfiguration1.properties().containsKey("Class"));
assertFalse(nestedConfiguration1.properties().containsKey("class"));
assertEquals(0, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertFalse(nestedConfiguration2.properties().containsKey("Class"));
assertFalse(nestedConfiguration2.properties().containsKey("class"));
assertEquals(0, nestedConfiguration2.properties().size());
}
@Test
public void nestedDirectConfigurationListWithPrefix() {
Map<String, String> properties = new HashMap<>();
properties.put("Baz.10.Class", "foo.Bar.NestedTestClass0");
properties.put("Baz.20.Class", "foo.Bar.NestedTestClass1");
properties.put("Baz.30.Class", "foo.Bar.NestedTestClass2");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertEquals("Baz.10.Class", nestedConfiguration0.name().actual());
assertEquals("Baz.10", nestedConfiguration0.name().canonical());
assertEquals("foo.Bar.NestedTestClass0", nestedConfiguration0.className());
assertEquals(properties, nestedConfiguration0.fullProperties());
assertEquals("Baz.20.Class", nestedConfiguration1.name().actual());
assertEquals("Baz.20", nestedConfiguration1.name().canonical());
assertEquals("foo.Bar.NestedTestClass1", nestedConfiguration1.className());
assertEquals(properties, nestedConfiguration1.fullProperties());
assertEquals("Baz.30.Class", nestedConfiguration2.name().actual());
assertEquals("Baz.30", nestedConfiguration2.name().canonical());
assertEquals("foo.Bar.NestedTestClass2", nestedConfiguration2.className());
assertEquals(properties, nestedConfiguration2.fullProperties());
}
@Test
public void nestedDirectConfigurationListWithPrefixKeepsClassEntries() {
Map<String, String> properties = new HashMap<>();
properties.put("Baz.10", "foo.Bar.NestedTestClass0");
properties.put("Baz.10.Class", "ClassValue");
properties.put("Baz.10.class", "ClassValue");
properties.put("Baz.20", "foo.Bar.NestedTestClass1");
properties.put("Baz.20.Class", "ClassValue");
properties.put("Baz.20.class", "ClassValue");
properties.put("Baz.30", "foo.Bar.NestedTestClass2");
properties.put("Baz.30.Class", "ClassValue");
properties.put("Baz.30.class", "ClassValue");
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofClass("foo.bar.TestClass", properties);
List<MCRInstanceConfiguration> nestedConfigurations = configuration.nestedConfigurationList("Baz");
MCRInstanceConfiguration nestedConfiguration0 = nestedConfigurations.get(0);
MCRInstanceConfiguration nestedConfiguration1 = nestedConfigurations.get(1);
MCRInstanceConfiguration nestedConfiguration2 = nestedConfigurations.get(2);
assertEquals(3, nestedConfigurations.size());
assertFalse(nestedConfiguration0.properties().containsKey(""));
assertFalse(nestedConfiguration0.properties().containsKey("Class"));
assertFalse(nestedConfiguration0.properties().containsKey("class"));
assertEquals(0, nestedConfiguration0.properties().size());
assertFalse(nestedConfiguration1.properties().containsKey(""));
assertFalse(nestedConfiguration1.properties().containsKey("Class"));
assertFalse(nestedConfiguration1.properties().containsKey("class"));
assertEquals(0, nestedConfiguration1.properties().size());
assertFalse(nestedConfiguration2.properties().containsKey(""));
assertFalse(nestedConfiguration2.properties().containsKey("Class"));
assertFalse(nestedConfiguration2.properties().containsKey("class"));
assertEquals(0, nestedConfiguration2.properties().size());
}
}
| 104,176 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationSingletonCollisionClassB.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/singletoncollision/MCRConfigurationSingletonCollisionClassB.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config.singletoncollision;
/**
* Utility Class to be loaded from Class A
*
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCRConfigurationSingletonCollisionClassB {
}
| 935 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationSingletonCollisionClassA.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/config/singletoncollision/MCRConfigurationSingletonCollisionClassA.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.config.singletoncollision;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationTest;
/**
* Utility Class to load Class B
*
* @author Tobias Lenhardt [Hammer1279]
*/
public class MCRConfigurationSingletonCollisionClassA {
public static final Object COLLISION_CLASS_B = MCRConfiguration2.getSingleInstanceOf(
MCRConfiguration2.getStringOrThrow(MCRConfigurationTest.COLLISION_PROPERTY_NAME)).get();
}
| 1,218 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJanitorEventHandlerBaseTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/events/MCRJanitorEventHandlerBaseTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.events;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRTestCase;
import org.mycore.common.MCRUserInformation;
import org.mycore.datamodel.metadata.MCRObject;
public class MCRJanitorEventHandlerBaseTest extends MCRTestCase {
@Test
public void testUserSwitchBack() {
AtomicBoolean eventHandlerCalled = new AtomicBoolean(false);
MCRJanitorEventHandlerBase eventHandler = new MCRJanitorEventHandlerBase() {
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
eventHandlerCalled.set(true);
throw new MCRException("Error that happened");
}
};
MCRSystemUserInformation oldUserInformation = MCRSystemUserInformation.getGuestInstance();
MCRSessionMgr.getCurrentSession().setUserInformation(oldUserInformation);
boolean exceptionCatched = false;
try {
MCREvent evt = new MCREvent(MCREvent.ObjectType.OBJECT, MCREvent.EventType.CREATE);
evt.put(MCREvent.OBJECT_KEY, new MCRObject());
eventHandler.doHandleEvent(evt);
} catch (MCRException e) {
exceptionCatched = true;
}
MCRUserInformation userInformation = MCRSessionMgr.getCurrentSession().getUserInformation();
Assert.assertTrue("The EventHandler should have been called", eventHandlerCalled.get());
Assert.assertTrue("A Exception should have been thrown", exceptionCatched);
Assert.assertEquals("The UserInformation should be the same as before. (" + oldUserInformation.getUserID() + "/"
+ userInformation.getUserID() + ")", oldUserInformation, userInformation);
}
}
| 2,650 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRShutdownHandlerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/events/MCRShutdownHandlerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.events;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
public class MCRShutdownHandlerTest {
@Test
public void runCloseables() {
final MCRShutdownHandler shutdownHandler = MCRShutdownHandler.getInstance();
AtomicBoolean lowClosed = new AtomicBoolean(false);
AtomicBoolean hiClosed = new AtomicBoolean(false);
AtomicBoolean vHiClosed = new AtomicBoolean(false);
MCRShutdownHandler.Closeable vHiPrio = new MCRShutdownHandler.Closeable() {
@Override
public int getPriority() {
return Integer.MAX_VALUE;
}
@Override
public void close() {
System.out.println("Closing very hi prio");
assertFalse("Low priority closeable was closed to early.", lowClosed.get());
assertFalse("High priority closeable was closed to early.", hiClosed.get());
vHiClosed.set(true);
}
@Override
public String toString() {
return "very high";
}
};
MCRShutdownHandler.Closeable lowPrio = new MCRShutdownHandler.Closeable() {
@Override
public int getPriority() {
return Integer.MIN_VALUE + 5;
}
@Override
public void close() {
System.out.println("Closing low prio");
assertTrue("High priority closeable is not closed.", hiClosed.get());
assertTrue("Very high priority closeable is not closed.", vHiClosed.get());
lowClosed.set(true);
}
@Override
public String toString() {
return "low";
}
};
MCRShutdownHandler.Closeable hiPrio = new MCRShutdownHandler.Closeable() {
@Override
public int getPriority() {
return Integer.MIN_VALUE + 10;
}
@Override
public void close() {
System.out.println("Closing hi prio");
assertTrue("Very high priority closeable is not closed.", vHiClosed.get());
assertFalse("Low priority closeable was closed to early.", lowClosed.get());
hiClosed.set(true);
}
@Override
public String toString() {
return "high";
}
};
shutdownHandler.addCloseable(vHiPrio);
shutdownHandler.addCloseable(lowPrio);
shutdownHandler.addCloseable(hiPrio);
shutdownHandler.runClosables();
assertTrue(hiClosed.get() && lowClosed.get());
}
}
| 3,528 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREventManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/events/test/MCREventManagerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.events.test;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.events.MCREventManager;
public class MCREventManagerTest extends MCRTestCase {
static String defaultProperties;
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Store.BaseDir", "tmp");
testProperties.put("MCR.Metadata.Store.SVNBase", "/tmp/versions");
testProperties.put("MCR.EventHandler.MCRObject.1.Class",
"org.mycore.datamodel.common.MCRXMLMetadataEventHandler");
testProperties.put("MCR.EventHandler.MCRObject.4.Indexer", "lucene-metadata");
testProperties.put("MCR.EventHandler.MCRObject.4.Foo", "fooProp");
testProperties.put("MCR.EventHandler.MCRDerivate.2.Class",
"org.mycore.datamodel.common.MCRXMLMetadataEventHandler");
testProperties.put("MCR.Searcher.lucene-metadata.Class",
"org.mycore.common.events.test.MCREventManagerTest$FakeLuceneSearcher");
testProperties.put("MCR.Searcher.lucene-metadata.Index", "metadata");
testProperties.put("MCR.Searcher.lucene-metadata.IndexDir", "%MCR.datadir%/lucene-index4metadata");
testProperties.put("MCR.Searcher.lucene-metadata.StoreQueryFields", "true");
return testProperties;
}
@Test
public void instance() {
try {
MCREventManager.instance();
} catch (MCRConfigurationException e) {
assertEquals("Configuration property MCR.EventHandler.Mode.Foo is not set.", e.getMessage());
}
}
}
| 2,541 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURIResolverTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRURIResolverTest.java | package org.mycore.common.xml;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.transform.Source;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
public class MCRURIResolverTest extends MCRTestCase {
public static final String TEST_DEVELOPER_FOLDER_STRING = "/home/workspace";
@Test
public void testGetParentDirectoryResourceURI() {
Map<String, String> testData = new LinkedHashMap<>();
testData.put("/root/.m2/repository/some/directory/some.jar!/xsl/directory/myfile.xsl",
"resource:xsl/directory/");
testData.put("/root/.m2/repository/some/directory/some.jar!/xsl/myfile.xsl",
"resource:xsl/");
String configurationXSLDirectory
= MCRConfigurationDir.getConfigurationDirectory().toPath()
.resolve("resources")
.resolve("xsl")
.toFile()
.toURI()
.toString();
testData.put(configurationXSLDirectory + "/mir-accesskey-utils.xsl", "resource:xsl/");
testData.put(configurationXSLDirectory + "/directory/mir-accesskey-utils.xsl",
"resource:xsl/directory/");
testData.put(Paths.get(TEST_DEVELOPER_FOLDER_STRING).toAbsolutePath().toFile().toURI()
+ "/directory/mir-accesskey-utils.xsl", "resource:directory/");
for (Map.Entry<String, String> entry : testData.entrySet()) {
String result = MCRURIResolver.getParentDirectoryResourceURI(entry.getKey());
Assert.assertEquals(entry.getValue(), result);
}
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> properties = super.getTestProperties();
properties.put("MCR.Developer.Resource.Override", TEST_DEVELOPER_FOLDER_STRING);
return properties;
}
@Test
public void testImportFromSameDirectory() throws Exception {
MCRConfiguration2.set("MCR.URIResolver.xslImports.xsl-import", "functions/xsl-1.xsl,functions/xsl-2.xsl");
Source resolved = MCRURIResolver.instance()
.resolve("xslImport:xsl-import:functions/xsl-2.xsl", "some.jar!/xsl/xsl/functions/xsl-2.xsl");
Assert.assertNotNull(resolved);
Assert.assertTrue(StringUtils.endsWith(resolved.getSystemId(), "/xsl/functions/xsl-1.xsl"));
resolved = MCRURIResolver.instance()
.resolve("xslImport:xsl-import:functions/xsl-2.xsl", "some.jar!/xslt/functions/xsl-2.xsl");
Assert.assertNotNull(resolved);
Assert.assertTrue(StringUtils.endsWith(resolved.getSystemId(), "/xslt/functions/xsl-1.xsl"));
}
}
| 2,851 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSLTransformationTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRXSLTransformationTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
@Deprecated
public class MCRXSLTransformationTest extends MCRTestCase {
MCRXSLTransformation tr;
File stylesheet;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
tr = MCRXSLTransformation.getInstance();
stylesheet = File.createTempFile("test", ".xsl");
initStylesheet();
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
stylesheet.delete();
}
/**
* @throws FileNotFoundException
*/
private void initStylesheet() throws FileNotFoundException {
FileOutputStream fout = new FileOutputStream(stylesheet);
OutputStreamWriter outw = new OutputStreamWriter(fout, StandardCharsets.UTF_8);
PrintWriter out = new PrintWriter(outw);
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
out.println("<xsl:template match='@*|node()'>");
out.println("<xsl:copy>");
out.println("<xsl:apply-templates select='@*|node()'/>");
out.println("</xsl:copy>");
out.println("</xsl:template>");
out.println("</xsl:stylesheet>");
out.close();
}
@Test
public void transform() {
Element root = new Element("root");
Document in = new Document(root);
root.addContent(new Element("child").setAttribute("hasChildren", "no"));
Document out = MCRXSLTransformation.transform(in, stylesheet.getAbsolutePath());
assertTrue("Input not the same as Output", MCRXMLHelper.deepEqual(in, out));
}
}
| 2,844 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXPathBuilderTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRXPathBuilderTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import static org.junit.Assert.assertEquals;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* @author Frank LΓΌtzenkirchen
*/
public class MCRXPathBuilderTest extends MCRTestCase {
@Test
public void testXPath() {
Element root = new Element("root");
Element title1 = new Element("title");
Element title2 = new Element("title");
Element author = new Element("contributor");
Attribute role = new Attribute("role", "author");
Attribute lang = new Attribute("lang", "de", Namespace.XML_NAMESPACE);
author.setAttribute(role);
author.setAttribute(lang);
root.addContent(title1);
root.addContent(author);
root.addContent(title2);
new Document(root);
assertEquals("/root", MCRXPathBuilder.buildXPath(root));
assertEquals("/root/contributor[1]", MCRXPathBuilder.buildXPath(author));
assertEquals("/root/title[1]", MCRXPathBuilder.buildXPath(title1));
assertEquals("/root/title[2]", MCRXPathBuilder.buildXPath(title2));
assertEquals("/root/contributor[1]/@role", MCRXPathBuilder.buildXPath(role));
assertEquals("/root/contributor[1]/@xml:lang", MCRXPathBuilder.buildXPath(lang));
root.detach();
assertEquals("root", MCRXPathBuilder.buildXPath(root));
assertEquals("root/contributor[1]", MCRXPathBuilder.buildXPath(author));
}
@Test
public void testMODS() {
Element container = new Element("container");
new Document(container);
Element mods = new Element("mods", "http://www.loc.gov/mods/v3");
Element name = new Element("name", "http://www.loc.gov/mods/v3");
mods.addContent(name);
container.addContent(mods);
assertEquals("/container", MCRXPathBuilder.buildXPath(container));
assertEquals("/container/mods:mods[1]", MCRXPathBuilder.buildXPath(mods));
assertEquals("/container/mods:mods[1]/mods:name[1]", MCRXPathBuilder.buildXPath(name));
}
}
| 2,893 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLHelperTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRXMLHelperTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import com.google.gson.JsonObject;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRXMLHelperTest extends MCRTestCase {
/**
* Test method for {@link org.mycore.common.xml.MCRXMLHelper#deepEqual(org.jdom2.Element, org.jdom2.Element)}.
*/
@Test
public void testDeepEqualElementElement() {
assertTrue("Elements should be equal", MCRXMLHelper.deepEqual(getSmallElement(), getSmallElement()));
assertTrue("Elements should be equal", MCRXMLHelper.deepEqual(getBigElement(), getBigElement()));
assertFalse("Elements should be different", MCRXMLHelper.deepEqual(getSmallElement(), getBigElement()));
assertFalse("Elements should be different",
MCRXMLHelper.deepEqual(getSmallElement().setAttribute("j", "junit"), getSmallElement()));
assertFalse("Elements should be different", MCRXMLHelper.deepEqual(getBigElement(), getSmallElement()));
}
private static Element getSmallElement() {
Element elm = new Element("test");
elm.setAttribute("j", "unit");
elm.setAttribute("junit", "test");
elm.addContent(new Element("junit"));
return elm;
}
private static Element getBigElement() {
Element elm = getSmallElement();
elm.addContent(new Element("junit"));
return elm;
}
@Test
public void testList() throws Exception {
Element child1 = new Element("child").setText("Hallo Welt");
Element child2 = new Element("child").setText("hello world");
Element child3 = new Element("child").setText("Bonjour le monde");
List<Content> l1 = new ArrayList<>();
l1.add(child1);
l1.add(child2);
l1.add(child3);
Element root = new Element("root");
root.addContent(l1);
String formattedXML = "<root>\n<child>Hallo Welt</child>\n" + "<child>hello world</child>"
+ "<child>Bonjour le monde</child>\n</root>";
SAXBuilder b = new SAXBuilder();
Document doc = b.build(new ByteArrayInputStream(formattedXML.getBytes(StandardCharsets.UTF_8)));
assertEquals("Elements should be equal", true, MCRXMLHelper.deepEqual(root, doc.getRootElement()));
}
@Test
public void jsonSerialize() throws Exception {
// simple text
Element e = new Element("hallo").setText("Hallo Welt");
JsonObject json = MCRXMLHelper.jsonSerialize(e);
assertEquals("Hallo Welt", json.getAsJsonPrimitive("$text").getAsString());
// attribute
e = new Element("hallo").setAttribute("hallo", "welt");
json = MCRXMLHelper.jsonSerialize(e);
assertEquals("welt", json.getAsJsonPrimitive("_hallo").getAsString());
// complex world class test
URL world = MCRXMLHelperTest.class.getResource("/worldclass.xml");
SAXBuilder builder = new SAXBuilder();
Document worldDocument = builder.build(world.openStream());
json = MCRXMLHelper.jsonSerialize(worldDocument.getRootElement());
assertNotNull(json);
assertEquals("World", json.getAsJsonPrimitive("_ID").getAsString());
assertEquals("http://www.w3.org/2001/XMLSchema-instance", json.getAsJsonPrimitive("_xmlns:xsi").getAsString());
JsonObject deLabel = json.getAsJsonArray("label").get(0).getAsJsonObject();
assertEquals("de", deLabel.getAsJsonPrimitive("_xml:lang").getAsString());
assertEquals("Staaten", deLabel.getAsJsonPrimitive("_text").getAsString());
assertEquals(2, json.getAsJsonObject("categories").getAsJsonArray("category").size());
}
}
| 4,861 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXPathEvaluatorTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRXPathEvaluatorTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* @author Frank LΓΌtzenkirchen
*/
public class MCRXPathEvaluatorTest extends MCRTestCase {
private MCRXPathEvaluator evaluator;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
String builder
= "document[name/@id='n1'][note/@href='#n1'][location/@href='#n1'][name[@id='n2']][location[@href='#n2']]";
Element document = new MCRNodeBuilder().buildElement(builder, null, null);
new Document(document);
Map<String, Object> variables = new HashMap<>();
variables.put("CurrentUser", "gast");
evaluator = new MCRXPathEvaluator(variables, document);
}
@Test
public void testEvaluator() {
assertEquals("n1", evaluator.replaceXPathOrI18n("name[1]/@id"));
assertEquals("n1", evaluator.replaceXPathOrI18n("/document/name[1]/@id"));
}
}
| 1,866 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRXMLParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import org.jdom2.JDOMException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mycore.common.MCRTestCase;
import org.mycore.common.content.MCRURLContent;
/**
* @author Thomas Scheffler (yagee)
*/
public class MCRXMLParserTest extends MCRTestCase {
private URL xmlResource = null;
private Path xmlFile = null;
private URL xmlResourceInvalid = null;
private Path xmlFileInvalid = null;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Override
@Before
public void setUp() throws Exception {
super.setUp();
xmlResource = MCRXMLParserTest.class.getResource("/MCRParserXercesTest-valid.xml");
xmlResourceInvalid = MCRXMLParserTest.class.getResource("/MCRParserXercesTest-invalid.xml");
//MCR-1069: create */../* URI
testFolder.newFolder("foo");
xmlFile = new File(testFolder.getRoot(), "foo/../MCRParserXercesTest-valid.xml").toPath();
xmlFileInvalid = new File(testFolder.getRoot(), "foo/../MCRParserXercesTest-invalid.xml").toPath();
Files.copy(xmlResource.openStream(), xmlFile, StandardCopyOption.REPLACE_EXISTING);
Files.copy(xmlResourceInvalid.openStream(), xmlFileInvalid, StandardCopyOption.REPLACE_EXISTING);
System.out.println(xmlFile.toUri());
}
@Test
public void testInvalidXML() throws IOException, JDOMException {
try {
MCRXMLParserFactory.getValidatingParser().parseXML(new MCRURLContent(xmlResourceInvalid));
fail("MCRParserXerces accepts invalid XML content when validation is requested");
} catch (Exception e) {
}
MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRURLContent(xmlResourceInvalid));
MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRURLContent(xmlFileInvalid.toUri().toURL()));
}
@Test
public void testValidXML() throws IOException, JDOMException {
MCRXMLParserFactory.getValidatingParser().parseXML(new MCRURLContent(xmlResource));
MCRXMLParserFactory.getValidatingParser().parseXML(new MCRURLContent(xmlFile.toUri().toURL()));
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.XMLParser.ValidateSchema", "true");
testProperties.put("log4j.logger.org.mycore.common.xml.MCRParserXerces", "FATAL");
return testProperties;
}
}
| 3,536 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCheckPermissionChainResolverTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRCheckPermissionChainResolverTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import java.util.Map;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.MCRAccessManager;
import org.mycore.access.MCRAccessMock;
import org.mycore.common.MCRTestCase;
public class MCRCheckPermissionChainResolverTest extends MCRTestCase {
private static final String RESOLVER_PREFIX = "checkPermissionChain";
public static final String MOCK_RESOLVER_PREFIX = "Mock";
private static final String MOCK_ID = "mcr_test_00000001";
public static final String PERMISSION_USE_STUFF = "use-stuff";
public static final String MOCK_CALL = MOCK_RESOLVER_PREFIX + ":nothing";
public static final String READ_CALL = RESOLVER_PREFIX + ":" + MOCK_ID + ":" + MCRAccessManager.PERMISSION_READ
+ ":" + MOCK_CALL;
public static final String USE_STUFF_CALL = RESOLVER_PREFIX + "::" + PERMISSION_USE_STUFF + ":" + MOCK_CALL;
final JDOMSource resultSource = new JDOMSource(new Document(new Element("result")));
@Override
public void setUp() throws Exception {
super.setUp();
MCRMockResolver.setResultSource(resultSource);
}
@Test
public void resolveReadObjectForbidden() {
MCRAccessMock.setMethodResult(false);
Assert.assertThrows(TransformerException.class, () -> MCRURIResolver.instance().resolve(READ_CALL, null));
assertReadCall();
Assert.assertEquals("The resolver should not have been called", 0, MCRMockResolver.getCalls().size());
}
@Test
public void resolveReadObjectAllowed() {
MCRAccessMock.setMethodResult(true);
Source result = null;
try {
result = MCRURIResolver.instance().resolve(READ_CALL, null);
} catch (TransformerException e) {
Assert.fail("Exception thrown!");
}
assertReadCall();
Assert.assertEquals("The result source should be returned", resultSource, result);
Assert.assertEquals("The resolver should have been called", 1, MCRMockResolver.getCalls().size());
Assert.assertEquals("The Mock resolver should have been called with the right uri", MOCK_CALL,
MCRMockResolver.getCalls().get(0).getHref());
}
@Test
public void resolvePermissionAllowed() {
MCRAccessMock.setMethodResult(true);
Source result = null;
try {
result = MCRURIResolver.instance().resolve(USE_STUFF_CALL, null);
} catch (TransformerException e) {
Assert.fail("Exception thrown!");
}
assertPermissionCall();
Assert.assertEquals("The result source should be returned", resultSource, result);
Assert.assertEquals("The resolver should have been called", 1, MCRMockResolver.getCalls().size());
Assert.assertEquals("The Mock resolver should have been called with the right uri", MOCK_CALL,
MCRMockResolver.getCalls().get(0).getHref());
}
@Test
public void resolvePermissionForbidden() {
MCRAccessMock.setMethodResult(false);
Assert.assertThrows(TransformerException.class, () -> MCRURIResolver.instance().resolve(USE_STUFF_CALL, null));
assertPermissionCall();
Assert.assertEquals("The resolver should not have been called", 0, MCRMockResolver.getCalls().size());
}
private void assertPermissionCall() {
Assert.assertEquals("There should be a call to the access strategy", 1,
MCRAccessMock.getCheckPermissionCalls().size());
Assert.assertEquals("The call should be made with permission " + PERMISSION_USE_STUFF, PERMISSION_USE_STUFF,
MCRAccessMock.getCheckPermissionCalls().get(0).getPermission());
Assert.assertNull("The call should be made with null as id ",
MCRAccessMock.getCheckPermissionCalls().get(0).getId());
}
private void assertReadCall() {
Assert.assertEquals("There should be a call to the access strategy", 1,
MCRAccessMock.getCheckPermissionCalls().size());
Assert.assertEquals("The call should be made with permission read", MCRAccessManager.PERMISSION_READ,
MCRAccessMock.getCheckPermissionCalls().get(0).getPermission());
Assert.assertEquals("The call should be made with the id " + MOCK_ID, MOCK_ID,
MCRAccessMock.getCheckPermissionCalls().get(0).getId());
}
@Override
public void tearDown() throws Exception {
super.tearDown();
MCRAccessMock.clearCheckPermissionCallsList();
MCRMockResolver.clearCalls();
}
@Override
protected Map<String, String> getTestProperties() {
final Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Access.Class", MCRAccessMock.class.getName());
testProperties.put("MCR.URIResolver.ModuleResolver." + MOCK_RESOLVER_PREFIX, MCRMockResolver.class.getName());
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
return testProperties;
}
}
| 5,908 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMockResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRMockResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
/**
* Can be used to write test against the {@link MCRURIResolver}.
* Just add MCR.URIResolver.ModuleResolver.YOUR_PREFIX with MCRMockResolver.class.getName() to the overwritten
* {@link org.mycore.common.MCRTestCase} getTestProperties()
*/
public class MCRMockResolver implements URIResolver {
private static final List<MCRMockResolverCall> CALLS = new ArrayList<>();
private static Source resultSource = null;
public static List<MCRMockResolverCall> getCalls() {
return Collections.unmodifiableList(CALLS);
}
public static void clearCalls() {
CALLS.clear();
}
public static void setResultSource(Source source) {
resultSource = source;
}
public static Source getResultSource() {
return resultSource;
}
@Override
public Source resolve(String href, String base) {
final MCRMockResolverCall mcrMockResolverCall = new MCRMockResolverCall(href, base);
CALLS.add(mcrMockResolverCall);
return getResultSource();
}
public static class MCRMockResolverCall {
private final String href;
private final String base;
private MCRMockResolverCall(String href, String base) {
this.href = href;
this.base = base;
}
public String getHref() {
return href;
}
public String getBase() {
return base;
}
}
}
| 2,346 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLFunctionsTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRXMLFunctionsTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.text.ParseException;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.MCRConfiguration2;
public class MCRXMLFunctionsTest extends MCRTestCase {
private static final String[] HTML_STRINGS = { "<h1>Hello World!</h1>",
"<h1>Hell<i>o</i> World!<br /></h1>", "<h1>Hell<i>o</i> World!<br></h1>",
"<h1>Hell<i>o</i> World!<br></h1>", "<h1>Hell<i>ö</i> World!<br></h1>",
"<h1>Hello</h1> <h2>World!</h2><br/>", "Hello <a href=\"http://www.mycore.de\">MyCoRe</a>!",
"Hello <a href='http://www.mycore.de'>MyCoRe</a>!",
"GlΓ€ser und Glaskeramiken im MgO-Al<sub>2</sub>O<sub>3</sub>-SiO<sub>2</sub>-System mit hoher MikrohΓ€rte und hohem ElastizitΓ€tsmodul" };
private static final String[] NON_HTML_STRINGS = { "Hello MyCoRe!", "a < b > c" };
/*
* Test method for 'org.mycore.common.xml.MCRXMLFunctions.formatISODate(String, String, String, String)'
*/
@Test
public void formatISODate() throws ParseException {
assertEquals("24.02.1964", MCRXMLFunctions.formatISODate("1964-02-24", "dd.MM.yyyy", "de"));
assertEquals("1571", MCRXMLFunctions.formatISODate("1571", "yyyy", "de"));
}
/*
* Test method for 'org.mycore.common.xml.MCRXMLFunctions.getISODate(String, String)'
*/
@Test
public void getISODate() throws ParseException {
assertEquals("1964-02-24", MCRXMLFunctions.getISODate("24.02.1964", "dd.MM.yyyy", "YYYY-MM-DD"));
assertEquals("Timezone was not correctly detected", "1964-02-23T22:00:00Z", MCRXMLFunctions
.getISODate("24.02.1964 00:00:00 +0200", "dd.MM.yyyy HH:mm:ss Z", "YYYY-MM-DDThh:mm:ssTZD"));
}
/*
* Test method for 'org.mycore.common.xml.MCRXMLFunctions.getISODateFromMCRHistoryDate(String, String, String)'
*/
@Test
public void getISODateFromMCRHistoryDate() {
assertEquals("1964-02-24T00:00:00.000Z",
MCRXMLFunctions.getISODateFromMCRHistoryDate("1964-02-24", "von", "gregorian"));
assertEquals("1964-03-08T00:00:00.000Z",
MCRXMLFunctions.getISODateFromMCRHistoryDate("1964-02-24", "von", "julian"));
assertEquals("1964-02-29T00:00:00.000Z",
MCRXMLFunctions.getISODateFromMCRHistoryDate("1964-02", "bis", "gregorian"));
assertEquals("-0100-12-31T00:00:00.000Z",
MCRXMLFunctions.getISODateFromMCRHistoryDate("100 BC", "bis", "gregorian"));
}
@Test
public void normalizeAbsoluteURL() throws MalformedURLException, URISyntaxException {
String source = "http://www.mycore.de/Space Character.test";
String result = "http://www.mycore.de/Space%20Character.test";
assertEquals("Result URL is not correct", result, MCRXMLFunctions.normalizeAbsoluteURL(source));
assertEquals("URL differs, but was already RFC 2396 conform.", result,
MCRXMLFunctions.normalizeAbsoluteURL(result));
source = "http://www.mycore.de/HΓΌhnerstall.pdf";
result = "http://www.mycore.de/H%C3%BChnerstall.pdf";
assertEquals("Result URL is not correct", result, MCRXMLFunctions.normalizeAbsoluteURL(source));
assertEquals("URL differs, but was already RFC 2396 conform.", result,
MCRXMLFunctions.normalizeAbsoluteURL(result));
}
@Test
public void endodeURIPath() throws URISyntaxException {
String source = "Space Character.test";
String result = "Space%20Character.test";
assertEquals("Result URI path is not correct", result, MCRXMLFunctions.encodeURIPath(source));
source = "HΓΌhnerstall.pdf";
result = "H%C3%BChnerstall.pdf";
assertEquals("Result URI path is not correct", source, MCRXMLFunctions.encodeURIPath(source));
assertEquals("Result URI path is not correct", result, MCRXMLFunctions.encodeURIPath(source, true));
}
@Test
public void decodeURIPath() throws URISyntaxException {
String source = "Space%20Character.test";
String result = "Space Character.test";
assertEquals("Result URI path is not correct", result, MCRXMLFunctions.decodeURIPath(source));
source = "H%C3%BChnerstall.pdf";
result = "HΓΌhnerstall.pdf";
assertEquals("Result URI path is not correct", result, MCRXMLFunctions.decodeURIPath(source));
source = "/New%20Folder";
result = "/New Folder";
assertEquals("Result URI path is not correct", result, MCRXMLFunctions.decodeURIPath(source));
}
@Test
public void shortenText() {
String test = "Foo bar";
String result = "Fooβ¦";
assertEquals("Shortened text did not match", result, MCRXMLFunctions.shortenText(test, 3));
assertEquals("Shortened text did not match", result, MCRXMLFunctions.shortenText(test, 0));
assertEquals("Shortened text did not match", test, MCRXMLFunctions.shortenText(test, test.length()));
}
/*
* Test method for 'org.mycore.common.xml.MCRXMLFunctions.isHtml(String)'
*/
@Test
public void isHtml() {
for (final String s : HTML_STRINGS) {
assertTrue("Should be html: " + s, MCRXMLFunctions.isHtml(s));
}
for (final String s : NON_HTML_STRINGS) {
assertFalse("Should not be html: " + s, MCRXMLFunctions.isHtml(s));
}
}
/*
* Test method for 'org.mycore.common.xml.MCRXMLFunctions.stripHtml(String)'
*/
@Test
public void stripHtml() {
for (final String s : HTML_STRINGS) {
final String stripped = MCRXMLFunctions.stripHtml(s);
assertFalse("Should not contains html: " + stripped, MCRXMLFunctions.isHtml(stripped));
}
}
@Test
public void toNCName() {
assertEquals("master_12345", MCRXMLFunctions.toNCName("master_12345"));
assertEquals("master_12345", MCRXMLFunctions.toNCName("master _12345"));
assertEquals("master_12345", MCRXMLFunctions.toNCName("1 2 master _12345"));
assertEquals("master_1-234", MCRXMLFunctions.toNCName(".-master_!1-23Γ€4~Β§"));
try {
MCRXMLFunctions.toNCName("123");
fail("123 can never be an NCName");
} catch (IllegalArgumentException iae) {
// this exception is expected
}
}
public void toNCNameSecondPart() {
assertEquals("master_12345", MCRXMLFunctions.toNCNameSecondPart("master_12345"));
assertEquals("master_12345", MCRXMLFunctions.toNCNameSecondPart("master _12345"));
assertEquals("12master_12345", MCRXMLFunctions.toNCNameSecondPart("1 2 master _12345"));
assertEquals(".-master_1-234", MCRXMLFunctions.toNCNameSecondPart(".-master_!1-23Γ€4~Β§"));
try {
MCRXMLFunctions.toNCName("123");
fail("123 can never be an NCName");
} catch (IllegalArgumentException iae) {
// this exception is expected
}
}
@Test
public void testNextImportStep() {
MCRConfiguration2.set("MCR.URIResolver.xslImports.xsl-import", "functions/xsl-1.xsl,functions/xsl-2.xsl");
// test with first stylesheet in chain
String next = MCRXMLFunctions.nextImportStep("xsl-import");
assertEquals("functions/xsl-2.xsl", next);
// test with include part
next = MCRXMLFunctions.nextImportStep("xsl-import:functions/xsl-2.xsl");
assertEquals("functions/xsl-1.xsl", next);
// test with last stylesheet in chain
next = MCRXMLFunctions.nextImportStep("xsl-import:functions/xsl-1.xsl");
assertEquals("", next);
}
}
| 8,620 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNodeBuilderTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/xml/MCRNodeBuilderTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.jaxen.JaxenException;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRTestCase;
/**
* @author Frank LΓΌtzenkirchen
*/
public class MCRNodeBuilderTest extends MCRTestCase {
@Test
public void testBuildingElements() throws JaxenException {
Element built = new MCRNodeBuilder().buildElement("element", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
assertTrue(built.getText().isEmpty());
built = new MCRNodeBuilder().buildElement("element", "text", null);
assertNotNull(built);
assertEquals("element", built.getName());
assertEquals("text", built.getText());
Element root = new Element("root");
built = new MCRNodeBuilder().buildElement("element", null, root);
assertNotNull(built);
assertEquals("element", built.getName());
assertNotNull(built.getParentElement());
assertEquals("root", built.getParentElement().getName());
}
@Test
public void testBuildingAttributes() throws JaxenException {
Attribute built = new MCRNodeBuilder().buildAttribute("@attribute", null, null);
assertNotNull(built);
assertEquals("attribute", built.getName());
assertTrue(built.getValue().isEmpty());
built = new MCRNodeBuilder().buildAttribute("@attribute", "value", null);
assertNotNull(built);
assertEquals("attribute", built.getName());
assertEquals("value", built.getValue());
Element parent = new Element("parent");
built = new MCRNodeBuilder().buildAttribute("@attribute", null, parent);
assertNotNull(built);
assertEquals("attribute", built.getName());
assertNotNull(built.getParent());
assertEquals("parent", built.getParent().getName());
}
@Test
public void testBuildingValues() throws JaxenException {
Attribute built = new MCRNodeBuilder().buildAttribute("@attribute='A \"test\"'", "ignore", null);
assertNotNull(built);
assertEquals("attribute", built.getName());
assertEquals("A \"test\"", built.getValue());
built = new MCRNodeBuilder().buildAttribute("@attribute=\"O'Brian\"", null, null);
assertNotNull(built);
assertEquals("attribute", built.getName());
assertEquals("O'Brian", built.getValue());
built = new MCRNodeBuilder().buildAttribute("@mime=\"text/plain\"", null, null);
assertNotNull(built);
assertEquals("mime", built.getName());
assertEquals("text/plain", built.getValue());
Element element = new MCRNodeBuilder().buildElement("name=\"O'Brian\"", null, null);
assertNotNull(element);
assertEquals("name", element.getName());
assertEquals("O'Brian", element.getText());
}
@Test
public void testBuildingTrees() throws JaxenException {
Element root = new Element("root");
Attribute built = new MCRNodeBuilder().buildAttribute("parent/child/@attribute", null, root);
assertNotNull(built);
assertEquals("attribute", built.getName());
assertNotNull(built.getParent());
assertEquals("child", built.getParent().getName());
assertNotNull(built.getParent().getParentElement());
assertEquals("parent", built.getParent().getParentElement().getName());
assertNotNull(built.getParent().getParentElement().getParentElement());
assertEquals("root", built.getParent().getParentElement().getParentElement().getName());
}
@Test
public void testFirstNodeBuilt() throws JaxenException {
MCRNodeBuilder builder = new MCRNodeBuilder();
builder.buildElement("element", null, null);
assertEquals("element", ((Element) (builder.getFirstNodeBuilt())).getName());
builder = new MCRNodeBuilder();
builder.buildAttribute("@attribute", null, null);
assertEquals("attribute", ((Attribute) (builder.getFirstNodeBuilt())).getName());
builder = new MCRNodeBuilder();
builder.buildElement("element", "value", null);
assertEquals("element", ((Element) (builder.getFirstNodeBuilt())).getName());
builder = new MCRNodeBuilder();
builder.buildAttribute("@attribute", "value", null);
assertEquals("attribute", ((Attribute) (builder.getFirstNodeBuilt())).getName());
builder = new MCRNodeBuilder();
Element parent = builder.buildElement("root/parent", null, null);
assertEquals("root", ((Element) (builder.getFirstNodeBuilt())).getName());
builder = new MCRNodeBuilder();
builder.buildElement("parent/child/grandchild", null, parent.getParent());
assertEquals("child", ((Element) (builder.getFirstNodeBuilt())).getName());
builder = new MCRNodeBuilder();
builder.buildElement("parent/child/grandchild", null, parent.getParent());
assertNull(builder.getFirstNodeBuilt());
builder = new MCRNodeBuilder();
builder.buildElement("parent/child[2]/grandchild", null, parent.getParent());
assertEquals("child", ((Element) (builder.getFirstNodeBuilt())).getName());
}
@Test
public void testSimplePredicates() throws JaxenException {
Element built = new MCRNodeBuilder().buildElement("element[child]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
assertNotNull(built.getChild("child"));
built = new MCRNodeBuilder().buildElement("element[child/grandchild]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
assertNotNull(built.getChild("child"));
assertNotNull(built.getChild("child").getChild("grandchild"));
built = new MCRNodeBuilder().buildElement("parent[child1]/child2", null, null);
assertNotNull(built);
assertEquals("child2", built.getName());
assertNotNull(built.getParentElement());
assertEquals("parent", built.getParentElement().getName());
assertNotNull(built.getParentElement().getChild("child1"));
}
@Test
public void testPredicatesWithValues() throws JaxenException {
Element built = new MCRNodeBuilder()
.buildElement("contributor[role/roleTerm[@type='code'][@authority='ude']='author']", null, null);
assertNotNull(built);
assertEquals("contributor", built.getName());
assertNotNull(built.getChild("role"));
assertNotNull(built.getChild("role").getChild("roleTerm"));
assertEquals("code", built.getChild("role").getChild("roleTerm").getAttributeValue("type"));
assertEquals("ude", built.getChild("role").getChild("roleTerm").getAttributeValue("authority"));
}
@Test
public void testMultiplePredicates() throws JaxenException {
Element built = new MCRNodeBuilder().buildElement("element[child1][child2]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
assertNotNull(built.getChild("child1"));
assertNotNull(built.getChild("child2"));
}
@Test
public void testNestedPredicates() throws JaxenException {
Element built = new MCRNodeBuilder().buildElement("element[child[grandchild1]/grandchild2]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
assertNotNull(built.getChild("child"));
assertNotNull(built.getChild("child").getChild("grandchild1"));
assertNotNull(built.getChild("child").getChild("grandchild2"));
}
@Test
public void testExpressionsToIgnore() throws JaxenException {
Element built = new MCRNodeBuilder().buildElement("element[2]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
built = new MCRNodeBuilder().buildElement("element[contains(.,'foo')]", null, null);
assertNotNull(built);
assertEquals("element", built.getName());
built = new MCRNodeBuilder().buildElement("foo|bar", null, null);
assertNull(built);
Attribute attribute = new MCRNodeBuilder().buildAttribute("@lang[preceding::*/foo='bar']", "value", null);
assertNotNull(attribute);
assertEquals("lang", attribute.getName());
assertEquals("value", attribute.getValue());
built = new MCRNodeBuilder().buildElement("parent/child/following::node/foo='bar'", null, null);
assertNotNull(built);
assertEquals("child", built.getName());
assertNotNull(built.getParentElement());
assertEquals("parent", built.getParentElement().getName());
assertEquals(0, built.getChildren().size());
assertEquals("", built.getText());
}
@Test
public void testAlreadyExisting() throws JaxenException {
Element existingChild = new MCRNodeBuilder().buildElement("parent/child", null, null);
Element existingParent = existingChild.getParentElement();
assertEquals(existingChild, new MCRNodeBuilder().buildNode("child", null, existingParent));
Attribute existingAttribute = new MCRNodeBuilder().buildAttribute("parent/@attribute", null, null);
existingParent = existingAttribute.getParent();
Attribute resolvedAttribute = new MCRNodeBuilder().buildAttribute("@attribute", null, existingParent);
assertEquals(existingAttribute, resolvedAttribute);
assertEquals(existingParent, resolvedAttribute.getParent());
Element child = new MCRNodeBuilder().buildElement("root/parent/child", null, null);
Element root = child.getParentElement().getParentElement();
Attribute attribute = new MCRNodeBuilder().buildAttribute("parent/child/@attribute", null, root);
assertEquals(child, attribute.getParent());
Element foo = new MCRNodeBuilder().buildElement("parent[child]/foo", null, root);
assertEquals(child, foo.getParentElement().getChild("child"));
Element parentWithChildValueX = new MCRNodeBuilder().buildElement("parent[child='X']", null, root);
assertNotSame(child.getParentElement(), parentWithChildValueX);
Element resolved = new MCRNodeBuilder().buildElement("parent[child='X']", null, root);
assertEquals(parentWithChildValueX, resolved);
child = new MCRNodeBuilder().buildElement("parent/child='X'", null, root);
assertNotNull(child);
assertEquals(parentWithChildValueX.getChild("child"), child);
}
@Test
public void testNamespaces() throws JaxenException {
Element role = new MCRNodeBuilder().buildElement("mods:name[@xlink:href='id']/mods:role[@type='creator']", null,
null);
assertEquals("role", role.getName());
assertEquals(MCRConstants.MODS_NAMESPACE, role.getNamespace());
assertEquals("creator", role.getAttributeValue("type"));
assertEquals("id", role.getParentElement().getAttribute("href", MCRConstants.XLINK_NAMESPACE).getValue());
}
@Test
public void testAssigningValueToLastGenreatedNode() throws JaxenException {
String value = "value";
Element generated = new MCRNodeBuilder().buildElement("titleInfo/title", value, null);
assertEquals(value, generated.getText());
assertNotEquals(value, generated.getParentElement().getText());
}
@Test
public void testBuildingNodeName() throws JaxenException {
Element generated = new MCRNodeBuilder().buildElement("mycoreobject/metadata/def.modsContainer/modsContainer",
null, null);
assertEquals("modsContainer", generated.getName());
assertEquals("def.modsContainer", generated.getParentElement().getName());
}
@Test
public void testBuildingRootComponents() throws JaxenException {
Element existingRoot = new Element("root");
existingRoot.setAttribute("type", "existing");
Document document = new Document(existingRoot);
Element returned = new MCRNodeBuilder().buildElement("root", null, document);
assertSame(existingRoot, returned);
returned = new MCRNodeBuilder().buildElement("root[foo]", null, document);
assertSame(existingRoot, returned);
assertNotNull(returned.getChild("foo"));
returned = new MCRNodeBuilder().buildElement("root[@foo='bar']", null, document);
assertSame(existingRoot, returned);
assertEquals("bar", returned.getAttributeValue("foo"));
returned = new MCRNodeBuilder().buildElement("root/child", "bar", document);
assertEquals("child", returned.getName());
assertSame(existingRoot, returned.getParent());
assertEquals("bar", returned.getText());
}
}
| 13,917 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTableMessageTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/log/MCRTableMessageTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.log;
import static org.junit.Assert.assertEquals;
import java.util.Optional;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.log.MCRTableMessage.Column;
public class MCRTableMessageTest extends MCRTestCase {
private static final String SEPARATOR = System.lineSeparator();
@Test
public void emptyTable() {
MCRTableMessage<Number> table = new MCRTableMessage<>(new Column<>("Arabic", Number::number),
new Column<>("Roman", Number::roman), new Column<>("English", Number::english));
String message = table.logMessage("Introduction");
String expected = "Introduction" + SEPARATOR +
"β Arabic β Roman β English β" + SEPARATOR +
"ββββββββββΌββββββββΌββββββββββ€";
assertEquals(expected, message);
}
@Test
public void columnLEssTable() {
MCRTableMessage<Number> table = new MCRTableMessage<>();
table.add(new Number(0, Optional.empty(), "zero"));
table.add(new Number(1, Optional.of("I"), "one"));
table.add(new Number(23, Optional.of("XXIII"), "twenty-three"));
table.add(new Number(42, Optional.of("XLII"), "forty-two"));
String message = table.logMessage("Introduction");
String expected = "Introduction";
assertEquals(expected, message);
}
@Test
public void simpleTable() {
MCRTableMessage<Number> table = new MCRTableMessage<>(new Column<>("Arabic", Number::number),
new Column<>("Roman", Number::roman), new Column<>("English", Number::english));
table.add(new Number(0, Optional.empty(), "zero"));
table.add(new Number(1, Optional.of("I"), "one"));
table.add(new Number(23, Optional.of("XXIII"), "twenty-three"));
table.add(new Number(42, Optional.of("XLII"), "forty-two"));
String message = table.logMessage("Introduction");
String expected = "Introduction" + SEPARATOR +
"β Arabic β Roman β English β" + SEPARATOR +
"ββββββββββΌββββββββΌβββββββββββββββ€" + SEPARATOR +
"β 0 β β zero β" + SEPARATOR +
"β 1 β I β one β" + SEPARATOR +
"β 23 β XXIII β twenty-three β" + SEPARATOR +
"β 42 β XLII β forty-two β";
assertEquals(expected, message);
}
private record Number(int number, Optional<String> roman, String english) {
}
}
| 3,386 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRThrowFunctionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/function/MCRThrowFunctionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.function;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
public class MCRThrowFunctionTest {
@Test
public void testToFunctionBiFunctionOfTERClassOfQsuperE() {
Optional<String> findFirst = Stream.of("passed")
.map(((MCRThrowFunction<String, String, IOException>) MCRThrowFunctionTest::failExceptionally)
.toFunction(MCRThrowFunctionTest::mayhandleException, IOException.class))
.findFirst();
assertEquals("Junit test:passed", findFirst.get());
}
@Test(expected = IOException.class)
public void testToFunction() throws IOException {
try {
Stream.of("passed").map(
((MCRThrowFunction<String, String, IOException>) MCRThrowFunctionTest::failExceptionally).toFunction())
.findFirst();
} catch (RuntimeException e) {
if (e.getCause() != null && e.getCause() instanceof IOException ioe) {
throw ioe;
}
throw e;
}
}
public static String failExceptionally(String input) throws IOException {
throw new IOException("Junit test");
}
public static String mayhandleException(String input, IOException e) {
return e.getMessage() + ":" + input;
}
}
| 2,135 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHeaderInputStreamTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/content/streams/MCRHeaderInputStreamTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.content.streams;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import org.junit.Test;
/**
* @author Frank LΓΌtzenkirchen
*/
public class MCRHeaderInputStreamTest {
@Test
public void emptyStream() throws Exception {
MCRHeaderInputStream h = new MCRHeaderInputStream(new ByteArrayInputStream(new byte[0]));
assertEquals(0, h.getHeader().length);
assertEquals(-1, h.read());
h.close();
}
@Test
public void smallStream() throws Exception {
byte[] data = "data".getBytes();
MCRHeaderInputStream h = new MCRHeaderInputStream(new ByteArrayInputStream(data));
assertArrayEquals(data, h.getHeader());
for (byte aData : data) {
assertEquals(aData, (byte) (h.read()));
}
assertEquals(-1, h.read());
h.close();
}
@Test
public void largeStream() throws Exception {
byte[] data = new byte[MCRHeaderInputStream.MAX_HEADER_SIZE + 1000];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) i;
}
MCRHeaderInputStream h = new MCRHeaderInputStream(new ByteArrayInputStream(data));
assertEquals(MCRHeaderInputStream.MAX_HEADER_SIZE, h.getHeader().length);
for (int i = 0; i < MCRHeaderInputStream.MAX_HEADER_SIZE; i++) {
assertEquals(data[i], h.getHeader()[i]);
}
for (byte aData : data) {
assertEquals(aData, (byte) (h.read()));
}
assertEquals(-1, h.read());
h.close();
}
}
| 2,368 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMD5InputStreamTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/common/content/streams/MCRMD5InputStreamTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should 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.content.streams;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.ByteArrayInputStream;
import org.junit.Test;
import org.mycore.common.MCRUtils;
import org.mycore.datamodel.ifs2.MCRFile;
/**
* @author Frank LΓΌtzenkirchen
*/
public class MCRMD5InputStreamTest {
@Test
public void emptyStream() throws Exception {
MCRMD5InputStream m = new MCRMD5InputStream(new ByteArrayInputStream(new byte[0]));
assertEquals(-1, m.read());
m.close();
assertEquals(MCRFile.MD5_OF_EMPTY_FILE, m.getMD5String());
}
@Test
public void smallStream() throws Exception {
byte[] data = "data".getBytes();
MCRMD5InputStream m = new MCRMD5InputStream(new ByteArrayInputStream(data));
for (byte aData : data) {
assertEquals(aData, (byte) (m.read()));
}
assertEquals(-1, m.read());
m.close();
assertFalse(MCRFile.MD5_OF_EMPTY_FILE.equals(m.getMD5String()));
assertEquals(16, m.getMD5().length);
assertEquals(32, m.getMD5String().length());
}
@Test
public void testUtils() throws Exception {
String md5 = MCRUtils.getMD5Sum(new ByteArrayInputStream(new byte[0]));
assertEquals(MCRFile.MD5_OF_EMPTY_FILE, md5);
}
}
| 2,072 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBooleanClauseParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/parser/bool/MCRBooleanClauseParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parser.bool;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.parsers.bool.MCRAndCondition;
import org.mycore.parsers.bool.MCRBooleanClauseParser;
import org.mycore.parsers.bool.MCRCondition;
import org.mycore.parsers.bool.MCRFalseCondition;
import org.mycore.parsers.bool.MCROrCondition;
import org.mycore.parsers.bool.MCRParseException;
import org.mycore.parsers.bool.MCRTrueCondition;
/**
* This class is a JUnit test case for org.mycore.MCRBooleanClausParser.
*
* @author Jens Kupferschmidt
*/
public class MCRBooleanClauseParserTest {
MCRBooleanClauseParser<Object> p = new MCRBooleanClauseParser<>();
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testSingleStrings() {
MCROrCondition c01 = new MCROrCondition(new MCRTrueCondition(),
new MCRFalseCondition(), new MCRTrueCondition());
System.out.println("Boolean claus test 1 --> " + c01);
assertEquals("Returned value is not", c01.toString(), p.parse("true or false or true").toString());
assertEquals("Returned value is not", c01.toString(), p.parse("(true) or (false) or (true)").toString());
MCROrCondition c02 = new MCROrCondition(new MCRTrueCondition(),
new MCROrCondition(new MCRFalseCondition(), new MCRTrueCondition()));
assertEquals("Returned value is not", c02.toString(), p.parse("true or (false or true)").toString());
assertEquals("Returned value is not", c02.toString(), p.parse("(true ) or ( ((false) or (true)))").toString());
MCRAndCondition c03 = new MCRAndCondition(new MCRTrueCondition(),
new MCRFalseCondition(), new MCRTrueCondition());
System.out.println("Boolean claus test 3 --> " + c03);
assertEquals("Returned value is not", c03.toString(), p.parse("true and false and true").toString());
MCROrCondition c04 = new MCROrCondition(new MCRTrueCondition(), new MCRAndCondition(
new MCRFalseCondition(), new MCRTrueCondition()));
System.out.println("Boolean claus test 4 --> " + c04);
assertEquals("Returned value is not", c04.toString(), p.parse("true or false and true").toString());
MCRCondition c05 = new MCRTrueCondition();
System.out.println("Boolean claus test 5 --> " + c05);
assertEquals("Returned value is not", c05.toString(), p.parse("true").toString());
assertEquals("Returned value is not", c05.toString(), p.parse("(true)").toString());
assertEquals("Returned value is not", c05.toString(), p.parse("(true )").toString());
try {
p.parse("(true").toString();
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
final String msg = "Syntax error: missing bracket in \"(true\"";
assertEquals(msg, e.getMessage());
}
try {
p.parse("(true) or false) or (true)").toString();
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
final String msg = "Syntax error: missing bracket in \"@<0>@ or false) or @<1>@\"";
assertEquals(msg, e.getMessage());
}
try {
p.parse("true and (false and true").toString();
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
final String msg = "Syntax error: missing bracket in \"true and (false and true\"";
assertEquals(msg, e.getMessage());
}
try {
p.parse("((((true or false))))) and true)").toString();
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
final String msg = "Syntax error: missing bracket in \"@<3>@) and true)\"";
assertEquals(msg, e.getMessage());
}
try {
p.parse("true or true or (true or true))))").toString();
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
final String msg = "Syntax error: missing bracket in \"true or true or @<0>@)))\"";
assertEquals(msg, e.getMessage());
}
try {
p.parse("(true ) or ((((((((( ((false) or (true))").toString();
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
System.out.println("##" + e.getMessage() + "##");
final String msg = "Syntax error: missing bracket in \"@<0>@ or ((((((((( @<3>@\"";
assertEquals(msg, e.getMessage());
}
}
@Test
public void testSingleElements() {
Element bool01 = new Element("boolean");
bool01.setAttribute("operator", "true");
try {
p.parse(bool01);
} catch (MCRParseException e) {
fail("Should not thorwn MCRParseException!");
}
Element bool02 = new Element("boolean");
bool02.setAttribute("operator", "truhe");
try {
p.parse(bool02);
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
System.out.println("##" + e.getMessage() + "##");
final String msg = "Syntax error: <truhe>";
assertEquals(msg, e.getMessage());
}
Element bool03 = new Element("boolean");
bool03.setAttribute("operators", "true");
try {
p.parse(bool03);
fail("Should have thrown MCRParseException but did not!");
} catch (MCRParseException e) {
System.out.println("##" + e.getMessage() + "##");
final String msg = "Syntax error: attribute operator not found";
assertEquals(msg, e.getMessage());
}
}
}
| 6,675 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTopologicalSortTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/tools/MCRTopologicalSortTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tools;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* TestCase for Topological Sort
* from: Cormen et.all "Introduction to Algorithms Section 22.4"
* Topological Sort, S. 550
*/
public class MCRTopologicalSortTest extends MCRTestCase {
@Test
public void dressOK() {
MCRTopologicalSort<String> ts = new MCRTopologicalSort<>();
ts.addNode("belt");
ts.addNode("jacket");
ts.addNode("pants");
ts.addNode("shirt");
ts.addNode("shoes");
ts.addNode("socks");
ts.addNode("tie");
ts.addNode("undershorts");
ts.addNode("watch");
ts.addEdge(ts.getNodeID("undershorts"), ts.getNodeID("pants"));
ts.addEdge(ts.getNodeID("undershorts"), ts.getNodeID("shoes"));
ts.addEdge(ts.getNodeID("socks"), ts.getNodeID("shoes"));
ts.addEdge(ts.getNodeID("pants"), ts.getNodeID("belt"));
ts.addEdge(ts.getNodeID("belt"), ts.getNodeID("jacket"));
ts.addEdge(ts.getNodeID("shirt"), ts.getNodeID("belt"));
ts.addEdge(ts.getNodeID("shirt"), ts.getNodeID("tie"));
ts.addEdge(ts.getNodeID("tie"), ts.getNodeID("jacket"));
int[] order = ts.doTopoSort();
Assert.assertNotNull("Possible Dress Order created", order);
}
/**
* TestCase for Topological Sort
* from: Cormen et.all "Introduction to Algorithms Section 22.4"
* Topological Sort, S. 550
*/
@Test
public void dressWrong() {
MCRTopologicalSort<String> ts = new MCRTopologicalSort<>();
ts.addNode("belt");
ts.addNode("jacket");
ts.addNode("pants");
ts.addNode("shirt");
ts.addNode("shoes");
ts.addNode("socks");
ts.addNode("tie");
ts.addNode("undershorts");
ts.addNode("watch");
ts.addEdge(ts.getNodeID("undershorts"), ts.getNodeID("pants"));
ts.addEdge(ts.getNodeID("undershorts"), ts.getNodeID("shoes"));
ts.addEdge(ts.getNodeID("socks"), ts.getNodeID("shoes"));
ts.addEdge(ts.getNodeID("pants"), ts.getNodeID("belt"));
ts.addEdge(ts.getNodeID("belt"), ts.getNodeID("jacket"));
ts.addEdge(ts.getNodeID("shirt"), ts.getNodeID("belt"));
ts.addEdge(ts.getNodeID("shirt"), ts.getNodeID("tie"));
ts.addEdge(ts.getNodeID("tie"), ts.getNodeID("jacket"));
ts.addEdge(ts.getNodeID("shoes"), ts.getNodeID("socks"));
int[] order = ts.doTopoSort();
Assert.assertNull("Dress Order was wrong", order);
Assert.assertTrue("Circle list contains [socks->shoes]", ts.toString().contains("[socks->shoes]"));
Assert.assertTrue("Circle list contains [shoes->socks]", ts.toString().contains("[shoes->socks]"));
}
}
| 3,522 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MyCoReWebPageProviderTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/tools/MyCoReWebPageProviderTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tools;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
public class MyCoReWebPageProviderTest extends MCRTestCase {
@Test
public void addSection() throws Exception {
MyCoReWebPageProvider wp = new MyCoReWebPageProvider();
// simple test
Element content = new Element("content");
content.setText("sample text");
Element section = wp.addSection("title1", content, "de");
assertNotNull(section);
assertEquals("title1", section.getAttributeValue("title"));
assertEquals("de", section.getAttributeValue("lang", Namespace.XML_NAMESPACE));
assertEquals("sample text", section.getChild("content").getText());
// xml text surrounded by p-tag
Element section2 = wp.addSection("title2", "<p>text test</p>", "en");
assertEquals("title2", section2.getAttributeValue("title"));
assertEquals("en", section2.getAttributeValue("lang", Namespace.XML_NAMESPACE));
assertEquals("text test", section2.getChild("p").getText());
// only text
Element section3 = wp.addSection("title3", "simple text", "uk");
assertEquals("simple text", section3.getChild("p").getText());
// multi tags
Element section4 = wp.addSection("title4", "<b>bold</b><i>italic</i>", "at");
assertEquals(2, section4.getChildren().size());
// check section count
assertEquals(4, wp.getXML().getRootElement().getContentSize());
// entities
wp.addSection("title5", " &äHallo", "de");
// custom tags
wp.addSection("title6", "<p><printlatestobjects /></p>", "de");
}
@Test
public void updateMeta() {
MyCoReWebPageProvider wp = new MyCoReWebPageProvider();
wp.updateMeta("myId", "myPath");
Element rootElement = wp.getXML().getRootElement();
Element meta = rootElement.getChild("meta");
assertNotNull(meta);
Element log = meta.getChild("log");
assertNotNull(log);
assertNotNull(log.getAttribute("date"));
assertNotNull(log.getAttribute("time"));
assertEquals("myId", log.getAttributeValue("lastEditor"));
assertEquals("myPath", log.getAttributeValue("labelPath"));
}
}
| 3,154 | 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.