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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRIIIFAnnotation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/additional/MCRIIIFAnnotation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.additional;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFResource;
import org.mycore.iiif.presentation.model.basic.MCRIIIFCanvas;
public class MCRIIIFAnnotation extends MCRIIIFAnnotationBase {
public static final String TYPE = "@oa:Annotation";
private MCRIIIFResource resource;
public MCRIIIFAnnotation(String id, MCRIIIFCanvas parent) {
super(id, parent, TYPE);
}
public MCRIIIFResource getResource() {
return resource;
}
public void setResource(MCRIIIFResource resource) {
this.resource = resource;
}
}
| 1,354 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFAnnotationList.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/additional/MCRIIIFAnnotationList.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.additional;
import java.util.ArrayList;
import java.util.List;
import org.mycore.iiif.presentation.model.basic.MCRIIIFCanvas;
public class MCRIIIFAnnotationList extends MCRIIIFAnnotationBase {
public List<MCRIIIFAnnotation> resources = new ArrayList<>();
public MCRIIIFAnnotationList(String id, MCRIIIFCanvas parent) {
super(id, parent, "sc:AnnotationList");
}
}
| 1,158 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFAnnotationBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/additional/MCRIIIFAnnotationBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.additional;
import org.mycore.iiif.presentation.model.MCRIIIFPresentationBase;
import org.mycore.iiif.presentation.model.basic.MCRIIIFCanvas;
public class MCRIIIFAnnotationBase extends MCRIIIFPresentationBase {
// custom serializer needed
protected String on;
private String label;
private String description;
private String motivation = "sc:painting";
private transient MCRIIIFCanvas parent;
public MCRIIIFAnnotationBase(String id, MCRIIIFCanvas parent, String type) {
super(id, type, API_PRESENTATION_2);
this.parent = parent;
refresh();
}
public void refresh() {
this.on = this.parent.getId();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMotivation() {
return motivation;
}
public void setMotivation(String motivation) {
this.motivation = motivation;
}
}
| 1,927 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/model/MCRIIIFBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.model;
import com.google.gson.annotations.SerializedName;
/**
* Base Class for most IIIF model classes
*/
public class MCRIIIFBase implements Cloneable {
public static final String API_PRESENTATION_2 = "http://iiif.io/api/presentation/2/context.json";
public static final String API_IMAGE_2 = "http://iiif.io/api/image/2/context.json";
@SerializedName("@context")
private String context;
@SerializedName("@type")
private String type;
@SerializedName("@id")
private String id;
public MCRIIIFBase(String id, String type, String context) {
if (id != null) {
this.id = id;
}
if (context != null) {
this.context = context;
}
if (type != null) {
this.type = type;
}
}
public MCRIIIFBase(String type, String context) {
this(null, type, context);
}
public MCRIIIFBase(String context) {
this(null, context);
}
public MCRIIIFBase() {
this(null);
}
public String getContext() {
return context;
}
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setContext(String context) {
this.context = context;
}
public void setType(String type) {
this.type = type;
}
public void setId(String id) {
this.id = id;
}
}
| 2,173 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSDefaultSectionProviderTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/test/java/org/mycore/wcms2/MCRWCMSDefaultSectionProviderTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import org.junit.Test;
import org.mycore.wcms2.navigation.MCRWCMSDefaultSectionProvider;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class MCRWCMSDefaultSectionProviderTest {
@Test
public void toJSON() throws Exception {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("src/test/resources/navigation/content.xml"));
MCRWCMSDefaultSectionProvider provider = new MCRWCMSDefaultSectionProvider();
JsonArray sectionArray = provider.toJSON(doc.getRootElement());
assertEquals(2, sectionArray.size());
// test section one
JsonObject section1 = (JsonObject) sectionArray.get(0);
assertEquals("Title one", section1.getAsJsonPrimitive("title").getAsString());
assertEquals("de", section1.getAsJsonPrimitive("lang").getAsString());
assertEquals("<p>Content one</p><br />", section1.getAsJsonPrimitive("data").getAsString());
// test section two
JsonObject section2 = (JsonObject) sectionArray.get(1);
assertEquals("Title two", section2.getAsJsonPrimitive("title").getAsString());
assertEquals("en", section2.getAsJsonPrimitive("lang").getAsString());
assertEquals("Content two", section2.getAsJsonPrimitive("data").getAsString());
}
}
| 2,207 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
DefaultNavigationProviderTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/test/java/org/mycore/wcms2/DefaultNavigationProviderTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.mycore.wcms2.navigation.MCRWCMSDefaultNavigationProvider;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* TODO: fix this test
*
* @author michel
*
*/
public class DefaultNavigationProviderTest {
@SuppressWarnings("unused")
private MCRWCMSDefaultNavigationProvider navProv;
@Test
public void toJSON() throws Exception {
MCRWCMSUtil.load(new File("src/test/resources/navigation/navigation.xml"));
this.navProv = new MCRWCMSDefaultNavigationProvider();
// JsonObject jsonNavigation = this.navProv.toJSON(navigation);
// test hierarchy
// JsonArray hierarchy = jsonNavigation.get("hierarchy").getAsJsonArray();
// JsonObject navRootItem = hierarchy.get(0).getAsJsonObject();
// JsonArray rootChildren = navRootItem.get("children").getAsJsonArray();
// assertEquals(2, rootChildren.size());
// JsonObject navMenuItem = rootChildren.get(0).getAsJsonObject();
// JsonArray menuChildren = navMenuItem.get("children").getAsJsonArray();
// assertEquals(2, menuChildren.size());
// test items
// JsonArray items = jsonNavigation.get("items").getAsJsonArray();
// // test root
// JsonObject rootItem = getByWCMSType("root", items).get(0);
// assertNotNull(rootItem);
// assertEquals("{tenantPath}/content/below/index.xml", rootItem.getAsJsonPrimitive("hrefStartingPage").getAsString());
// assertEquals("/content", rootItem.getAsJsonPrimitive("dir").getAsString());
// assertEquals("main title", rootItem.getAsJsonPrimitive("mainTitle").getAsString());
// assertEquals("history title", rootItem.getAsJsonPrimitive("historyTitle").getAsString());
// assertEquals("template1", rootItem.getAsJsonPrimitive("template").getAsString());
// assertEquals("DocPortal", rootItem.getAsJsonPrimitive("parentTenant").getAsString());
// assertEquals("/content/test.xml", rootItem.getAsJsonPrimitive("parentPage").getAsString());
// JsonArray includeList = rootItem.get("include").getAsJsonArray();
// assertEquals(1, includeList.size());
// assertEquals("test:sample", includeList.get(0).getAsJsonPrimitive().getAsString());
// // test menu
// JsonObject menuItem = getByWCMSType("menu", items).get(0);
// assertNotNull(menuItem);
// assertEquals("main", menuItem.getAsJsonPrimitive("id").getAsString());
// assertEquals("/content/main", menuItem.getAsJsonPrimitive("dir").getAsString());
// JsonObject label = menuItem.get("labelMap").getAsJsonObject();
// assertEquals("Hauptmenü links", label.getAsJsonPrimitive("de").getAsString());
// assertEquals("Main menu left", label.getAsJsonPrimitive("en").getAsString());
// // test includes
// for(JsonObject includeItem : getByWCMSType("include", items)) {
// String ref = includeItem.getAsJsonPrimitive("ref").getAsString();
// String uri = includeItem.getAsJsonPrimitive("uri").getAsString();
// if(ref != null)
// assertEquals("search", ref);
// if(uri != null)
// assertEquals("test:insertUri", uri);
// }
// test item
// JsonObject item = getByWebpageId("/editor_form_search-expert.xml", items);
// assertNotNull(item);
// assertEquals("extern", item.getAsJsonPrimitive("type").getAsString());
// assertEquals("_self", item.getAsJsonPrimitive("target").getAsString());
// assertEquals(false, item.getAsJsonPrimitive("replaceMenu").getAsBoolean());
// assertEquals(true, item.getAsJsonPrimitive("constrainPopUp").getAsBoolean());
// assertEquals("template2", item.getAsJsonPrimitive("template").getAsString());
// assertEquals("bold", item.getAsJsonPrimitive("style").getAsString());
// JsonObject label2 = item.get("labelMap").getAsJsonObject();
// assertEquals("Expertensuche", label2.getAsJsonPrimitive("de").getAsString());
// assertEquals("Expert Search", label2.getAsJsonPrimitive("en").getAsString());
}
@SuppressWarnings("unused")
private List<JsonObject> getByWCMSType(String type, JsonArray items) {
List<JsonObject> itemList = new ArrayList<>();
for (JsonElement e : items) {
JsonObject item = (JsonObject) e;
if (item.getAsJsonPrimitive("wcmsType").getAsString().equals(type)) {
itemList.add(item);
}
}
return itemList;
}
@SuppressWarnings("unused")
private JsonObject getByWebpageId(String id, JsonArray items) {
for (JsonElement e : items) {
JsonObject item = (JsonObject) e;
if (item.getAsJsonPrimitive("href") != null && item.getAsJsonPrimitive("href").getAsString().equals(id)) {
return item;
}
}
return null;
}
@Test
public void fromJSON() {
// TODO
}
}
| 6,285 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
NavigationTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/test/java/org/mycore/wcms2/datamodel/NavigationTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMResult;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
public class NavigationTest {
private MCRNavigation navigation;
@Before
public void setup() {
this.navigation = new MCRNavigation();
this.navigation.setTemplate("template_mysample");
this.navigation.setDir("/content");
this.navigation.setHistoryTitle("History Title");
this.navigation.setHrefStartingPage("/content/below/index.xml");
this.navigation.setMainTitle("Main Title");
MCRNavigationMenuItem menu1 = new MCRNavigationMenuItem();
menu1.setId("main");
MCRNavigationMenuItem menu2 = new MCRNavigationMenuItem();
menu1.setId("below");
MCRNavigationInsertItem insert1 = new MCRNavigationInsertItem();
insert1.setURI("myuri:workflow");
this.navigation.addMenu(menu1);
this.navigation.addInsertItem(insert1);
this.navigation.addMenu(menu2);
}
@Test
public void toXML() throws Exception {
JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class);
Marshaller m = jc.createMarshaller();
JDOMResult JDOMResult = new JDOMResult();
m.marshal(this.navigation, JDOMResult);
Element navigationElement = JDOMResult.getDocument().getRootElement();
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
out.output(navigationElement, System.out);
// test attributes
assertEquals("template_mysample", navigationElement.getAttributeValue("template"));
assertEquals("/content", navigationElement.getAttributeValue("dir"));
assertEquals("History Title", navigationElement.getAttributeValue("historyTitle"));
assertEquals("/content/below/index.xml", navigationElement.getAttributeValue("hrefStartingPage"));
assertEquals("Main Title", navigationElement.getAttributeValue("mainTitle"));
// test children
assertEquals(2, navigationElement.getChildren("menu").size());
assertEquals(1, navigationElement.getChildren("insert").size());
}
@Test
public void fromXML() throws Exception {
JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class);
Unmarshaller m = jc.createUnmarshaller();
Object o = m.unmarshal(new File("src/test/resources/navigation/navigation.xml"));
assertTrue(o instanceof MCRNavigation);
MCRNavigation navigation = (MCRNavigation) o;
// test navigation
assertEquals("template1", navigation.getTemplate());
assertEquals("{tenantPath}/content/below/index.xml", navigation.getHrefStartingPage());
assertEquals("/content", navigation.getDir());
assertEquals("main title", navigation.getMainTitle());
assertEquals("history title", navigation.getHistoryTitle());
// test menu
MCRNavigationMenuItem menu = (MCRNavigationMenuItem) navigation.getChildren().get(0);
assertEquals("main", menu.getId());
assertEquals("/content/main", menu.getDir());
assertEquals("Hauptmenü links", menu.getLabel("de"));
assertEquals("Main menu left", menu.getLabel("en"));
// test item
MCRNavigationItem searchItem = (MCRNavigationItem) menu.getChildren().get(0);
assertEquals("{tenantPath}/content/main/search.xml", searchItem.getHref());
assertEquals(MCRNavigationItem.Type.intern, searchItem.getType());
assertEquals(MCRNavigationItem.Target._self, searchItem.getTarget());
assertEquals("normal", searchItem.getStyle());
assertEquals(false, searchItem.isReplaceMenu());
assertEquals(true, searchItem.isConstrainPopUp());
assertEquals("Suche", searchItem.getLabel("de"));
assertEquals("Retrieval", searchItem.getLabel("en"));
assertEquals(2, searchItem.getChildren().size());
// test group
MCRNavigationGroup group = (MCRNavigationGroup) menu.getChildren().get(2);
assertEquals("foo", group.getId());
assertEquals("Foo-Gruppe", group.getLabel("de"));
MCRNavigationItem foo1 = (MCRNavigationItem) group.getChildren().get(0);
assertEquals("{tenantPath}/content/main/foo1.xml", foo1.getHref());
assertEquals("Foo1", foo1.getLabel("de"));
}
@Test
public void toJSON() {
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(this.navigation);
JsonObject navigationObject = jsonElement.getAsJsonObject();
assertEquals("template_mysample", navigationObject.get("template").getAsString());
assertEquals("/content", navigationObject.get("dir").getAsString());
assertEquals("History Title", navigationObject.get("historyTitle").getAsString());
assertEquals("/content/below/index.xml", navigationObject.get("hrefStartingPage").getAsString());
assertEquals("Main Title", navigationObject.get("mainTitle").getAsString());
}
}
| 6,143 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
SampleItemTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/test/java/org/mycore/wcms2/datamodel/SampleItemTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
public class SampleItemTest {
// TODO
// @Test
// public void fromXML() throws Exception {
// JAXBContext jc = JAXBContext.newInstance(new Class[] {Navigation.class, SampleItem.class});
// Unmarshaller m = jc.createUnmarshaller();
// Object o = m.unmarshal(new File("src/test/resources/navigation/navigation2.xml"));
// assertTrue(o instanceof Navigation);
// Navigation navigation = (Navigation)o;
// MenuItem menu = (MenuItem)navigation.getChildren().get(0);
// SampleItem sampleItem = (SampleItem)menu.getChildren().get(0);
// assertEquals("myownitem", sampleItem.name);
// }
//
// @XmlRootElement(name = "sampleItem")
// public static class SampleItem implements NavigationItem {
// @XmlAttribute
// public String name;
// }
}
| 1,656 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ItemTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/test/java/org/mycore/wcms2/datamodel/ItemTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import static org.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMResult;
import org.junit.Before;
import org.junit.Test;
import org.mycore.wcms2.datamodel.MCRNavigationItem.Target;
import org.mycore.wcms2.datamodel.MCRNavigationItem.Type;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
public class ItemTest {
private MCRNavigationItem item;
@Before
public void setup() {
this.item = new MCRNavigationItem();
this.item.setHref("/content/main/search.xml");
this.item.setStyle("bold");
this.item.setTarget(Target._self);
this.item.setType(Type.intern);
this.item.setTemplate("template_mysample");
this.item.setConstrainPopUp(true);
this.item.setReplaceMenu(false);
this.item.setI18n("item.test.key");
this.item.addLabel("de", "Deutschland");
this.item.addLabel("en", "England");
}
@Test
public void toXML() throws Exception {
JAXBContext jc = JAXBContext.newInstance(MCRNavigationItem.class);
Marshaller m = jc.createMarshaller();
JDOMResult JDOMResult = new JDOMResult();
m.marshal(this.item, JDOMResult);
Element itemElement = JDOMResult.getDocument().getRootElement();
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
out.output(itemElement, System.out);
assertEquals("template_mysample", itemElement.getAttributeValue("template"));
assertEquals("bold", itemElement.getAttributeValue("style"));
assertEquals("_self", itemElement.getAttributeValue("target"));
assertEquals("intern", itemElement.getAttributeValue("type"));
assertEquals("true", itemElement.getAttributeValue("constrainPopUp"));
assertEquals("false", itemElement.getAttributeValue("replaceMenu"));
assertEquals("item.test.key", itemElement.getAttributeValue("i18nKey"));
Element label1 = itemElement.getChildren().get(0);
Element label2 = itemElement.getChildren().get(1);
assertEquals("Deutschland", label1.getValue());
assertEquals("England", label2.getValue());
}
@Test
public void toJSON() {
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(this.item);
JsonObject navigationObject = jsonElement.getAsJsonObject();
assertEquals("template_mysample", navigationObject.get("template").getAsString());
assertEquals("bold", navigationObject.get("style").getAsString());
assertEquals("_self", navigationObject.get("target").getAsString());
assertEquals("intern", navigationObject.get("type").getAsString());
assertEquals(true, navigationObject.get("constrainPopUp").getAsBoolean());
assertEquals(false, navigationObject.get("replaceMenu").getAsBoolean());
}
}
| 3,808 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/MCRWCMSUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.util.MCRServletContentHelper;
import org.mycore.common.function.MCRThrowFunction;
import org.mycore.wcms2.datamodel.MCRNavigation;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
public abstract class MCRWCMSUtil {
public static MCRNavigation load(org.w3c.dom.Document doc) throws JAXBException {
return unmarshall(um -> um.unmarshal(doc));
}
public static MCRNavigation load(File navigationFile) throws JAXBException {
return unmarshall(um -> um.unmarshal(navigationFile));
}
private static MCRNavigation unmarshall(MCRThrowFunction<Unmarshaller, Object, JAXBException> unmarshallFunction)
throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class);
if (unmarshallFunction.apply(jc.createUnmarshaller()) instanceof MCRNavigation navigation) {
return navigation;
}
return null;
}
/**
* Save navigation.xml with JAXB.
* If MCR.navigationFile.SaveInOldFormat is true the navigation is stored in the old format.
*/
public static void save(MCRNavigation navigation, OutputStream out) throws JAXBException, IOException,
JDOMException {
JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ByteArrayOutputStream bout = new ByteArrayOutputStream(MCRServletContentHelper.DEFAULT_BUFFER_SIZE);
m.marshal(navigation, bout);
byte[] xml = bout.toByteArray();
if (saveInOldFormat()) {
xml = convertToOldFormat(xml);
}
out.write(xml);
}
/**
* Converts the navigation.xml to the old format.
*/
private static byte[] convertToOldFormat(byte[] xml) throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new ByteArrayInputStream(xml));
Element rootElement = doc.getRootElement();
rootElement.setAttribute("href", rootElement.getName());
List<Element> children = rootElement.getChildren();
for (Element menu : children) {
String id = menu.getAttributeValue("id");
menu.setName(id);
menu.setAttribute("href", id);
menu.removeAttribute("id");
}
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
ByteArrayOutputStream bout = new ByteArrayOutputStream(xml.length);
out.output(doc, bout);
return bout.toByteArray();
}
private static boolean saveInOldFormat() {
return MCRConfiguration2.getOrThrow("MCR.NavigationFile.SaveInOldFormat", Boolean::parseBoolean);
}
}
| 4,032 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWebPagesSynchronizer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/MCRWebPagesSynchronizer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRStartupHandler.AutoExecutable;
import jakarta.servlet.ServletContext;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRWebPagesSynchronizer implements AutoExecutable {
private static Logger LOGGER = LogManager.getLogger(MCRWebPagesSynchronizer.class);
private static final int FAT_PRECISION = 2000;
private static final long DEFAULT_COPY_BUFFER_SIZE = 16 * 1024 * 1024; // 16 KB
private static ServletContext SERVLET_CONTEXT = null;
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getName()
*/
@Override
public String getName() {
return "Webpages synchronizer";
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getPriority()
*/
@Override
public int getPriority() {
return 0;
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#startUp(jakarta.servlet.ServletContext)
*/
@Override
public void startUp(ServletContext servletContext) {
if (servletContext != null) {
SERVLET_CONTEXT = servletContext;
File wcmsDataDir = null;
File webappBasePath = null;
try {
//we are running in a servlet container
webappBasePath = getWebAppBaseDir();
LOGGER.info("WebAppBasePath={}", webappBasePath.getAbsolutePath());
wcmsDataDir = getWCMSDataDir();
if (!wcmsDataDir.isDirectory()) {
LOGGER.info("{} does not exist or is not a directory. Skipping synchronization.",
wcmsDataDir.getAbsolutePath());
return;
}
synchronize(wcmsDataDir, webappBasePath);
} catch (IOException e) {
throw new MCRException("Error while synchronizing " + wcmsDataDir + " to " + webappBasePath, e);
}
}
}
public static File getWCMSDataDir() {
return new File(MCRConfiguration2.getStringOrThrow("MCR.WCMS2.DataDir"));
}
public static Path getWCMSDataDirPath() {
return MCRConfiguration2.getOrThrow("MCR.WCMS2.DataDir", Paths::get);
}
public static File getWebAppBaseDir() throws IOException {
if (SERVLET_CONTEXT == null) {
throw new IOException("ServletContext is not initialized.");
}
String realPath = SERVLET_CONTEXT.getRealPath("/");
if (realPath == null) {
throw new IOException("Could not get webapp base path.");
}
return new File(realPath);
}
/**
* Returns an OuputStream that writes to local webapp and to file inside <code>MCR.WCMS2.DataDir</code>.
*/
public static OutputStream getOutputStream(String path) throws IOException {
String cleanPath = path.startsWith("/") ? path.substring(1) : path;
File wcmsDataDir = getWCMSDataDir();
File webappBaseDir = getWebAppBaseDir();
File webappTarget = new File(webappBaseDir, cleanPath);
if (!webappTarget.toPath().startsWith(webappBaseDir.toPath())) {
throw new IOException(String.format(Locale.ROOT, "Cannot write %s outside the web application: %s",
webappTarget, webappBaseDir));
}
File wcmsDataDirTarget = new File(wcmsDataDir, cleanPath);
createDirectoryIfNeeded(webappTarget);
createDirectoryIfNeeded(wcmsDataDirTarget);
LOGGER.info(String.format(Locale.ROOT, "Writing content to %s and to %s.", webappTarget, wcmsDataDirTarget));
return new TeeOutputStream(new FileOutputStream(wcmsDataDirTarget), new FileOutputStream(webappTarget));
}
private static void createDirectoryIfNeeded(File targetFile) throws IOException {
File targetDirectory = targetFile.getParentFile();
if (!targetDirectory.isDirectory() && !targetDirectory.mkdirs()) {
throw new IOException(String.format(Locale.ROOT, "Could not create directory: %s", targetDirectory));
}
}
/**
* Returns URL of the given resource.
*
* This URL may point to a file inside a JAR file in <code>WEB-INF/lib</code>.
* @param path should start with '/'
* @return null, if no resource with that path could be found
*/
public static URL getURL(String path) throws MalformedURLException {
String cleanPath = path.startsWith("/") ? path : String.format(Locale.ROOT, "/%s", path);
return SERVLET_CONTEXT.getResource(cleanPath);
}
/**
* Returns an InputStream of the given resource.
*
* @param path should start with '/'
* @return null, if no resource with that path could be found
*/
public InputStream getInputStream(String path) {
String cleanPath = path.startsWith("/") ? path : String.format(Locale.ROOT, "/%s", path);
return SERVLET_CONTEXT.getResourceAsStream(cleanPath);
}
private static void synchronize(File wcmsDataDir, File webappBasePath) throws IOException {
synchronize(wcmsDataDir, webappBasePath, DEFAULT_COPY_BUFFER_SIZE);
}
private static void synchronize(File source, File destination, long chuckSize) throws IOException {
long newChuckSize = chuckSize;
if (newChuckSize <= 0) {
LOGGER.error("Chunk size must be positive: using default value.");
newChuckSize = DEFAULT_COPY_BUFFER_SIZE;
}
if (source.isDirectory()) {
if (!destination.exists()) {
if (!destination.mkdirs()) {
throw new IOException("Could not create path " + destination);
}
} else if (!destination.isDirectory()) {
throw new IOException("Source and Destination not of the same type:" + source.getCanonicalPath()
+ " , " + destination.getCanonicalPath());
}
File[] sources = source.listFiles();
//copy each file from source
for (File srcFile : sources) {
File destFile = new File(destination, srcFile.getName());
synchronize(srcFile, destFile, newChuckSize);
}
} else {
if (destination.exists() && destination.isDirectory()) {
delete(destination);
}
if (destination.exists()) {
long sts = source.lastModified() / FAT_PRECISION;
long dts = destination.lastModified() / FAT_PRECISION;
//do not copy same timestamp and same length
if (sts == 0 || sts != dts || source.length() != destination.length()) {
copyFile(source, destination, newChuckSize);
}
} else {
copyFile(source, destination, newChuckSize);
}
}
}
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException {
try (FileInputStream is = new FileInputStream(srcFile);
FileOutputStream os = new FileOutputStream(destFile, false)) {
FileChannel iChannel = is.getChannel();
FileChannel oChannel = os.getChannel();
long doneBytes = 0L;
long todoBytes = srcFile.length();
while (todoBytes != 0L) {
long iterationBytes = Math.min(todoBytes, chunkSize);
long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes);
if (iterationBytes != transferredLength) {
throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only "
+ transferredLength + " bytes copied.");
}
doneBytes += transferredLength;
todoBytes -= transferredLength;
}
}
boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified());
if (!successTimestampOp) {
LOGGER.warn(String.format(Locale.ROOT,
"Could not change timestamp for %s. Index synchronization may be slow.", destFile));
}
}
private static void delete(File file) {
if (file.isDirectory()) {
for (File subFile : file.listFiles()) {
delete(subFile);
}
}
if (file.exists() && !file.delete()) {
LOGGER.warn(String.format(Locale.ROOT, "Could not delete %s.", file));
}
}
}
| 9,879 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSDefaultSectionProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/navigation/MCRWCMSDefaultSectionProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.navigation;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Content;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.Text;
import org.jdom2.output.XMLOutputter;
import org.mycore.common.MCRSessionMgr;
import org.mycore.tools.MyCoReWebPageProvider;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import jakarta.ws.rs.WebApplicationException;
/**
* The default implementation to convert MyCoRe Webpage sections
* from and to json.
*
* @author Matthias Eichner
*/
public class MCRWCMSDefaultSectionProvider implements MCRWCMSSectionProvider {
private static final Logger LOGGER = LogManager.getLogger(MCRWCMSDefaultSectionProvider.class);
private static final List<String> HTML_TAG_LIST = Arrays.asList("a", "abbr", "acronym", "address", "applet", "area",
"article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "big", "blockquote", "body", "br", "button",
"canvas", "caption", "center", "cite", "code", "col", "colgroup", "data", "datalist", "dd", "del", "details",
"dfn", "dialog", "dir", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer",
"form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hr", "html", "i", "iframe",
"img", "input", "ins", "kbd", "label", "legend", "li", "link", "main", "map", "mark", "meta", "meter", "nav",
"noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "pre",
"progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", "source", "span",
"strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea",
"tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr");
public JsonArray toJSON(Element rootElement) {
JsonArray sectionArray = new JsonArray();
for (Element section : rootElement.getChildren(MyCoReWebPageProvider.XML_SECTION)) {
// get infos of element
String title = section.getAttributeValue(MyCoReWebPageProvider.XML_TITLE);
String lang = section.getAttributeValue(MyCoReWebPageProvider.XML_LANG, Namespace.XML_NAMESPACE);
String sectionAsString = null;
try {
sectionAsString = getContentAsString(section);
} catch (IOException ioExc) {
LOGGER.error("while reading section data.", ioExc);
continue;
}
// create json object
JsonObject jsonObject = new JsonObject();
if (title != null && !title.equals("")) {
jsonObject.addProperty(JSON_TITLE, title);
}
if (lang != null && !lang.equals("")) {
jsonObject.addProperty(JSON_LANG, lang);
}
JsonArray unknownHTMLTags = new JsonArray();
listUnknownHTMLTags(section).forEach(unknownHTMLTags::add);
jsonObject.add("unknownHTMLTags", unknownHTMLTags);
jsonObject.addProperty(JSON_DATA, sectionAsString);
// add to array
sectionArray.add(jsonObject);
}
return sectionArray;
}
/**
* Returns a list of unknown HTML tags.
*
* @param element the element to validate
* @return a list of unknown HTML tags.
*/
private List<String> listUnknownHTMLTags(Element element) {
List<String> unknownTagList = new ArrayList<>();
String elementName = element.getName().toLowerCase(Locale.ROOT);
if (!HTML_TAG_LIST.contains(elementName)) {
unknownTagList.add(elementName);
}
for (Element el : element.getChildren()) {
unknownTagList.addAll(listUnknownHTMLTags(el));
}
return unknownTagList;
}
/**
* Returns the content of an element as string. The element itself
* is ignored.
*
* @param element the element to get the content from
* @return the content as string
*/
protected String getContentAsString(Element element) throws IOException {
XMLOutputter out = new XMLOutputter();
StringWriter writer = new StringWriter();
for (Content child : element.getContent()) {
if (child instanceof Element childElement) {
out.output(childElement, writer);
} else if (child instanceof Text text) {
String trimmedText = text.getTextTrim();
if (!Objects.equals(trimmedText, "")) {
Text newText = new Text(trimmedText);
out.output(newText, writer);
}
}
}
return writer.toString();
}
@Override
public Element fromJSON(JsonArray jsonSectionArray) {
// create new document
MyCoReWebPageProvider wp = new MyCoReWebPageProvider();
// parse sections
for (JsonElement sectionElement : jsonSectionArray) {
if (!sectionElement.isJsonObject()) {
LOGGER.warn("Invalid json element in content array! {}", sectionElement);
continue;
}
JsonObject sectionObject = sectionElement.getAsJsonObject();
String title = null;
String lang = null;
if (sectionObject.has(JSON_TITLE)) {
title = sectionObject.get(JSON_TITLE).getAsJsonPrimitive().getAsString();
}
if (sectionObject.has(JSON_LANG)) {
lang = sectionObject.get(JSON_LANG).getAsJsonPrimitive().getAsString();
}
String xmlAsString = sectionObject.get(JSON_DATA).getAsJsonPrimitive().getAsString();
try {
wp.addSection(title, xmlAsString, lang);
} catch (IOException | JDOMException exc) {
throw new WebApplicationException("unable to add section " + title, exc);
}
}
wp.updateMeta(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID(), null);
return wp.getXML().detachRootElement();
}
}
| 7,225 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSJSONProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/navigation/MCRWCMSJSONProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.navigation;
import com.google.gson.JsonElement;
/**
*
* @author Matthias Eichner
*/
public interface MCRWCMSJSONProvider<O, J extends JsonElement> {
J toJSON(O object);
O fromJSON(J json);
}
| 959 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSContentManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/navigation/MCRWCMSContentManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.navigation;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRURLContent;
import org.mycore.tools.MyCoReWebPageProvider;
import org.mycore.wcms2.MCRWebPagesSynchronizer;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
/**
* This class provides methods to get, create and save MyCoRe webpages.
*
* @author Matthias Eichner
*/
public class MCRWCMSContentManager {
private static final Logger LOGGER = LogManager.getLogger(MCRWCMSContentManager.class);
private MCRWCMSSectionProvider sectionProvider;
public enum ErrorType {
notExist, invalidFile, notMyCoReWebPage, invalidDirectory, couldNotSave, couldNotMove
}
public MCRWCMSContentManager() {
this.sectionProvider = MCRConfiguration2.<MCRWCMSSectionProvider>getInstanceOf("MCR.WCMS2.sectionProvider")
.orElseGet(MCRWCMSDefaultSectionProvider::new);
}
/**
* Return a json object with the content of a MyCoRe webpage.
* <p>
* {
* type: "content",
* content: @see {@link MCRWCMSDefaultSectionProvider}
* }
* </p>
* <p>
* If an error occur (e.g. file not exist) the returning json
* looks like:<br>
* {
* type: "error",
* errorType: "invalidFile"
* webpageId: "myfolder/webpage1.xml"
* }
* </p>
*
* @param webpageId id of the webpage
* @return json object
* @see ErrorType
*/
public JsonObject getContent(String webpageId) throws IOException, JDOMException {
boolean isXML = webpageId.endsWith(".xml");
URL resourceURL = null;
try {
resourceURL = MCRWebPagesSynchronizer.getURL(webpageId);
} catch (MalformedURLException e) {
throwError(ErrorType.invalidDirectory, webpageId);
}
// file is not in web application directory
if (!isXML) {
throwError(ErrorType.invalidFile, webpageId);
}
Document doc = null;
if (resourceURL == null) {
MyCoReWebPageProvider wpp = new MyCoReWebPageProvider();
wpp.addSection("neuer Eintrag", new Element("p").setText("TODO"), "de");
doc = wpp.getXML();
} else {
doc = new MCRURLContent(resourceURL).asXML();
}
Element rootElement = doc.getRootElement();
if (!"MyCoReWebPage".equals(rootElement.getName())) {
throwError(ErrorType.notMyCoReWebPage, webpageId);
}
// return content
return getContent(rootElement);
}
public JsonObject getContent(Element e) {
JsonArray sectionArray = this.sectionProvider.toJSON(e);
JsonObject content = new JsonObject();
content.addProperty("type", "content");
content.add("content", sectionArray);
return content;
}
/**
* Saves the content of the given items.
*
* Returns a json object, if everything is ok:
* <p>
* { type: "saveDone" }
* </p>
*
* <p>
* If one or more files could'nt be saved because of an error the returning
* json looks like:<br>
* {
* type: "error",
* errorArray: [
* {type: "error", errorType: "invalidDirectory", webpageId: "abc.xml"},
* {type: "error", errorType: "invalidFile", webpageId: "abc2.xml"}
* ...
* ]
* }
* </p>
*
*/
public void save(JsonArray items) {
XMLOutputter out = new XMLOutputter(Format.getRawFormat().setEncoding("UTF-8"));
for (JsonElement e : items) {
validateContent(e).ifPresent(item -> {
String webpageId = getWebPageId(item).get();
if (!webpageId.endsWith(".xml")) {
throwError(ErrorType.invalidFile, webpageId);
}
JsonArray content = item.get("content").getAsJsonArray();
Element mycoreWebpage = this.sectionProvider.fromJSON(content);
// save
try (OutputStream fout = MCRWebPagesSynchronizer.getOutputStream(webpageId)) {
out.output(new Document(mycoreWebpage), fout);
} catch (IOException | RuntimeException exc) {
LOGGER.error("Error while saving {}", webpageId, exc);
throwError(ErrorType.couldNotSave, webpageId);
}
});
}
}
private Optional<String> getWebPageId(JsonObject item) {
JsonElement webpageIdElement = item.has("href") ? item.get("href")
: (item.has("hrefStartingPage") ? item
.get("hrefStartingPage") : null);
if (webpageIdElement == null || !webpageIdElement.isJsonPrimitive()) {
return Optional.empty();
}
return Optional.of(webpageIdElement)
.map(JsonElement::getAsString);
}
private Optional<JsonObject> validateContent(JsonElement e) {
if (!e.isJsonObject()) {
LOGGER.warn("Invalid json element in items {}", e);
return Optional.empty();
}
JsonObject item = e.getAsJsonObject();
if (!item.has("dirty") || !item.get("dirty").getAsBoolean()) {
return Optional.empty();
}
//TODO wenn man nur den href ändert und nicht den content muss die datei
// trotzdem umgeschrieben werden -> check auf file exists
if (!getWebPageId(item).isPresent() || !item.has("content") || !item.get("content").isJsonArray()) {
return Optional.empty();
}
return Optional.of(item);
}
public void move(String from, String to) {
try {
// get from
URL fromURL = MCRWebPagesSynchronizer.getURL(from);
Document document;
if (fromURL == null) {
// if the from resource couldn't be found we assume its not created yet.
MyCoReWebPageProvider wpp = new MyCoReWebPageProvider();
wpp.addSection("neuer Eintrag", new Element("p").setText("TODO"), "de");
document = wpp.getXML();
} else {
SAXBuilder builder = new SAXBuilder();
document = builder.build(fromURL);
}
// save
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setEncoding("UTF-8"));
try (OutputStream fout = MCRWebPagesSynchronizer.getOutputStream(to)) {
out.output(document, fout);
}
// delete old
if (fromURL != null) {
Files.delete(Paths.get(fromURL.toURI()));
}
} catch (Exception exc) {
LOGGER.error("Error moving {} to {}", from, to, exc);
throwError(ErrorType.couldNotMove, to);
}
}
/**
* Throws a new webapplication exception with given error type.
* <code>{ type: "error", errorType: "typeOfError", webpageId: "abc.xml" }</code>
*
* @param errorType type of the error
* @param webpageId webpageId where the error occur
*/
private void throwError(ErrorType errorType, String webpageId) {
JsonObject error = new JsonObject();
error.addProperty("type", errorType.name());
error.addProperty("webpageId", webpageId);
Response response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(error.toString())
.type(MediaType.APPLICATION_JSON).build();
throw new WebApplicationException(response);
}
}
| 8,953 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSSectionProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/navigation/MCRWCMSSectionProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.navigation;
import org.jdom2.Element;
import com.google.gson.JsonArray;
/**
*
* @author Matthias Eichner
*/
public interface MCRWCMSSectionProvider extends MCRWCMSJSONProvider<Element, JsonArray> {
String JSON_TITLE = "title";
String JSON_LANG = "lang";
String JSON_DATA = "data";
@Override
Element fromJSON(JsonArray jsonSection);
/**
* Converts a MyCoRe Webpage to a json array. The array contains
* all the section elements of the webpage including their content.
* <p>
* [<br>
* {title: "title of section", lang: "de", data: "<xml>content of section</xml>"},<br>
* {title: "title of section 2", lang: "en", data: "<xml>content of section 2</xml>"}<br>
* ]
* </p>
*/
@Override
JsonArray toJSON(Element object);
}
| 1,589 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSNavigationUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/navigation/MCRWCMSNavigationUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.navigation;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilder;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.xml.MCRDOMUtils;
import org.mycore.frontend.MCRLayoutUtilities;
import org.mycore.wcms2.MCRWCMSUtil;
import org.mycore.wcms2.MCRWebPagesSynchronizer;
import org.mycore.wcms2.datamodel.MCRNavigation;
import org.mycore.wcms2.datamodel.MCRNavigationBaseItem;
import org.mycore.wcms2.datamodel.MCRNavigationItem;
import org.mycore.wcms2.datamodel.MCRNavigationItemContainer;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.google.gson.JsonObject;
import jakarta.xml.bind.JAXBException;
public class MCRWCMSNavigationUtils {
private static MCRWCMSNavigationProvider NAVIGATION_PROVIDER = MCRConfiguration2
.<MCRWCMSNavigationProvider>getInstanceOf("MCR.WCMS2.navigationProvider")
.orElseGet(MCRWCMSDefaultNavigationProvider::new);
/**
* @see MCRWCMSNavigationProvider#toJSON(MCRNavigation)
*/
public static synchronized JsonObject toJSON(MCRNavigation navigation) {
return NAVIGATION_PROVIDER.toJSON(navigation);
}
public static synchronized MCRNavigation fromJSON(JsonObject jsonNavigation) {
return NAVIGATION_PROVIDER.fromJSON(jsonNavigation);
}
/**
* Saves the given navigation
*/
public static void save(MCRNavigation navigation) throws IOException, JAXBException, JDOMException {
OutputStream out = MCRWebPagesSynchronizer.getOutputStream(MCRLayoutUtilities.NAV_RESOURCE);
MCRWCMSUtil.save(navigation, out);
out.flush();
out.close();
}
/**
* Returns the navigation as json.
*/
public static synchronized JsonObject getNavigationAsJSON() throws IOException, SAXException, JAXBException {
return NAVIGATION_PROVIDER.toJSON(getNavigation());
}
/**
* Returns the navigation as jdom document.
*/
public static synchronized Document getNavigationAsXML() {
return MCRLayoutUtilities.getNavi();
}
/**
* Returns the navigation as pojo.
*/
public static MCRNavigation getNavigation() throws IOException, SAXException, JAXBException {
DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
try {
org.w3c.dom.Document doc = documentBuilder.parse(MCRLayoutUtilities.getNavigationURL().toString());
if (doc.getElementsByTagName("menu").getLength() == 0) {
NodeList nodeList = doc.getFirstChild().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
((org.w3c.dom.Element) nodeList.item(i)).setAttribute("id", nodeList.item(i).getNodeName());
doc.renameNode(nodeList.item(i), null, "menu");
}
}
} else {
MCRConfiguration2.set("MCR.NavigationFile.SaveInOldFormat", String.valueOf(false));
}
return MCRWCMSUtil.load(doc);
} finally {
MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
}
}
/**
* Runs recursive through the item tree and changes each href and hrefStartingPage attribute to the new href.
*
* @param item
* navigation item to change (and all its children)
* @param from
* which href to change
* @param to
* new value of href
* @return if something in the tree was changed
*/
public static boolean updateHref(MCRNavigationBaseItem item, String from, String to) {
boolean dirty = false;
if (item instanceof MCRNavigation navigation) {
if (navigation.getHrefStartingPage() != null && navigation.getHrefStartingPage().equals(from)) {
navigation.setHrefStartingPage(to);
dirty = true;
}
} else if (item instanceof MCRNavigationItem navItem && navItem.getHref().equals(from)) {
navItem.setHref(to);
dirty = true;
}
if (item instanceof MCRNavigationItemContainer container) {
for (MCRNavigationBaseItem child : container.getChildren()) {
if (updateHref(child, from, to)) {
dirty = true;
}
}
}
return dirty;
}
}
| 5,325 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSDefaultNavigationProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/navigation/MCRWCMSDefaultNavigationProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.navigation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.frontend.MCRLayoutUtilities;
import org.mycore.wcms2.datamodel.MCRNavigation;
import org.mycore.wcms2.datamodel.MCRNavigationBaseItem;
import org.mycore.wcms2.datamodel.MCRNavigationGroup;
import org.mycore.wcms2.datamodel.MCRNavigationInsertItem;
import org.mycore.wcms2.datamodel.MCRNavigationItem;
import org.mycore.wcms2.datamodel.MCRNavigationItemContainer;
import org.mycore.wcms2.datamodel.MCRNavigationMenuItem;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* Default implementation of <code>NavigationProvider</code>.
*
* @author Matthias Eichner
*/
public class MCRWCMSDefaultNavigationProvider implements MCRWCMSNavigationProvider {
private static final Logger LOGGER = LogManager.getLogger(MCRWCMSDefaultSectionProvider.class);
private static Gson gson;
static {
gson = new Gson();
}
@Override
public JsonObject toJSON(MCRNavigation navigation) {
JsonObject returnObject = new JsonObject();
JsonArray hierarchy = new JsonArray();
JsonArray items = new JsonArray();
returnObject.add(JSON_HIERARCHY, hierarchy);
returnObject.add(JSON_ITEMS, items);
create(navigation, hierarchy, items);
return returnObject;
}
private void create(MCRNavigationBaseItem item, JsonArray hierarchy, JsonArray items) throws MCRException {
JsonObject hierarchyObject = add(item, hierarchy, items);
if (item instanceof MCRNavigationItemContainer navigationItemContainer) {
JsonArray childHierarchyArray = new JsonArray();
for (MCRNavigationBaseItem childItem : navigationItemContainer.getChildren()) {
create(childItem, childHierarchyArray, items);
}
if (childHierarchyArray.size() > 0) {
hierarchyObject.add(JSON_CHILDREN, childHierarchyArray);
}
}
}
private JsonObject add(MCRNavigationBaseItem item, JsonArray hierarchy, JsonArray items) {
int id = items.size();
JsonObject jsonItem = gson.toJsonTree(item).getAsJsonObject();
jsonItem.addProperty(JSON_WCMS_ID, id);
jsonItem.remove(JSON_CHILDREN);
WCMSType type = null;
String href = null;
if (item instanceof MCRNavigation navigation) {
type = WCMSType.root;
href = navigation.getHrefStartingPage();
} else if (item instanceof MCRNavigationMenuItem menuItem) {
type = WCMSType.menu;
href = menuItem.getDir();
} else if (item instanceof MCRNavigationItem navigationItem) {
type = WCMSType.item;
href = navigationItem.getHref();
} else if (item instanceof MCRNavigationInsertItem) {
type = WCMSType.insert;
} else if (item instanceof MCRNavigationGroup) {
type = WCMSType.group;
} else {
LOGGER.warn("Unable to set type for item {}", id);
}
jsonItem.addProperty(JSON_WCMS_TYPE, type.name());
if (href != null) {
jsonItem.add("access", getAccess(href));
}
items.add(jsonItem);
// create hierarchy for root
JsonObject hierarchyObject = new JsonObject();
hierarchyObject.addProperty(JSON_WCMS_ID, id);
hierarchy.add(hierarchyObject);
return hierarchyObject;
}
@Override
public MCRNavigation fromJSON(JsonObject navigationJSON) {
JsonArray items = navigationJSON.get(JSON_ITEMS).getAsJsonArray();
JsonArray hierarchy = navigationJSON.get(JSON_HIERARCHY).getAsJsonArray();
if (hierarchy.size() > 0) {
JsonObject root = hierarchy.get(0).getAsJsonObject();
MCRNavigationBaseItem item = createItem(root, items);
if (item instanceof MCRNavigation navigation) {
return navigation;
}
}
return null;
}
private MCRNavigationBaseItem createItem(JsonObject hierarchyObject, JsonArray items) {
if (!hierarchyObject.has(JSON_WCMS_ID)) {
LOGGER.warn("While saving navigation.xml. Invalid object in hierarchy.");
return null;
}
MCRNavigationBaseItem item = getNavigationItem(hierarchyObject.get(JSON_WCMS_ID).getAsString(), items);
if (item == null) {
LOGGER.warn("While saving navigation.xml. Item with id {} is null!", hierarchyObject.get(JSON_WCMS_ID));
return null;
}
JsonElement children = hierarchyObject.get(JSON_CHILDREN);
if (children != null && children.isJsonArray() && item instanceof MCRNavigationItemContainer itemAsContainer) {
for (JsonElement child : children.getAsJsonArray()) {
if (child.isJsonObject()) {
MCRNavigationBaseItem childItem = createItem(child.getAsJsonObject(), items);
if (childItem != null) {
itemAsContainer.getChildren().add(childItem);
}
}
}
}
return item;
}
/**
* Internal method to get an <code>NavigationItem</code> from
* the json array.
*
* @param wcmsId id of the item
* @param items list of items
* @return instance of <code>NavigationItem</code> or null
*/
private MCRNavigationBaseItem getNavigationItem(String wcmsId, JsonArray items) {
for (JsonElement e : items) {
if (e.isJsonObject()) {
JsonObject item = e.getAsJsonObject();
if (item.has(JSON_WCMS_ID) && item.has(JSON_WCMS_TYPE)
&& wcmsId.equals(item.get(JSON_WCMS_ID).getAsString())) {
WCMSType wcmsType = WCMSType.valueOf(item.get(JSON_WCMS_TYPE).getAsString());
if (wcmsType.equals(WCMSType.root)) {
return gson.fromJson(item, MCRNavigation.class);
} else if (wcmsType.equals(WCMSType.menu)) {
return gson.fromJson(item, MCRNavigationMenuItem.class);
} else if (wcmsType.equals(WCMSType.item)) {
return gson.fromJson(item, MCRNavigationItem.class);
} else if (wcmsType.equals(WCMSType.insert)) {
return gson.fromJson(item, MCRNavigationInsertItem.class);
} else if (wcmsType.equals(WCMSType.group)) {
return gson.fromJson(item, MCRNavigationGroup.class);
}
}
}
}
return null;
}
private JsonObject getAccess(String href) {
JsonObject accessObject = new JsonObject();
if (MCRLayoutUtilities.hasRule("read", href)) {
JsonObject readObject = new JsonObject();
accessObject.add("read", readObject);
readObject.addProperty("ruleID", MCRLayoutUtilities.getRuleID("read", href));
readObject.addProperty("ruleDes", MCRLayoutUtilities.getRuleDescr("read", href));
}
if (MCRLayoutUtilities.hasRule("write", href)) {
JsonObject writeObject = new JsonObject();
accessObject.add("write", writeObject);
writeObject.addProperty("ruleID", MCRLayoutUtilities.getRuleID("write", href));
writeObject.addProperty("ruleDes", MCRLayoutUtilities.getRuleDescr("write", href));
}
return accessObject;
}
}
| 8,403 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSNavigationProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/navigation/MCRWCMSNavigationProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.navigation;
import org.mycore.wcms2.datamodel.MCRNavigation;
import com.google.gson.JsonObject;
/**
* Connection between the Navigation Datamodel and the WCMS.
*
* @author Matthias Eichner
*/
public interface MCRWCMSNavigationProvider extends MCRWCMSJSONProvider<MCRNavigation, JsonObject> {
String JSON_HIERARCHY = "hierarchy";
String JSON_ITEMS = "items";
String JSON_CHILDREN = "children";
String JSON_WCMS_ID = "wcmsId";
String JSON_WCMS_TYPE = "wcmsType";
enum WCMSType {
root, item, insert, menu, group
}
/**
* <p>
* Converts a <code>Navigation</code> object to a json one. The structure of the json is:
* </p>
* <pre>
* {
* hierarchy: [
* {"wcmsId":0,"children":[
* {"wcmsId":1,"children":[
* {"wcmsId":2}
* ]}
* ]}
* }
* items: [
* {"wcmsId" : "0", "wcmsType" : "root", "mainTitle" : "My Main Title", "dir" : "/content" ...},
* {"wcmsId" : "1", "wcmsType" : "menu", "id" : "main", "labelMap":{"de":"Hauptmenü","en":"Main menu"} ... }
* {"wcmsId" : "2", "wcmsType" : "item", "type" : "intern", "style" : "bold" ...}
* ...
* ]
* }
* </pre>
* @return the generated json
*/
@Override
JsonObject toJSON(MCRNavigation navigation);
/**
* Converts an WCMS JSON Object to an <code>Navigation</code> object.
*
* TODO: json data structure
*/
@Override
MCRNavigation fromJSON(JsonObject jsonNavigation);
}
| 2,314 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigationBaseItem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationBaseItem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
/**
* The super class of all navigation related items.
*
* @author Matthias Eichner
*/
public interface MCRNavigationBaseItem {
}
| 899 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigationMenuItem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationMenuItem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlElementRefs;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "menu")
@XmlAccessorType(XmlAccessType.NONE)
public class MCRNavigationMenuItem extends MCRNavigationI18nItem
implements MCRNavigationItemContainer {
@XmlAttribute(required = true)
private String id;
@XmlAttribute
private String dir;
// children
@XmlElementRefs({
@XmlElementRef(type = MCRNavigationItem.class),
@XmlElementRef(type = MCRNavigationGroup.class),
@XmlElementRef(type = MCRNavigationInsertItem.class)
})
// @XmlAnyElement(lax = true)
private List<MCRNavigationBaseItem> children;
public MCRNavigationMenuItem() {
this.children = new ArrayList<>();
}
public String getId() {
return id;
}
public String getDir() {
return dir;
}
public void setId(String id) {
this.id = id;
}
public void setDir(String dir) {
this.dir = dir;
}
public void addItem(MCRNavigationItem item) {
this.children.add(item);
}
public void addInsertItem(MCRNavigationInsertItem insertItem) {
this.children.add(insertItem);
}
public List<MCRNavigationBaseItem> getChildren() {
return this.children;
}
}
| 2,334 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigationInsertItem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationInsertItem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "insert")
@XmlAccessorType(XmlAccessType.NONE)
public class MCRNavigationInsertItem implements MCRNavigationBaseItem {
@XmlAttribute
private String uri;
public String getURI() {
return uri;
}
public void setURI(String uri) {
this.uri = uri;
}
}
| 1,279 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigationItemContainer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationItemContainer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import java.util.List;
public interface MCRNavigationItemContainer extends MCRNavigationBaseItem {
List<MCRNavigationBaseItem> getChildren();
}
| 915 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigationItem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationItem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlElementRefs;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
@XmlRootElement(name = "item")
@XmlAccessorType(XmlAccessType.NONE)
public class MCRNavigationItem extends MCRNavigationI18nItem implements MCRNavigationItemContainer {
@XmlType(name = "ItemType")
public enum Type {
intern, extern
}
public enum Target {
_self, _blank
}
// general
@XmlAttribute(required = true)
private String href;
@XmlAttribute
private Type type;
// navigation
@XmlAttribute
private Target target;
@XmlAttribute
private boolean replaceMenu;
@XmlAttribute
private boolean constrainPopUp;
@XmlAttribute
protected String template;
@XmlAttribute
protected String style;
// children
@XmlElementRefs({ @XmlElementRef(type = MCRNavigationItem.class),
@XmlElementRef(type = MCRNavigationInsertItem.class) })
private List<MCRNavigationBaseItem> children;
public MCRNavigationItem() {
super();
this.children = new ArrayList<>();
}
public String getHref() {
return href;
}
public boolean isReplaceMenu() {
return replaceMenu;
}
public boolean isConstrainPopUp() {
return constrainPopUp;
}
public Type getType() {
return type;
}
public Target getTarget() {
return target;
}
public String getTemplate() {
return template;
}
public void setHref(String href) {
this.href = href;
}
public void setType(Type type) {
this.type = type;
}
public void setTarget(Target target) {
this.target = target;
}
public void setReplaceMenu(boolean replaceMenu) {
this.replaceMenu = replaceMenu;
}
public void setConstrainPopUp(boolean constrainPopUp) {
this.constrainPopUp = constrainPopUp;
}
public void setTemplate(String template) {
this.template = template;
}
public void setStyle(String style) {
this.style = style;
}
public String getStyle() {
return style;
}
public void addItem(MCRNavigationItem item) {
this.children.add(item);
}
public void addInsertItem(MCRNavigationInsertItem insertItem) {
this.children.add(insertItem);
}
@Override
public List<MCRNavigationBaseItem> getChildren() {
return this.children;
}
}
| 3,523 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigationGroup.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationGroup.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlElementRefs;
import jakarta.xml.bind.annotation.XmlID;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "group")
@XmlAccessorType(XmlAccessType.NONE)
public class MCRNavigationGroup extends MCRNavigationI18nItem implements MCRNavigationItemContainer {
// general
@XmlAttribute(required = true)
@XmlID
private String id;
// children
@XmlElementRefs({ @XmlElementRef(type = MCRNavigationItem.class),
@XmlElementRef(type = MCRNavigationInsertItem.class) })
private List<MCRNavigationBaseItem> children;
public MCRNavigationGroup() {
super();
this.children = new ArrayList<>();
}
public void addItem(MCRNavigationItem item) {
this.children.add(item);
}
public void addInsertItem(MCRNavigationInsertItem insertItem) {
this.children.add(insertItem);
}
@Override
public List<MCRNavigationBaseItem> getChildren() {
return this.children;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| 2,150 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigationI18nItem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigationI18nItem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import java.util.HashMap;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.NONE)
public abstract class MCRNavigationI18nItem implements MCRNavigationBaseItem {
@XmlAttribute(name = "i18nKey")
private String i18nKey;
private HashMap<String, String> labelMap;
public MCRNavigationI18nItem() {
this.labelMap = new HashMap<>();
}
public String getI18n() {
return i18nKey;
}
public void setI18n(String i18nKey) {
this.i18nKey = i18nKey;
}
public void addLabel(String language, String text) {
this.labelMap.put(language, text);
}
public void removeLabel(String language) {
this.labelMap.remove(language);
}
public boolean containsLabel(String language) {
return this.labelMap.containsKey(language);
}
public String getLabel(String language) {
return this.labelMap.get(language);
}
@XmlElement(name = "label")
public Label[] getLabelArray() {
return this.labelMap.entrySet()
.stream()
.map(entry -> new Label(entry.getKey(), entry.getValue()))
.toArray(Label[]::new);
}
public void setLabelArray(Label[] labelArray) {
for (Label label : labelArray) {
this.labelMap.put(label.getLanguage(), label.getText());
}
}
public static class Label {
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
private String language;
@XmlValue
private String text;
public Label() {
this(null, null);
}
public Label(String language, String text) {
this.language = language;
this.text = text;
}
public String getLanguage() {
return language;
}
public String getText() {
return text;
}
}
}
| 2,880 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNavigation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/datamodel/MCRNavigation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.datamodel;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlElementRefs;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* Represents the root entry of a navigation.xml.
*
* @author Matthias Eichner
*/
@XmlRootElement(name = "navigation")
@XmlAccessorType(XmlAccessType.NONE)
public class MCRNavigation implements MCRNavigationItemContainer {
// general
@XmlAttribute
private String hrefStartingPage;
@XmlAttribute
private String dir;
@XmlAttribute
private String mainTitle;
@XmlAttribute
protected String template;
// multitenancy
@XmlAttribute
private String historyTitle;
// children
@XmlElementRefs({ @XmlElementRef(type = MCRNavigationMenuItem.class),
@XmlElementRef(type = MCRNavigationInsertItem.class) })
private List<MCRNavigationBaseItem> children;
public MCRNavigation() {
this.children = new ArrayList<>();
}
public String getHrefStartingPage() {
return hrefStartingPage;
}
public String getDir() {
return dir;
}
public String getMainTitle() {
return mainTitle;
}
public String getHistoryTitle() {
return historyTitle;
}
public String getTemplate() {
return template;
}
public void setHrefStartingPage(String hrefStartingPage) {
this.hrefStartingPage = hrefStartingPage;
}
public void setDir(String dir) {
this.dir = dir;
}
public void setMainTitle(String mainTitle) {
this.mainTitle = mainTitle;
}
public void setHistoryTitle(String historyTitle) {
this.historyTitle = historyTitle;
}
public void setTemplate(String template) {
this.template = template;
}
public void addMenu(MCRNavigationMenuItem menu) {
this.children.add(menu);
}
public void addInsertItem(MCRNavigationInsertItem insertItem) {
this.children.add(insertItem);
}
public List<MCRNavigationBaseItem> getChildren() {
return this.children;
}
}
| 3,040 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSFileBrowserResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSFileBrowserResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.resources;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Objects;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.mycore.common.MCRUtils;
import org.mycore.frontend.MCRLayoutUtilities;
import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess;
import org.mycore.wcms2.MCRWebPagesSynchronizer;
import org.mycore.wcms2.access.MCRWCMSPermission;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
@Path("wcms2/filebrowser")
@MCRRestrictedAccess(MCRWCMSPermission.class)
public class MCRWCMSFileBrowserResource {
private ArrayList<String> folderList = new ArrayList<>();
private String wcmsDataPath = MCRWebPagesSynchronizer.getWCMSDataDir().getPath();
private static final Logger LOGGER = LogManager.getLogger(MCRWCMSFileBrowserResource.class);
@Context
HttpServletRequest request;
@Context
HttpServletResponse response;
@Context
ServletContext context;
@GET
public InputStream getFileBrowser() {
return getClass().getResourceAsStream("/META-INF/resources/modules/wcms2/filebrowser.html");
}
@GET
@Path("gui/{filename:.*}")
public Response getResources(@PathParam("filename") String filename) {
if (filename.startsWith("/") || filename.contains("../")) {
return Response.status(Status.BAD_REQUEST).build();
}
if (filename.endsWith(".js")) {
return Response.ok(getClass()
.getResourceAsStream("/META-INF/resources/modules/wcms2/" + filename))
.header("Content-Type", "application/javascript")
.build();
}
if (filename.endsWith(".css")) {
return Response.ok(getClass()
.getResourceAsStream("/META-INF/resources/modules/wcms2/" + filename))
.header("Content-Type", "text/css")
.build();
}
return Response.ok(getClass()
.getResourceAsStream("/META-INF/resources/modules/wcms2/" + filename))
.build();
}
@GET
@Path("/folder")
public String getFolders() throws IOException, ParserConfigurationException, SAXException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
File file = new File(MCRLayoutUtilities.getNavigationURL().getPath());
Document doc = docBuilder.parse(file);
getallowedPaths(doc.getDocumentElement());
File dir = MCRWebPagesSynchronizer.getWCMSDataDir();
JsonObject jsonObj = new JsonObject();
jsonObj.add("folders", getFolder(dir, false));
return jsonObj.toString();
}
@POST
@Path("/folder")
public Response addFolder(@QueryParam("path") String path) throws IOException {
File wcmsDir = resolveDirWCMS(path);
File wepAppdir = resolveDirWebApp(path);
if (wcmsDir.mkdir() && wepAppdir.mkdir()) {
return Response.ok().build();
}
return Response.status(Status.CONFLICT).build();
}
private File resolveDirWebApp(String path) throws IOException {
return MCRUtils.safeResolve(MCRWebPagesSynchronizer.getWebAppBaseDir().toPath(),
removeLeadingSlash(path)).toFile();
}
@DELETE
@Path("/folder")
public Response deleteFolder(@QueryParam("path") String path) throws IOException {
File wcmsDir = resolveDirWCMS(path);
File wepAppdir = resolveDirWebApp(path);
if (wepAppdir.isDirectory()) {
if (wepAppdir.list().length < 1) {
if (FileUtils.deleteQuietly(wepAppdir) && FileUtils.deleteQuietly(wcmsDir)) {
return Response.ok().build();
}
} else {
return Response.status(Status.FORBIDDEN).build();
}
}
return Response.status(Status.CONFLICT).build();
}
private File resolveDirWCMS(String path) {
return MCRUtils.safeResolve(MCRWebPagesSynchronizer.getWCMSDataDirPath(), removeLeadingSlash(path)).toFile();
}
@GET
@Path("/files")
public String getFiles(@QueryParam("path") String path, @QueryParam("type") String type) throws IOException {
File dir = MCRUtils.safeResolve(MCRWebPagesSynchronizer.getWCMSDataDirPath(), removeLeadingSlash(path))
.toFile();
JsonObject jsonObj = new JsonObject();
JsonArray jsonArray = new JsonArray();
File[] fileArray = dir.listFiles();
if (fileArray != null) {
for (File file : fileArray) {
String mimetype = Files.probeContentType(file.toPath());
if (mimetype != null && (type.equals("images") ? mimetype.split("/")[0].equals("image")
: !mimetype.split("/")[1].contains("xml"))) {
JsonObject fileJsonObj = new JsonObject();
fileJsonObj.addProperty("name", file.getName());
fileJsonObj.addProperty("path", context.getContextPath() + path + "/" + file.getName());
if (file.isDirectory()) {
fileJsonObj.addProperty("type", "folder");
} else {
fileJsonObj.addProperty("type", mimetype.split("/")[0]);
}
jsonArray.add(fileJsonObj);
}
}
jsonObj.add("files", jsonArray);
return jsonObj.toString();
}
return "";
}
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response getUpload(@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition header, @FormDataParam("path") String path) {
try {
saveFile(inputStream, path + "/" + header.getFileName());
} catch (IOException e) {
LOGGER.error("Error while saving {}", path, e);
return Response.status(Status.CONFLICT).build();
}
return Response.ok().build();
}
@DELETE
public Response deleteFile(@QueryParam("path") String path) throws IOException {
File wcmsDir = MCRUtils.safeResolve(MCRWebPagesSynchronizer.getWCMSDataDirPath(), removeLeadingSlash(path))
.toFile();
File wepAppdir = MCRUtils.safeResolve(MCRWebPagesSynchronizer.getWebAppBaseDir().toPath(),
removeLeadingSlash(path)).toFile();
if (delete(wcmsDir) && delete(wepAppdir)) {
return Response.ok().build();
}
return Response.status(Status.CONFLICT).build();
}
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String getUpload(@FormDataParam("upload") InputStream inputStream,
@FormDataParam("upload") FormDataContentDisposition header, @QueryParam("CKEditorFuncNum") int funcNum,
@QueryParam("href") String href, @QueryParam("type") String type, @QueryParam("basehref") String basehref) {
String path = "";
try {
path = saveFile(inputStream, href + "/" + header.getFileName());
} catch (IOException e) {
LOGGER.error("Error while saving {}", href + "/" + header.getFileName(), e);
return "";
}
if (Objects.equals(type, "images")) {
return "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(" + funcNum + ",'"
+ path.substring(path.lastIndexOf("/") + 1) + "', '');</script>";
}
return "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(" + funcNum + ",'" + basehref
+ path.substring(path.lastIndexOf("/") + 1) + "', '');</script>";
}
protected String saveFile(InputStream inputStream, String path) throws IOException {
String newPath = testIfFileExists(path);
OutputStream outputStream = MCRWebPagesSynchronizer.getOutputStream(newPath);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
outputStream.close();
return newPath;
}
protected String testIfFileExists(String path) {
String newPath = removeLeadingSlash(path);
java.nio.file.Path basePath = MCRWebPagesSynchronizer.getWCMSDataDirPath();
File file = MCRUtils.safeResolve(basePath, newPath)
.toFile();
int i = 1;
while (file.exists()) {
String type = newPath.substring(newPath.lastIndexOf("."));
String name = newPath.substring(0, newPath.lastIndexOf("."));
if (i > 1) {
name = name.substring(0, name.lastIndexOf("("));
}
newPath = name + "(" + i++ + ")" + type;
file = MCRUtils.safeResolve(basePath, newPath).toFile();
}
return newPath;
}
private String removeLeadingSlash(String newPath) {
return newPath.startsWith("/") ? newPath.substring(1) : newPath;
}
protected void getallowedPaths(Element element) {
String pathString = element.getAttribute("dir");
if (!Objects.equals(pathString, "")) {
folderList.add(wcmsDataPath + pathString);
}
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
getallowedPaths((Element) node);
}
}
}
protected JsonObject getFolder(File node, boolean folderallowed) {
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("name", node.getName());
jsonObj.addProperty("path", node.getAbsolutePath());
jsonObj.addProperty("allowed", folderallowed);
if (node.isDirectory()) {
jsonObj.addProperty("type", "folder");
JsonArray jsonArray = new JsonArray();
File[] childNodes = node.listFiles();
for (File child : childNodes) {
if (child.isDirectory()) {
if (folderallowed || folderList.contains(child.getPath())) {
jsonArray.add(getFolder(child, true));
} else {
jsonArray.add(getFolder(child, false));
}
}
}
if (jsonArray.size() > 0) {
jsonObj.add("children", jsonArray);
}
return jsonObj;
}
return jsonObj;
}
protected static boolean delete(File file) {
if (file.isDirectory()) {
for (File subFile : file.listFiles()) {
delete(subFile);
}
}
return !file.exists() || file.delete();
}
}
| 12,732 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSNavigationResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSNavigationResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.resources;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess;
import org.mycore.wcms2.access.MCRWCMSPermission;
import org.mycore.wcms2.datamodel.MCRNavigation;
import org.mycore.wcms2.navigation.MCRWCMSContentManager;
import org.mycore.wcms2.navigation.MCRWCMSNavigationProvider;
import org.mycore.wcms2.navigation.MCRWCMSNavigationUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonStreamParser;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
@Path("wcms/navigation")
@MCRRestrictedAccess(MCRWCMSPermission.class)
public class MCRWCMSNavigationResource {
private static final XPathExpression<Element> TEMPLATE_PATH;
static {
TEMPLATE_PATH = XPathFactory.instance().compile("*[@template]", Filters.element());
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public String get() {
try {
JsonObject json = MCRWCMSNavigationUtils.getNavigationAsJSON();
return json.toString();
} catch (Exception exc) {
throw new WebApplicationException(exc, Status.INTERNAL_SERVER_ERROR);
}
}
@GET
@Path("content")
@Produces(MediaType.APPLICATION_JSON)
public String getContent(@QueryParam("webpagePath") String webpagePath) throws Exception {
JsonObject json = getContentManager().getContent(webpagePath);
return json.toString();
}
@POST
@Path("save")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response save(String json) throws Exception {
JsonStreamParser jsonStreamParser = new JsonStreamParser(json);
if (!jsonStreamParser.hasNext()) {
return Response.status(Status.BAD_REQUEST).build();
}
JsonObject saveObject = jsonStreamParser.next().getAsJsonObject();
// get navigation
MCRNavigation newNavigation = MCRWCMSNavigationUtils.fromJSON(saveObject);
// save navigation
MCRWCMSNavigationUtils.save(newNavigation);
// save content
JsonArray items = saveObject.get(MCRWCMSNavigationProvider.JSON_ITEMS).getAsJsonArray();
getContentManager().save(items);
return Response.ok().build();
}
/**
* Returns a json object containing all available templates.
*/
@GET
@Path("templates")
@Produces(MediaType.APPLICATION_JSON)
public String getTemplates(@Context ServletContext servletContext) {
// templates of navigation.xml
Document xml = MCRWCMSNavigationUtils.getNavigationAsXML();
List<Element> elementList = TEMPLATE_PATH.evaluate(xml);
HashSet<String> entries = elementList.stream()
.map(e -> e.getAttributeValue("template"))
.collect(Collectors.toCollection(HashSet::new));
// templates by folder
String templatePath = MCRConfiguration2.getString("MCR.WCMS2.templatePath").orElse("/templates/master/");
Set<String> resourcePaths = servletContext.getResourcePaths(templatePath);
if (resourcePaths != null) {
for (String resourcepath : resourcePaths) {
String newResourcepath = resourcepath.substring(templatePath.length(), resourcepath.length() - 1);
entries.add(newResourcepath);
}
}
// create returning json
JsonArray returnArr = new JsonArray();
for (String entry : entries) {
returnArr.add(new JsonPrimitive(entry));
}
return returnArr.toString();
}
@POST
@Path("move")
public void move(@QueryParam("from") String from, @QueryParam("to") String to) throws Exception {
if (from == null || to == null) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
.entity("from or to parameter not set").build());
}
// move it
getContentManager().move(from, to);
// update navigation
MCRNavigation navigation = MCRWCMSNavigationUtils.getNavigation();
boolean hrefUpdated = MCRWCMSNavigationUtils.updateHref(navigation, from, to);
if (hrefUpdated) {
MCRWCMSNavigationUtils.save(navigation);
}
}
protected MCRWCMSContentManager getContentManager() {
return new MCRWCMSContentManager();
}
}
| 5,826 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSAccessResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/resources/MCRWCMSAccessResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.resources;
import java.util.Collection;
import java.util.Date;
import org.mycore.access.mcrimpl.MCRAccessRule;
import org.mycore.access.mcrimpl.MCRAccessStore;
import org.mycore.access.mcrimpl.MCRRuleMapping;
import org.mycore.access.mcrimpl.MCRRuleStore;
import org.mycore.common.MCRSessionMgr;
import org.mycore.frontend.MCRLayoutUtilities;
import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess;
import org.mycore.wcms2.access.MCRWCMSPermission;
import com.google.gson.JsonObject;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response.Status;
@Path("wcms/access")
@MCRRestrictedAccess(MCRWCMSPermission.class)
public class MCRWCMSAccessResource {
@DELETE
public String delete(@QueryParam("webPageID") String webPageID, @QueryParam("perm") String perm) {
JsonObject returnObject = new JsonObject();
if (!MCRLayoutUtilities.hasRule(perm, webPageID)) {
throw new WebApplicationException(Status.NOT_FOUND);
}
MCRAccessStore accessStore = MCRAccessStore.getInstance();
MCRRuleMapping ruleMap = accessStore.getAccessDefinition(perm, MCRLayoutUtilities.getWebpageACLID(webPageID));
accessStore.deleteAccessDefinition(ruleMap);
JsonObject doneObject = new JsonObject();
returnObject.addProperty("type", "editDone");
returnObject.add("edit", doneObject);
return returnObject.toString();
}
@POST
public String createOrUpdate(@QueryParam("webPageID") String webPageID, @QueryParam("perm") String perm,
@QueryParam("ruleID") String ruleID) {
MCRAccessStore accessStore = MCRAccessStore.getInstance();
JsonObject returnObject = new JsonObject();
if (MCRLayoutUtilities.hasRule(perm, webPageID)) {
MCRRuleMapping ruleMap = accessStore.getAccessDefinition(perm,
MCRLayoutUtilities.getWebpageACLID(webPageID));
ruleMap.setRuleId(ruleID);
accessStore.updateAccessDefinition(ruleMap);
} else {
MCRRuleMapping ruleMap = new MCRRuleMapping();
ruleMap.setCreator(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID());
ruleMap.setCreationdate(new Date());
ruleMap.setPool(perm);
ruleMap.setRuleId(ruleID);
ruleMap.setObjId(MCRLayoutUtilities.getWebpageACLID(webPageID));
accessStore.createAccessDefinition(ruleMap);
}
JsonObject doneObject = new JsonObject();
returnObject.addProperty("type", "editDone");
returnObject.add("edit", doneObject);
doneObject.addProperty("ruleId", MCRLayoutUtilities.getRuleID(perm, webPageID));
doneObject.addProperty("ruleDes", MCRLayoutUtilities.getRuleDescr(perm, webPageID));
return returnObject.toString();
}
@GET
public String getRuleList() {
JsonObject returnObject = new JsonObject();
MCRRuleStore store = MCRRuleStore.getInstance();
Collection<String> ruleIds = store.retrieveAllIDs();
for (String id : ruleIds) {
MCRAccessRule rule = store.getRule(id);
returnObject.addProperty(rule.getId(), rule.getDescription());
}
return returnObject.toString();
}
}
| 4,164 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWCMSPermission.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wcms2/src/main/java/org/mycore/wcms2/access/MCRWCMSPermission.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wcms2.access;
import org.mycore.access.MCRAccessManager;
import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker;
import jakarta.ws.rs.container.ContainerRequestContext;
public class MCRWCMSPermission implements MCRResourceAccessChecker {
@Override
public boolean isPermitted(ContainerRequestContext request) {
return MCRAccessManager.checkPermission("use-wcms");
}
}
| 1,156 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMediaSourceType.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/MCRMediaSourceType.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media;
import org.mycore.common.MCRException;
public enum MCRMediaSourceType {
mp4, rtmp_stream, hls_stream, dash_stream;
public String getSimpleType() {
String str = toString();
int pos = str.indexOf('_');
return pos > 0 ? str.substring(0, pos) : str;
}
public String getMimeType() {
return switch (this) {
case mp4 -> "video/mp4";
case hls_stream -> "application/x-mpegURL";
case rtmp_stream -> "rtmp/mp4";
case dash_stream -> "application/dash+xml";
default -> throw new MCRException(this + " has no MIME type defined.");
};
}
}
| 1,402 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/video/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Classes for video (streaming).
* @author Thomas Scheffler
*
*/
package org.mycore.media.video;
| 832 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMediaSource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/video/MCRMediaSource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.video;
import org.apache.logging.log4j.LogManager;
import org.mycore.media.MCRMediaSourceType;
public class MCRMediaSource {
private String uri;
private MCRMediaSourceType type;
public MCRMediaSource(String file, MCRMediaSourceType type) {
LogManager.getLogger().info("uri : {}", file);
this.uri = file;
this.type = type;
}
public String getUri() {
return uri;
}
public MCRMediaSourceType getType() {
return type;
}
}
| 1,248 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMediaSourceProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/video/MCRMediaSourceProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.video;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRAbstractFileStore;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.filter.MCRSecureTokenV2FilterConfig;
import org.mycore.frontend.support.MCRSecureTokenV2;
import org.mycore.media.MCRMediaSourceType;
public class MCRMediaSourceProvider {
private static Optional<String> wowzaBaseURL = MCRConfiguration2.getString("MCR.Media.Wowza.BaseURL");
private static Optional<String> wowzaRTMPBaseURL = MCRConfiguration2
.getString("MCR.Media.Wowza.RTMPBaseURL");
private static String wowzaHashParameter = MCRConfiguration2.getString("MCR.Media.Wowza.HashParameter")
.orElse("wowzatokenhash");
static {
MCRConfiguration2.addPropertyChangeEventLister(p -> p.startsWith("MCR.Media.Wowza"),
MCRMediaSourceProvider::updateWowzaSettings);
}
private Optional<MCRSecureTokenV2> wowzaToken;
private ArrayList<MCRMediaSource> sources;
public MCRMediaSourceProvider(String derivateId, String path, Optional<String> userAgent,
Supplier<String[]> parameterSupplier) throws IOException, URISyntaxException {
try {
wowzaToken = wowzaBaseURL.map(
(w) -> new MCRSecureTokenV2(
MCRConfiguration2.getStringOrThrow("MCR.Media.Wowza.ContentPathPrefix")
+ getContentPath(derivateId, path),
MCRSessionMgr.getCurrentSession().getCurrentIP(),
MCRConfiguration2.getStringOrThrow("MCR.Media.Wowza.SharedSecred"),
parameterSupplier.get()));
} catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException ioe) {
throw ioe;
}
if (cause instanceof URISyntaxException use) {
throw use;
}
throw e;
}
ArrayList<MCRMediaSource> mediaSources = new ArrayList<>(4);
getDashStream()
.map(s -> new MCRMediaSource(s, MCRMediaSourceType.dash_stream))
.ifPresent(mediaSources::add);
userAgent.filter(MCRMediaSourceProvider::mayContainHLSStream).ifPresent(f -> getHLSStream()
.map(s -> new MCRMediaSource(s, MCRMediaSourceType.hls_stream))
.ifPresent(mediaSources::add));
getRTMPStream()
.map(s -> new MCRMediaSource(s, MCRMediaSourceType.rtmp_stream))
.ifPresent(mediaSources::add);
mediaSources.add(
new MCRMediaSource(getPseudoStream(MCRObjectID.getInstance(derivateId), path), MCRMediaSourceType.mp4));
this.sources = mediaSources;
}
public static void updateWowzaSettings(String propertyName, Optional<String> oldValue,
Optional<String> newValue) {
//CSOFF: InnerAssignment
switch (propertyName) {
case "MCR.Media.Wowza.BaseURL" -> wowzaBaseURL = newValue;
case "MCR.Media.Wowza.RTMPBaseURL" -> wowzaRTMPBaseURL = newValue;
case "MCR.Media.Wowza.HashParameter" -> wowzaHashParameter = newValue.orElse("wowzatokenhash");
default -> {
}
}
//CSON: InnerAssignment
}
public List<MCRMediaSource> getSources() {
return Collections.unmodifiableList(sources);
}
private Optional<String> toURL(MCRSecureTokenV2 token, Optional<String> baseURL, String suffix,
String hashParameterName) {
return baseURL.map(b -> {
try {
return token.toURI(b, suffix, hashParameterName).toString();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
});
}
private Optional<String> getDashStream() {
return wowzaToken.flatMap(w -> toURL(w, wowzaBaseURL, "/manifest.mpd", wowzaHashParameter));
}
private Optional<String> getHLSStream() {
return wowzaToken.flatMap(w -> toURL(w, wowzaBaseURL, "/playlist.m3u8", wowzaHashParameter));
}
private Optional<String> getRTMPStream() {
return wowzaToken.flatMap(w -> toURL(w, wowzaRTMPBaseURL, "", wowzaHashParameter));
}
private String getPseudoStream(MCRObjectID derivate, String path) {
return MCRSecureTokenV2FilterConfig.getFileNodeServletSecured(derivate, path);
}
private static String getContentPath(String derivateId, String path) {
try {
MCRPath mcrPath = MCRPath.getPath(derivateId, path);
MCRAbstractFileStore fileStore = (MCRAbstractFileStore) Files.getFileStore(mcrPath);
java.nio.file.Path absolutePath = fileStore.getPhysicalPath(mcrPath);
java.nio.file.Path relativePath = fileStore.getBaseDirectory().relativize(absolutePath);
LogManager.getLogger().info("{} -> {} -> {}", mcrPath, absolutePath, relativePath);
return relativePath.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static boolean mayContainHLSStream(String userAgent) {
//Gecko on Android will not work if we submit HLS stream
return !(userAgent.contains("Android") && userAgent.contains("Gecko"));
}
}
| 6,387 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLFunctions.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/frontend/MCRXMLFunctions.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.frontend;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.mycore.media.video.MCRMediaSource;
import org.mycore.media.video.MCRMediaSourceProvider;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MCRXMLFunctions {
private static final String[] EMPTY_ARRAY = new String[0];
public static NodeList getSources(String derivateId, String path)
throws IOException, ParserConfigurationException, URISyntaxException {
return getSources(derivateId, path, null);
}
public static NodeList getSources(String derivateId, String path, String userAgent)
throws IOException, ParserConfigurationException, URISyntaxException {
MCRMediaSourceProvider provider = new MCRMediaSourceProvider(derivateId, path, Optional.ofNullable(userAgent),
() -> EMPTY_ARRAY);
List<MCRMediaSource> sources = provider.getSources();
Document document = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.newDocument();
return new NodeList() {
@Override
public Node item(int index) {
Element source = document.createElement("source");
source.setAttribute("src", sources.get(index).getUri());
source.setAttribute("type", sources.get(index).getType().getMimeType());
return source;
}
@Override
public int getLength() {
return sources.size();
}
};
}
}
| 2,522 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/frontend/jersey/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Jersey resources
* @author Thomas Scheffler (yagee)
*
*/
package org.mycore.media.frontend.jersey;
| 836 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJWPlayerResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/frontend/jersey/MCRJWPlayerResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.frontend.jersey;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.NoSuchFileException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.glassfish.jersey.server.JSONP;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.media.video.MCRMediaSource;
import org.mycore.media.video.MCRMediaSourceProvider;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response.Status;
/**
* @author Thomas Scheffler (yagee)
*/
@Path("jwplayer")
public class MCRJWPlayerResource {
@Context
private HttpServletRequest request;
@GET
@Path("{derivateId}/{path: .+}/sources.js")
@Produces({ "application/javascript" })
@JSONP(queryParam = "callback")
public String getSourcesAsJSONP(@PathParam("derivateId") String derivateId, @PathParam("path") String path)
throws URISyntaxException, IOException {
// TODO: FIX THIS: https://jersey.java.net/documentation/latest/user-guide.html#d0e8837
return getSources(derivateId, path);
}
@GET
@Path("{derivateId}/{path: .+}/sources.json")
@Produces({ "application/javascript" })
public String getSources(@PathParam("derivateId") String derivateId, @PathParam("path") String path)
throws URISyntaxException, IOException {
MCRObjectID derivate = MCRJerseyUtil.getID(derivateId);
MCRJerseyUtil.checkDerivateReadPermission(derivate);
try {
MCRMediaSourceProvider formatter = new MCRMediaSourceProvider(derivateId, path,
Optional.ofNullable(request.getHeader("User-Agent")),
() -> Arrays.stream(Optional.ofNullable(request.getQueryString()).orElse("").split("&"))
.filter(p -> !p.startsWith("callback="))
.toArray(String[]::new));
return toJson(formatter.getSources());
} catch (NoSuchFileException e) {
LogManager.getLogger().warn("Could not find video file.", e);
throw new WebApplicationException(Status.NOT_FOUND);
}
}
private String toJson(List<MCRMediaSource> sources) {
return new Gson().toJson(sources.stream().map(s -> new Source(s.getUri(), s.getType().getSimpleType())).toArray(
Source[]::new));
}
/* simple pojo for json output */
private static class Source {
@SuppressWarnings("unused")
private String file;
@SuppressWarnings("unused")
private String type;
Source(String file, String type) {
LogManager.getLogger().info("file : {}", file);
this.file = file;
this.type = type;
}
}
}
| 3,774 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRThumbnailResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/frontend/jersey/MCRThumbnailResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.frontend.jersey;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.attribute.FileTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.media.services.MCRThumbnailGenerator;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.CacheControl;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
@Path("thumbnail")
public class MCRThumbnailResource {
@Context
private Request request;
/**
* This method returns a thumbnail for a given document with a given size in pixel for the shortest side.
* @param documentId the documentID you want the thumbnail from
* @param size the size of the shortest side in pixel
* @param ext the extension of the new image file (jpg ord png)
* @return the thumbnail as png, jpg or error 404 if if there is no derivate or no generator for filetype
*/
@GET
@Path("{documentId}/{size}.{ext}")
@Produces({ "image/png", "image/jpeg" })
public Response getThumbnailFromDocument(@PathParam("documentId") String documentId, @PathParam("size") int size,
@PathParam("ext") String ext) {
return getThumbnail(documentId, size, ext);
}
/**
* This method returns a thumbnail for a given document with a default size in pixel for the shortest side.
* @param documentId the documentID you want the thumbnail from
* @param ext the extension of the new image file (jpg ord png)
* @return the thumbnail as png, jpg or error 404 if if there is no derivate or no generator for filetype
*/
@GET
@Path("{documentId}.{ext}")
@Produces({ "image/png", "image/jpeg" })
public Response getThumbnailFromDocument(@PathParam("documentId") String documentId, @PathParam("ext") String ext) {
int defaultSize = MCRConfiguration2.getOrThrow("MCR.Media.Thumbnail.DefaultSize", Integer::parseInt);
return getThumbnail(documentId, defaultSize, ext);
}
private Response getThumbnail(String documentId, int size, String ext) {
List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(MCRJerseyUtil.getID(documentId),
1, TimeUnit.MINUTES);
for (MCRObjectID derivateId : derivateIds) {
if (MCRAccessManager.checkDerivateDisplayPermission(derivateId.toString())) {
String nameOfMainFile = MCRMetadataManager.retrieveMCRDerivate(derivateId).getDerivate().getInternals()
.getMainDoc();
if (nameOfMainFile != null && !nameOfMainFile.equals("")) {
MCRPath mainFile = MCRPath.getPath(derivateId.toString(), '/' + nameOfMainFile);
try {
FileTime lastModified = Files.getLastModifiedTime(mainFile);
Date lastModifiedDate = new Date(lastModified.toMillis());
Response.ResponseBuilder resp = request.evaluatePreconditions(lastModifiedDate);
if (resp != null) {
return resp.build();
}
String mimeType = Files.probeContentType(mainFile);
List<MCRThumbnailGenerator> generators = MCRConfiguration2
.getOrThrow("MCR.Media.Thumbnail.Generators", MCRConfiguration2::splitValue)
.map(MCRConfiguration2::<MCRThumbnailGenerator>instantiateClass)
.filter(thumbnailGenerator -> thumbnailGenerator.matchesFileType(mimeType, mainFile))
.collect(Collectors.toList());
final Optional<BufferedImage> thumbnail = generators.stream()
.map(thumbnailGenerator -> {
try {
return thumbnailGenerator.getThumbnail(mainFile, size);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
})
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
if (thumbnail.isPresent()) {
CacheControl cc = new CacheControl();
cc.setMaxAge((int) TimeUnit.DAYS.toSeconds(1));
String type = "image/png";
if (Objects.equals(ext, "jpg") || Objects.equals(ext, "jpeg")) {
type = "image/jpeg";
}
return Response.ok(thumbnail.get())
.cacheControl(cc)
.lastModified(lastModifiedDate)
.type(type)
.build();
}
} catch (IOException | RuntimeException e) {
throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
}
return Response.status(Response.Status.NOT_FOUND).build();
}
}
| 6,647 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRThumbnailUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/services/MCRThumbnailUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.services;
import java.awt.image.BufferedImage;
public class MCRThumbnailUtils {
public static int getImageType(BufferedImage image) {
int colorType = 12;
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
int colorTypeTemp = getColorType(image.getRGB(x, y));
if (colorTypeTemp == BufferedImage.TYPE_4BYTE_ABGR) {
return BufferedImage.TYPE_4BYTE_ABGR;
}
colorType = colorTypeTemp < colorType ? colorTypeTemp : colorType;
}
}
return colorType;
}
public static int getColorType(int color) {
int alpha = (color >> 24) & 0xff;
int red = (color >> 16) & 0xff;
int green = (color >> 8) & 0xff;
int blue = (color) & 0xff;
if (alpha < 255) {
return BufferedImage.TYPE_4BYTE_ABGR;
}
if (red == green && green == blue) {
if (red == 255 || red == 0) {
return BufferedImage.TYPE_BYTE_BINARY;
}
return BufferedImage.TYPE_BYTE_GRAY;
}
return BufferedImage.TYPE_3BYTE_BGR;
}
}
| 1,950 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPdfThumbnailGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/services/MCRPdfThumbnailGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.services;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.RandomAccessReadBuffer;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDDestinationOrAction;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.mycore.datamodel.niofs.MCRPath;
public class MCRPdfThumbnailGenerator implements MCRThumbnailGenerator {
private static final Logger LOGGER = LogManager.getLogger();
private static final Pattern MATCHING_MIMETYPE = Pattern.compile("^application/pdf");
@Override
public boolean matchesFileType(String mimeType, MCRPath path) {
return MATCHING_MIMETYPE.matcher(mimeType).matches();
}
@Override
public Optional<BufferedImage> getThumbnail(MCRPath path, int size) throws IOException {
try (InputStream fileIS = Files.newInputStream(path);
RandomAccessRead readBuffer = new RandomAccessReadBuffer(fileIS);
PDDocument pdf = Loader.loadPDF(readBuffer)) {
final PDPage page = resolveOpenActionPage(pdf);
float pdfWidth = page.getCropBox().getWidth();
float pdfHeight = page.getCropBox().getHeight();
final int newWidth = pdfWidth > pdfHeight ? (int) Math.ceil(size * pdfWidth / pdfHeight) : size;
final float scale = newWidth / pdfWidth;
PDFRenderer pdfRenderer = new PDFRenderer(pdf);
int pageIndex = pdf.getPages().indexOf(page);
if (pageIndex == -1) {
LOGGER.warn("Could not resolve initial page, using first page.");
pageIndex = 0;
}
BufferedImage pdfRender = pdfRenderer.renderImage(pageIndex, scale);
int imageType = MCRThumbnailUtils.getImageType(pdfRender);
if (imageType == BufferedImage.TYPE_BYTE_BINARY || imageType == BufferedImage.TYPE_BYTE_GRAY) {
BufferedImage thumbnail = new BufferedImage(pdfRender.getWidth(), pdfRender.getHeight(),
imageType);
Graphics g = thumbnail.getGraphics();
g.drawImage(pdfRender, 0, 0, null);
g.dispose();
return Optional.of(thumbnail);
}
return Optional.of(pdfRender);
}
}
private PDPage resolveOpenActionPage(PDDocument pdf) throws IOException {
PDDestinationOrAction openAction = pdf.getDocumentCatalog().getOpenAction();
if (openAction instanceof PDActionGoTo goTo && goTo.getDestination() instanceof PDPageDestination destination) {
openAction = destination;
}
if (openAction instanceof PDPageDestination namedDestination) {
final PDPage pdPage = namedDestination.getPage();
if (pdPage != null) {
return pdPage;
} else {
int pageNumber = namedDestination.getPageNumber();
if (pageNumber != -1) {
return pdf.getPage(pageNumber);
}
}
}
return pdf.getPage(0);
}
}
| 4,345 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRThumbnailGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-media/src/main/java/org/mycore/media/services/MCRThumbnailGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.media.services;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Optional;
import org.mycore.datamodel.niofs.MCRPath;
public interface MCRThumbnailGenerator {
boolean matchesFileType(String mimeType, MCRPath path);
Optional<BufferedImage> getThumbnail(MCRPath path, int size) throws IOException;
}
| 1,090 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/test/java/org/mycore/mcr/neo4j/parser/MCRNeo4JParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.parser;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.language.MCRLanguageFactory;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JParser;
public class MCRNeo4JParserTest extends AbstractNeo4JParserTest {
@BeforeClass
public static void beforeClass() {
System.setProperty("log4j.configurationFile", "log4j2-test.xml");
}
@Test
public void testParseMCRObject() throws Exception {
MCRLanguageFactory.instance().getLanguage("xx");
MCRConfiguration2.set("MCR.Metadata.Type.work", "true");
MCRConfiguration2.set("MCR.Metadata.Type.manuscript", "true");
MCRConfiguration2.set("MCR.Neo4J.NodeAttribute.manuscript.descriptor",
"/mycoreobject/metadata/def.mss82");
MCRConfiguration2.set("MCR.Neo4J.NodeAttribute.manuscript.signature",
"/mycoreobject/metadata/def.mss02");
MCRConfiguration2.set("MCR.Neo4J.ParserClass.MCRMetaLangText",
"org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JMetaLangTextParser");
MCRConfiguration2.set("MCR.Neo4J.ParserClass.MCRMetaClassification",
"org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JMetaClassificationParser");
MCRConfiguration2.set("MCR.Neo4J.ParserClass.MCRMetaHistoryDate",
"org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JMetaHistoryDateParser");
final MCRNeo4JParser parser = new MCRNeo4JParser();
final MCRObject manuscript = new MCRObject(read("/mcrobjects/a_mcrobject_00000001.xml"));
final String result = parser.createNeo4JQuery(manuscript);
System.out.println(result);
assertNotNull(result);
}
protected Document read(String file) throws IOException, JDOMException {
return (new SAXBuilder()).build(this.getClass().getResourceAsStream(file));
}
}
| 2,923 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaLangTextParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/test/java/org/mycore/mcr/neo4j/parser/MCRMetaLangTextParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.List;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JMetaLangTextParser;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
public class MCRMetaLangTextParserTest extends AbstractNeo4JParserTest {
@Test
public void testParseWithoutLang() {
final Element mss01 = metadata.getChild("def.mss01");
final List<Neo4JNode> result = new MCRNeo4JMetaLangTextParser().parse(mss01);
assertEquals(1, result.size());
assertNull(result.get(0).lang());
assertEquals("Test 1", result.get(0).text());
}
@Test
public void testParseWithLang() {
final Element mss82 = metadata.getChild("def.mss82");
final List<Neo4JNode> result = new MCRNeo4JMetaLangTextParser().parse(mss82);
assertEquals(4, result.size());
assertEquals("de", result.get(0).lang());
assertEquals("deutscher text 1", result.get(0).text());
assertEquals("de", result.get(1).lang());
assertEquals("deutscher text 2", result.get(1).text());
assertEquals("de", result.get(2).lang());
assertEquals("deutscher text 3", result.get(2).text());
assertEquals("en", result.get(3).lang());
assertEquals("english text", result.get(3).text());
}
}
| 2,202 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaHistoryDateParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/test/java/org/mycore/mcr/neo4j/parser/MCRMetaHistoryDateParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.parser;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JMetaHistoryDateParser;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
public class MCRMetaHistoryDateParserTest extends AbstractNeo4JParserTest {
@Test
public void testParse() {
final List<Neo4JNode> nodes = new MCRNeo4JMetaHistoryDateParser().parse(metadata.getChild("def.mss28"));
assertEquals(2, nodes.size());
assertEquals("de", nodes.get(0).lang());
assertEquals("12.11.1603", nodes.get(0).text());
assertEquals("en", nodes.get(1).lang());
assertEquals("1603-11-12", nodes.get(1).text());
}
}
| 1,508 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaClassificationParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/test/java/org/mycore/mcr/neo4j/parser/MCRMetaClassificationParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.List;
import org.junit.Test;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JMetaClassificationParser;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
public class MCRMetaClassificationParserTest extends AbstractNeo4JParserTest {
@Test
public void testCreateClassificationNodes() {
final List<Neo4JNode> nodes = new MCRNeo4JMetaClassificationParser().parse(metadata.getChild("def.class_test"));
assertEquals(2, nodes.size());
assertNull(nodes.get(0).lang());
assertEquals("classification_id_-_category_1", nodes.get(0).text());
assertNull(nodes.get(1).lang());
assertEquals("classification_id_-_category_2", nodes.get(1).text());
}
@Test
public void testCreateNoRelationsForUnlinkedCategories() {
final List<Neo4JRelation> relations = new MCRNeo4JMetaClassificationParser().parse(
metadata.getChild("def.unlinked_class"),
MCRObjectID.getInstance("a_mcrobject_00000001"));
assertEquals(0, relations.size());
}
@Test
public void testCreateRelationsForLinkedCategories() throws Exception {
addClassification("/TestOwner.xml");
final List<Neo4JRelation> relations = new MCRNeo4JMetaClassificationParser().parse(
metadata.getChild("def.linked_class"),
MCRObjectID.getInstance("a_mcrobject_00000001"));
assertEquals(2, relations.size());
assertEquals("a_mcrobject_00000001", relations.get(0).sourceNodeID());
assertEquals("a_mcrobject_00000002", relations.get(0).targetNodeID());
assertEquals("MyMssOwner:owner_de0", relations.get(0).relationshipType());
assertEquals("a_mcrobject_00000001", relations.get(1).sourceNodeID());
assertEquals("a_mcrobject_12345678", relations.get(1).targetNodeID());
assertEquals("MyMssOwner:owner_de1", relations.get(1).relationshipType());
}
}
| 2,933 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
AbstractNeo4JParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/test/java/org/mycore/mcr/neo4j/parser/AbstractNeo4JParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.parser;
import java.io.IOException;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.mycore.common.MCRException;
import org.mycore.common.MCRStoreTestCase;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.utils.MCRXMLTransformer;
public abstract class AbstractNeo4JParserTest extends MCRStoreTestCase {
protected final Document doc;
protected final Element metadata;
public AbstractNeo4JParserTest() {
try {
doc = new SAXBuilder().build(getClass().getResourceAsStream("/mcrobjects/a_mcrobject_00000001.xml"));
} catch (JDOMException | IOException e) {
throw new MCRException("Error while loading Resource:", e);
}
metadata = doc.getRootElement().getChild("metadata");
}
@Override
protected Map<String, String> getTestProperties() {
final Map<String, String> properties = super.getTestProperties();
properties.put("MCR.Metadata.Type.mcrobject", "true");
properties.put("MCR.Metadata.Type.derivate", "true");
properties.put("MCR.Metadata.ObjectID.NumberPattern", "00000000");
return properties;
}
protected void addClassification(String file) throws Exception {
Document classification = (new SAXBuilder()).build(this.getClass().getResourceAsStream(file));
MCRCategory category = MCRXMLTransformer.getCategory(classification);
MCRCategoryDAOFactory.getInstance().addCategory((MCRCategoryID) null, category);
}
}
| 2,516 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Neo4JNode.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jutil/Neo4JNode.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil;
public record Neo4JNode(String lang, String text) {
}
| 841 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jutil/MCRNeo4JUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_CLASSID_CATEGID_SEPARATOR;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_CONFIG_PREFIX;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JAbstractDataModelParser;
/**
* Util for Neo4J
*
* @author Andreas Kluge
* @author Jens Kupferschmidt
*/
public class MCRNeo4JUtil {
/**
* Retrieves the label of a classification based on the provided class ID and category ID.
*
* @param classidString the class ID of the classification
* @param categidString the category ID of the classification
* @param language the xml:language attribute (extended by x-)
* @return the label of the classification
*/
public static String getClassificationLabel(String classidString, String categidString, String language) {
String label = "";
MCRCategoryID categid = new MCRCategoryID(classidString, categidString);
MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance();
MCRCategory categ = dao.getCategory(categid, 1);
MCRLabel categLabel = categ.getLabel(language).orElse(null);
if (categLabel != null) {
label = categLabel.getText().replace("'", "");
}
return label;
}
/**
* Retrieves the label of a classification based on the provided class ID and category ID.
*
* @param classID the class ID of the classification
* @param categID the category ID of the classification
* @param lang the xml:language attribute
* @return the label of the classification
*/
public static Optional<String> getClassLabel(final String classID, final String categID, final String lang) {
final MCRCategory category = MCRCategoryDAOFactory.getInstance()
.getCategory(new MCRCategoryID(classID, categID), 1);
if (null == category) {
// LOGGER.warn("Category {}:{} not found!", classID, categID);
return Optional.empty();
}
return category
.getLabel(lang)
.map(label -> StringUtils.replace(label.getText(), "'", ""));
}
public static String removeIllegalRelationshipTypeCharacters(String linkType) {
String filteredType = StringUtils.replace(linkType, ":", NEO4J_CLASSID_CATEGID_SEPARATOR);
filteredType = StringUtils.deleteWhitespace(filteredType);
filteredType = StringUtils.remove(filteredType, '-');
filteredType = StringUtils.remove(filteredType, '"');
filteredType = StringUtils.remove(filteredType, '\'');
filteredType = StringUtils.remove(filteredType, '.');
filteredType = StringUtils.remove(filteredType, ';');
return filteredType;
}
private MCRNeo4JUtil() {
throw new IllegalStateException("Utility class");
}
/**
* Instantiates Neo4JParserClasses from properties and saves them in a Map.
*
* @param propertiesMap Map of String, String with MCR class keys and class paths to be instantiated
* @param filterClassKey don't instantiate a class by a given configuration key, to avoid loop instantiation
* @return Map with parsers for each defined MCR metadata type
*/
public static Map<String, MCRNeo4JAbstractDataModelParser> getMCRNeo4JInstantiatedParserMap(
Map<String, String> propertiesMap, String filterClassKey) {
final Map<String, MCRNeo4JAbstractDataModelParser> parserMap;
parserMap = new HashMap<>();
propertiesMap.forEach((k, v) -> {
// avoid loop instantiation
if (!Objects.equals(k, filterClassKey)) {
parserMap.put(k, MCRConfiguration2.getOrThrow(NEO4J_CONFIG_PREFIX + "ParserClass." + k,
MCRConfiguration2::instantiateClass));
}
});
return parserMap;
}
}
| 5,206 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Neo4JRelation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jutil/Neo4JRelation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JUtil.removeIllegalRelationshipTypeCharacters;
import java.util.concurrent.ThreadLocalRandom;
public record Neo4JRelation(String sourceNodeID, String targetNodeID, String relationshipType) {
@Override
public String toString() {
return "Neo4JRelation{" +
"sourceNode='" + sourceNodeID + '\'' +
", targetNode='" + targetNodeID + '\'' +
", relationshipType='" + relationshipType + '\'' +
'}';
}
/**
* Appends the current query with a directed relation between the current node 'a' and a target node 'b'.
* Since node references needs to be unique within a query, node 'b' will be extended with a random number.
* In Case node 'b' doesn't already exist it will be generated.
* The relationshipType will be filtered of all illegal characters.
*
* sample sub query:
* MERGE (b12345 {id:'MCRID_TARGET_ID'})
* ON CREATE
* SET b12345:AutoGenerated , b12345.id='MCRID_TARGET_ID'
*
* MERGE (a)-[:relationshipType]->(b12345)
*
*
* @return a sub query containing a relation between two nodes
*/
public String toAppendQuery() {
StringBuilder sbQuery = new StringBuilder();
Long random = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);
sbQuery.append("MERGE (b").append(random).append(" {id: '").append(targetNodeID).append("'})\n")
.append("ON CREATE\n")
.append(" SET b").append(random).append(":AutoGenerated").append(" , b").append(random)
.append(".id='")
.append(targetNodeID).append("'\n");
String filteredType = removeIllegalRelationshipTypeCharacters(relationshipType);
sbQuery.append("MERGE (a)-[:").append(filteredType).append("]->(b").append(random)
.append(")\n");
return sbQuery.toString();
}
/**
* Generates a query with a directed relation between the current node 'a' and a target node 'b'.
* Since node references needs to be unique within a query, node 'b' will be extended with a random number.
* In Case node 'a' and/or 'b' doesn't already exist they will be generated.
* The relationshipType will be filtered of all illegal characters.
*
* sample sub query:
* MERGE (a {id:'MCRID_SOURCE_ID'})
* * ON CREATE
* * SET a:AutoGenerated , a.id='MCRID_SOURCE_ID'
* MERGE (b12345 {id:'MCRID_TARGET_ID'})
* ON CREATE
* SET b12345:AutoGenerated , b12345.id='MCRID_TARGET_ID'
*
* MERGE (a)-[:relationshipType]->(b12345)
*
*
* @return a full query containing a relation between two nodes
*/
public String toFullQuery() {
StringBuilder sbQuery = new StringBuilder();
Long random = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE);
sbQuery.append("MERGE (a").append(random).append(" {id: '").append(sourceNodeID).append("'})\n")
.append("ON CREATE\n")
.append(" SET a").append(random).append(":AutoGenerated").append(" , a").append(random)
.append(".id='")
.append(sourceNodeID).append("'\n");
sbQuery.append("MERGE (b").append(random).append(" {id: '").append(targetNodeID).append("'})\n")
.append("ON CREATE\n")
.append(" SET b").append(random).append(":AutoGenerated").append(" , b").append(random)
.append(".id='")
.append(targetNodeID).append("'\n");
String filteredType = removeIllegalRelationshipTypeCharacters(relationshipType);
sbQuery.append("MERGE (a").append(random).append(")-[:").append(filteredType).append("]->(b").append(random)
.append(")\n");
return sbQuery.toString();
}
}
| 4,617 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JConstants.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jutil/MCRNeo4JConstants.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil;
/**
* Utility Class providing constants to Neo4J Implementation
* @author Andreas Kluge (ai112vezo)
*/
public class MCRNeo4JConstants {
public static final String NEO4J_CONFIG_PREFIX = "MCR.Neo4J.";
public static final String DEFAULT_NEO4J_SERVER_URL = NEO4J_CONFIG_PREFIX + "ServerURL";
public static final String NEO4J_PARAMETER_SEPARATOR = "_-_";
public static final String NEO4J_CLASSID_CATEGID_SEPARATOR = "__";
private MCRNeo4JConstants() {
throw new IllegalStateException("Utility class");
}
}
| 1,329 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Neo4JMetaData.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jtojson/Neo4JMetaData.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public record Neo4JMetaData(
@JsonProperty String title,
@JsonProperty List<String> content) {
}
| 974 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Neo4JPathJsonRecord.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jtojson/Neo4JPathJsonRecord.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonRootName("p")
public record Neo4JPathJsonRecord(
@JsonProperty("nodes") List<Neo4JNodeJsonRecord> nodes,
@JsonProperty("relationships") List<Neo4JRelationShipJsonRecord> relationships
// List<Neo4JSegment> segments
) {
}
| 1,359 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Neo4JRelationShipJsonRecord.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jtojson/Neo4JRelationShipJsonRecord.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson;
import java.util.Map;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Neo4JRelationShipJsonRecord(
//Long start,
String startElementId,
//Long end,
String endElementId,
String type,
Long id,
String elementId,
Map<String, String> properties) {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Neo4JRelationShipJsonRecord that = (Neo4JRelationShipJsonRecord) o;
return Objects.equals(startElementId, that.startElementId)
&& Objects.equals(endElementId, that.endElementId)
&& Objects.equals(type, that.type) && Objects.equals(id, that.id)
&& Objects.equals(elementId, that.elementId);
}
@Override
public int hashCode() {
return Objects.hash(startElementId, endElementId, type, id, elementId);
}
}
| 1,951 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Neo4JNodeJsonRecord.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jtojson/Neo4JNodeJsonRecord.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Neo4JNodeJsonRecord(
List<String> type,
String id,
String mcrid,
List<Neo4JMetaData> metadata) {
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Neo4JNodeJsonRecord neo4JNode = (Neo4JNodeJsonRecord) o;
return Objects.equals(id, neo4JNode.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| 1,580 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_CONFIG_PREFIX;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JUtil.getMCRNeo4JInstantiatedParserMap;
import static org.mycore.mcr.neo4j.utils.MCRNeo4JUtilsConfigurationHelper.getConfiguration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Parser Class for Neo4J
* @author Andreas Kluge (ai112vezo)
*/
public class MCRNeo4JParser implements MCRNeo4JMetaParser {
private static final Logger LOGGER = LogManager.getLogger(MCRNeo4JParser.class);
private static final String LANG_UNSET = "__unset__";
private final Map<String, MCRNeo4JAbstractDataModelParser> parserMap;
private static final String CLASS_KEY = "BaseParser";
public MCRNeo4JParser() {
Map<String, String> propertiesMap = MCRConfiguration2.getSubPropertiesMap(NEO4J_CONFIG_PREFIX + "ParserClass.");
parserMap = getMCRNeo4JInstantiatedParserMap(propertiesMap, CLASS_KEY);
}
private String parseSourceNodeInformation(MCRObject mcrObject, XPathFactory xpf,
Map<String, String> attributes, Document xml) {
// "Set a:<type>, a:id='Wert', a.name='MYNAME', a.descriptor='desc'"
StringBuilder sbNode = new StringBuilder();
MCRObjectID id = mcrObject.getId();
sbNode.append(" SET a:").append(id.getTypeId()).append(" , a.id='").append(id).append('\'');
attributes.forEach((k, v) -> LOGGER.debug("Neo4J property configuration {} {}", k, v));
parserMap.forEach((k, v) -> LOGGER.debug("Neo4J configured Parser {} {}", k, v));
attributes.forEach((k, v) -> {
if (k.startsWith("link") && v.length() > 0) {
return;
}
XPathExpression<Element> xpath = xpf.compile(v, Filters.element(), null);
List<Element> elements = xpath.evaluate(xml);
if (elements.isEmpty()) {
LOGGER.warn("No entries for path {}", v);
return;
}
for (Element parent : elements) {
LOGGER.debug("current Element: {}", parent);
Attribute classAttribute = parent.getAttribute("class");
if (classAttribute == null) {
LOGGER.error("Parent of current Element: {}", parent.getParent());
LOGGER.error("NULL Class printing current Element {}", parent);
LOGGER.error("Parser Attributes {}", parent.getAttributes());
// TODO: return (no crash/error message) or no return and let it crash
return;
}
LOGGER.debug("parse: {}", classAttribute);
MCRNeo4JAbstractDataModelParser clazz = parserMap.get(classAttribute.getValue());
if (null == clazz) {
throw new MCRException("Parser class for " + classAttribute.getValue() + " not set!");
}
for (Element elm : elements) {
final List<Neo4JNode> nodes = clazz.parse(elm);
final Map<String, List<String>> langNodes = new HashMap<>(nodes.size());
// add nodes with a language to their respective key
nodes.stream()
.filter(node -> StringUtils.isNotBlank(node.lang()))
.forEach(
node -> langNodes.computeIfAbsent(node.lang(), val -> new ArrayList<>()).add(node.text()));
// add nodes without a language to the unset language key
nodes.stream()
.filter(node -> StringUtils.isBlank(node.lang()))
.forEach(
node -> langNodes.computeIfAbsent(LANG_UNSET, val -> new ArrayList<>()).add(node.text()));
for (Map.Entry<String, List<String>> entries : langNodes.entrySet()) {
final String lang = entries.getKey();
final List<String> text = entries.getValue();
final String key;
if (StringUtils.equals(lang, LANG_UNSET)) {
key = k;
} else {
key = k + "_" + lang;
}
final String cleaned = text.stream()
.map(value -> StringUtils.replace(value, "'", ""))
.collect(Collectors.joining("', '", "['", "']"));
sbNode.append(", a.").append(key).append('=').append(cleaned);
}
}
}
});
sbNode.append('\n');
return sbNode.toString();
}
public String createNeo4JQuery(MCRObject mcrObject) {
MCRObjectID id = mcrObject.getId();
String type = id.getTypeId();
XPathFactory xpf = XPathFactory.instance();
Map<String, String> attributes = getConfiguration(type);
Document xml = mcrObject.createXML();
String sourceNodeInformation = parseSourceNodeInformation(mcrObject, xpf, attributes, xml);
StringBuilder sbQuery = new StringBuilder();
// CHECK if Node is Already existing
sbQuery.append("MERGE (a {id: '").append(id).append("'})\n");
// IF not found, Create it
sbQuery.append("ON CREATE\n");
sbQuery.append(sourceNodeInformation);
// IF already exists though created by Relation Target
sbQuery.append("ON Match\n").append(sourceNodeInformation)
.append(", a.temp = ''\n")
.append("WITH *\n")
.append("CALL { WITH a\n").append(" WITH a WHERE a.temp IS NOT NULL\n").append(" REMOVE a.temp\n")
.append(" REMOVE a:AutoGenerated}\n");
attributes.forEach((k, v) -> {
if (k.startsWith("link") && v.length() > 0) {
XPathExpression<Element> xpath = xpf.compile(v, Filters.element(), null);
List<Element> elms = xpath.evaluate(xml);
if (elms.isEmpty()) {
LOGGER.warn("No entries for path {}", v);
return;
}
for (Element parent : elms) {
LOGGER.info("current Element: {}", parent);
Attribute classAttribute = parent.getAttribute("class");
LOGGER.info("parse: {}", classAttribute.getValue());
MCRNeo4JAbstractDataModelParser clazz = parserMap.get(classAttribute.getValue());
for (Element elm : elms) {
// should only one elm in elms
List<Neo4JRelation> relations = clazz.parse(elm, id);
relations.stream().forEach((relation) -> {
sbQuery.append(relation.toAppendQuery());
sbQuery.append('\n');
});
}
}
}
});
return sbQuery.toString();
}
@Override
public String createNeo4JUpdateQuery(MCRObject mcrObject) {
MCRObjectID id = mcrObject.getId();
StringBuilder queryBuilder = new StringBuilder();
// remove outgoing Relationships and reset all properties besides node id and mcrid
queryBuilder.append("MATCH (n {id:'").append(id).append("'}) \n");
queryBuilder.append("OPTIONAL MATCH (n)-[r]->() DELETE r \n");
queryBuilder.append("SET n = {id: '").append(id).append("'} \n");
return queryBuilder.toString();
}
}
| 9,169 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JAbstractDataModelParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JAbstractDataModelParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import java.util.List;
import org.jdom2.Element;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Abstract class for Neo4J Parsers
* @author Andreas Kluge (ai112vezo)
*/
public abstract class MCRNeo4JAbstractDataModelParser {
public abstract List<Neo4JRelation> parse(Element classElement, MCRObjectID sourceID);
/**
* The corresponding DataModel Parser extracts the information within the {@code <rootTag>}
* and return the information as {@code <T>}
* <p>
* The calling MCRNeo4JMetaParser implementation may require different return types.
* <p>
* The implementation of MCRNeo4JParser requires either {@code List<String>} or {@code Map<String, List<String>>}
*
* @param rootTag jdom2 Element
* @return {@code <T>} Handled by the calling MCRNeo4JMetaParser implementation
*/
public abstract List<Neo4JNode> parse(Element rootTag);
}
| 1,829 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JMetaISO8601DateParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JMetaISO8601DateParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import org.jdom2.Element;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Neo4J DataModelParser for ISO8601 Dates
* @author Jens Kupferschmidt
*/
public class MCRNeo4JMetaISO8601DateParser extends MCRNeo4JAbstractDataModelParser {
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
SimpleDateFormat deFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.ROOT);
SimpleDateFormat enFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ROOT);
@Override
public List<Neo4JRelation> parse(Element classElement, MCRObjectID sourceID) {
return Collections.emptyList();
}
@Override
public List<Neo4JNode> parse(Element rootTag) {
List<Neo4JNode> values = new ArrayList<>();
for (Element element : rootTag.getChildren()) {
final String text = element.getTextTrim();
if (text != null && text.length() > 0) {
try {
final String formattedDe = deFormat.format(isoFormat.parse(text));
values.add(new Neo4JNode("de", formattedDe));
final String formattedEn = enFormat.format(isoFormat.parse(text));
values.add(new Neo4JNode("en", formattedEn));
} catch (ParseException e) {
values.add(new Neo4JNode("de", text));
values.add(new Neo4JNode("en", text));
}
}
}
return values;
}
}
| 2,586 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JMetaParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JMetaParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import org.mycore.datamodel.metadata.MCRObject;
/**
* Neo4J Parser Interface
* @author Andreas Kluge (ai112vezo)
*/
public interface MCRNeo4JMetaParser {
String createNeo4JQuery(MCRObject mcrObject);
String createNeo4JUpdateQuery(MCRObject mcrObject);
}
| 1,057 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JMetaHistoryDateParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JMetaHistoryDateParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Neo4J DataModelParser for HistoryDates
* @author Andreas Kluge (ai112vezo)
*/
public class MCRNeo4JMetaHistoryDateParser extends MCRNeo4JAbstractDataModelParser {
@Override
public List<Neo4JRelation> parse(Element classElement, MCRObjectID sourceID) {
return Collections.emptyList();
}
@Override
public List<Neo4JNode> parse(Element rootTag) {
List<Neo4JNode> values = new ArrayList<>();
for (Element element : rootTag.getChildren()) {
for (Element text : element.getChildren("text")) {
final String lang = text.getAttributeValue("lang", Namespace.XML_NAMESPACE);
final String content = StringUtils.replace(text.getTextTrim(), "'", "");
values.add(new Neo4JNode(lang, content));
}
}
return values;
}
}
| 2,012 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JMetaLangTextParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JMetaLangTextParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Neo4J DataModelParser for LangText
* @author Andreas Kluge (ai112vezo)
*/
public class MCRNeo4JMetaLangTextParser extends MCRNeo4JAbstractDataModelParser {
@Override
public List<Neo4JRelation> parse(Element classElement, MCRObjectID sourceID) {
return Collections.emptyList();
}
@Override
public List<Neo4JNode> parse(Element rootTag) {
final List<Neo4JNode> nodes = new ArrayList<>();
for (Element element : rootTag.getChildren()) {
if (element != null) {
final String lang = element.getAttributeValue("lang", Namespace.XML_NAMESPACE);
final String text = StringUtils.replace(element.getTextTrim(), "'", "");
nodes.add(new Neo4JNode(lang, text));
}
}
return nodes;
}
}
| 1,979 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JMetaLinkIDParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JMetaLinkIDParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRConstants;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Neo4J DataModelParser for MCRObject LinkID
* @author Andreas Kluge (ai112vezo)
*/
public class MCRNeo4JMetaLinkIDParser extends MCRNeo4JAbstractDataModelParser {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public List<Neo4JRelation> parse(Element classElement, MCRObjectID sourceID) {
List<Neo4JRelation> relations = new ArrayList<>();
for (Element element : classElement.getChildren()) {
String linkType = element.getAttributeValue("type");
String linkHref = element.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE);
if (linkHref != null && linkHref.trim().length() > 0) {
try {
MCRObjectID.getInstance(linkHref);
LOGGER.debug("Got MCRObjectID from {}", linkHref);
} catch (Exception e) {
LOGGER.warn("The xlink:href is not a MCRObjectID");
continue;
}
}
if (linkHref == null) {
LOGGER.error("No relationship target for node {}", sourceID);
continue;
}
if (linkType == null || linkType.trim().length() == 0) {
LOGGER.warn("Set default link type reference for {}", sourceID);
linkType = "reference";
}
relations.add(new Neo4JRelation(sourceID.getTypeId(), linkHref, linkType));
}
return relations;
}
@Override
public List<Neo4JNode> parse(Element rootTag) {
return Collections.emptyList();
}
}
| 2,823 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JMetaXMLParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JMetaXMLParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_CONFIG_PREFIX;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JUtil.getMCRNeo4JInstantiatedParserMap;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Neo4J DataModelParser for XML
* @author Andreas Kluge (ai112vezo)
*/
public class MCRNeo4JMetaXMLParser extends MCRNeo4JAbstractDataModelParser {
private final Map<String, MCRNeo4JAbstractDataModelParser> parserMap;
private static final Logger LOGGER = LogManager.getLogger();
private static final String CLASS_KEY = "MCRMetaXML";
public MCRNeo4JMetaXMLParser() {
Map<String, String> propertiesMap = MCRConfiguration2.getSubPropertiesMap(NEO4J_CONFIG_PREFIX + "ParserClass.");
parserMap = getMCRNeo4JInstantiatedParserMap(propertiesMap, CLASS_KEY);
}
@Override
public List<Neo4JRelation> parse(Element classElement, MCRObjectID sourceID) {
return Collections.emptyList();
}
@Override
public List<Neo4JNode> parse(Element rootTag) {
if (rootTag.getChildren().size() > 0) {
Element child = rootTag.getChildren().get(0);
if (child.getChildren().size() > 0) {
Element grandChild = child.getChildren().get(0);
String nameTag = grandChild.getName();
MCRNeo4JAbstractDataModelParser clazz = parserMap.get("MCRMetaXML." + nameTag);
if (null == clazz) {
LOGGER.warn("Parser class for MCRMetaXML.{} not set!", nameTag);
} else {
return clazz.parse(grandChild);
}
}
}
return Collections.emptyList();
}
}
| 2,904 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JMetaClassificationParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/datamodel/metadata/neo4jparser/MCRNeo4JMetaClassificationParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_PARAMETER_SEPARATOR;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JUtil.getClassLabel;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Element;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JNode;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.Neo4JRelation;
/**
* Neo4J DataModelParser for Classifications
* @author Andreas Kluge (ai112vezo)
* @author Jens Kupferschmidt
* @author Michael Becker
*/
public class MCRNeo4JMetaClassificationParser extends MCRNeo4JAbstractDataModelParser {
@Override
public List<Neo4JRelation> parse(Element classElement, MCRObjectID sourceID) {
final List<Neo4JRelation> relations = new ArrayList<>(classElement.getChildren().size());
final String sourceNodeID = sourceID.toString();
for (Element element : classElement.getChildren()) {
final String classID = element.getAttributeValue("classid");
final String categID = element.getAttributeValue("categid");
final String relationshipType = classID + ":" + categID;
if (StringUtils.isBlank(classID) || StringUtils.isBlank(categID)) {
continue;
}
final Optional<String> href = getClassLabel(classID, categID, "x-mcrid");
href.ifPresent(
targetNodeID -> relations.add(new Neo4JRelation(sourceNodeID, targetNodeID, relationshipType)));
}
return relations;
}
@Override
public List<Neo4JNode> parse(Element rootTag) {
List<Neo4JNode> values = new ArrayList<>();
for (Element element : rootTag.getChildren()) {
String classidString = element.getAttributeValue("classid");
String categidString = element.getAttributeValue("categid");
values.add(new Neo4JNode(null, classidString + NEO4J_PARAMETER_SEPARATOR + categidString));
}
return values;
}
}
| 2,954 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/utils/MCRNeo4JManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.utils;
import org.mycore.datamodel.metadata.MCRObject;
/**
* Interface for Neo4JUtils
* @author Andreas Kluge
* @author Jens Kupferschmidt
*/
public interface MCRNeo4JManager {
/**
* Adds a node to Neo4j based on the provided MCRObject and its configuration according to the
* MCRNeo4JUtilsConfigurationHelper class.
*
* @param mcrObject the MCRObject to be added as a node
*/
void addNodeByMCRObject(MCRObject mcrObject);
/**
* Updates a node in Neo4j based on the provided MCRObject.
*
* @param mcrObject the MCRObject to be updated
*/
void updateNodeByMCRObject(MCRObject mcrObject);
/**
* Deletes a node and its relation from Neo4j based on the provided MCRObject ID.
*
* @param id the ID of the MCRObject representing the node to be deleted
*/
void deleteNodeByMCRObjectID(String id);
}
| 1,634 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JUtilsConfigurationHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/utils/MCRNeo4JUtilsConfigurationHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.utils;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_CONFIG_PREFIX;
import java.util.HashMap;
import java.util.Map;
import org.mycore.common.config.MCRConfiguration2;
/**
* The MCRNeo4JUtilsConfigurationHelper class provides utility methods for managing configuration settings related to
* Neo4j in MyCoRe. It maintains a map of attribute paths for different MCR object types.
* <p>
* Note: This class assumes the usage of MyCoRe and its specific configuration conventions. The attributePaths map
* follows the format: {@code Map<MCRObjectType, Map<property, path_to_element>>}
* <p>
* Example usage: {@code Map<String, String> configuration =
* MCRNeo4JUtilsConfigurationHelper.getConfiguration("ObjectType");}
* {@code String idPath = configuration.get("id"); String descriptorPath = configuration.get("descriptor");}
* // Use the configuration for further processing
* <p>
* Note: This class utilizes the MCRConfiguration2 class for retrieving configuration properties.
*
* @author Andreas Kluge
* @author Jens Kupferschmidt
*/
public class MCRNeo4JUtilsConfigurationHelper {
/**
* A map of MyCoRe properties starts with {@code MCR.Neo4J... Map<MCRObjectType, Map<property, path_to_element>>}
*/
static Map<String, Map<String, String>> attributePaths = new HashMap<>();
/**
* Retrieves the configuration for the specified MCR object type. Configured in the Style of
* {@code MCR.Neo4J.NodeAttribute.<MCRObjectType>.propertyName=Path/to/value}
*
* @param type the MCR object type
* @return a map of attribute paths for the specified object type
*/
public static Map<String, String> getConfiguration(String type) {
if (attributePaths.containsKey(type)) {
return attributePaths.get(type);
}
Map<String, String> properties = MCRConfiguration2.getSubPropertiesMap(NEO4J_CONFIG_PREFIX
+ "NodeAttribute." + type + ".");
Map<String, String> attributes = new HashMap<>();
attributes.put("id", "/mycoreobject/@ID");
attributes.put("type", type);
String desc = properties.get("descriptor");
if (desc != null && desc.length() > 1) {
attributes.put("descriptor", desc);
} else {
attributes.put("descriptor", "/mycoreobject/@label");
}
properties.forEach((k, v) -> {
if (!k.startsWith("descriptor")) {
attributes.put(k, v);
}
});
attributePaths.put(type, attributes);
return attributes;
}
private MCRNeo4JUtilsConfigurationHelper() {
throw new IllegalStateException("Utility class");
}
}
| 3,469 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JDatabaseDriver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/utils/MCRNeo4JDatabaseDriver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Query;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
/**
* The MCRNeo4JDatabaseDriver class is a Java driver implementation for connecting to a Neo4j database. It provides
* methods to establish a connection, test connection settings, and execute queries.
*
* @author Andreas Kluge
*/
public class MCRNeo4JDatabaseDriver {
private static final Logger LOGGER = LogManager.getLogger();
private static MCRNeo4JDatabaseDriver instance = null;
private final String url;
private String user;
private String password;
private Driver driver;
/**
* Constructs an MCRNeo4JDatabaseDriver object with connection settings loaded from a configuration file.
*/
private MCRNeo4JDatabaseDriver() {
this.url = MCRConfiguration2.getString(MCRNeo4JConstants.NEO4J_CONFIG_PREFIX + "ServerURL").orElse("");
this.user = MCRConfiguration2.getString(MCRNeo4JConstants.NEO4J_CONFIG_PREFIX + "user").orElse("");
this.password = MCRConfiguration2.getString(MCRNeo4JConstants.NEO4J_CONFIG_PREFIX + "password").orElse("");
}
/**
* Returns an instance of MCRNeo4JDatabaseDriver. If no instance exists, a new one is created.
*
* @return the MCRNeo4JDatabaseDriver instance
*/
public static MCRNeo4JDatabaseDriver getInstance() {
if (instance == null) {
instance = new MCRNeo4JDatabaseDriver();
}
return instance;
}
/**
* Tests the connection settings by checking if the URL, username, and password are set, if the driver is
* initialized and submits a test query.
*
* @return true if the connection settings are valid, false otherwise
*/
public boolean testConnectionSettings() {
if (url.isEmpty() || user.isEmpty() || password.isEmpty()) {
if (url.isEmpty()) {
LOGGER.info("No database URL");
}
if (user.isEmpty()) {
LOGGER.info("No user");
}
if (password.isEmpty()) {
LOGGER.info("No password");
}
return false;
}
if (driver == null) {
LOGGER.info("driver is null");
return false;
}
try {
driver.verifyConnectivity();
} catch (Exception e) {
LOGGER.info("Verification failed");
return false;
}
try (Session session = driver.session()) {
String queryResult = session.executeWrite(tx -> {
Query query = new Query("RETURN '1'");
Result result = tx.run(query);
return result.single().get(0).asString();
});
LOGGER.info("Test query result is: {}", queryResult);
return queryResult.equals("1");
} catch (Exception e) {
LOGGER.info("Exception: {}", e.getMessage());
}
return false;
}
/**
* Returns the driver used for the database connection. If the driver is not initialized, a connection is created.
*
* @return the Neo4j driver
*/
public Driver getDriver() {
if (this.driver == null) {
createConnection();
}
return driver;
}
/**
* Creates a connection to the Neo4j database using the stored connection settings.
*/
private void createConnection() {
this.driver = GraphDatabase.driver(url, AuthTokens.basic(user, password));
}
/**
* Creates a connection to the Neo4j database using the specified URL, username, and password.
*
* @param url the URL of the Neo4j database
* @param user the username for the database connection
* @param password the password for the database connection
*/
public void createConnection(String url, String user, String password) {
this.driver = GraphDatabase.driver(url, AuthTokens.basic(user, password));
}
}
| 5,047 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JQueryRunner.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/utils/MCRNeo4JQueryRunner.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.utils;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_PARAMETER_SEPARATOR;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JUtil.getClassificationLabel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson.Neo4JMetaData;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson.Neo4JNodeJsonRecord;
import org.mycore.mcr.neo4j.index.MCRNeo4JIndexEventHandler;
import org.neo4j.driver.Driver;
import org.neo4j.driver.Query;
import org.neo4j.driver.Record;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.neo4j.driver.Value;
import org.neo4j.driver.types.Node;
import org.neo4j.driver.types.Path;
import org.neo4j.driver.types.Relationship;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class MCRNeo4JQueryRunner {
private static final Logger LOGGER = LogManager.getLogger(MCRNeo4JIndexEventHandler.class);
private static final String LANGUAGE = MCRConfiguration2.getString("MCR.Metadata.DefaultLang").orElse("de");
/**
* Executes a write-only query in Neo4j using the provided query string. This function is responsible for executing
* queries that modify the Neo4j database.
*
* @param queryString the query string to be executed
*/
public static void commitWriteOnlyQuery(String queryString) {
Driver driver = MCRNeo4JDatabaseDriver.getInstance().getDriver();
try {
driver.verifyConnectivity();
} catch (Exception e) {
LOGGER.error("Neo4J connection failed.", e.getCause());
return;
}
try (Session session = driver.session()) {
session.executeWrite(tx -> {
Query query = new Query(queryString);
return tx.run(query);
});
}
}
/**
* Executes a read-only query in Neo4j using the provided query string and returns the result as a list of JSON
* strings. This function is responsible for executing queries that retrieve data from the Neo4j database.
*
* @param queryString the query string to be executed
* @param lang the language for parsing
* @return a list of a Map with keys containing the type_recordKey and as value the JSON strings representing the
* query result for the given key
*/
public static List<Map<String, String>> commitReadOnlyQuery(String queryString, String lang) {
Driver driver = MCRNeo4JDatabaseDriver.getInstance().getDriver();
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
AtomicInteger counter = new AtomicInteger();
try (Session session = driver.session()) {
return session.executeRead(tx -> {
List<Map<String, String>> records = new ArrayList<>();
Result result = tx.run(queryString);
while (result.hasNext()) {
Record thisRecord = result.next();
Map<String, String> keyMap = new HashMap<>();
for (String key : thisRecord.keys()) {
Value recordData = thisRecord.get(key);
counter.getAndAdd(1);
if (StringUtils.equals(recordData.type().name(), "NODE")) {
String node = gson.toJson(nodeToNeo4JNodeJsonRecord(recordData.asNode(), lang));
String nodeSB = "{\"n\":" + node + "}";
LOGGER.debug("record is Node");
keyMap.put("node_" + key, nodeSB);
} else if (StringUtils.equals(recordData.type().name(), "RELATIONSHIP")) {
LOGGER.debug("record is Relationship");
keyMap.put("rel_" + key, "{\"r\":" + gson.toJson(recordData.asRelationship()) + "}");
} else if (StringUtils.equals(recordData.type().name(), "PATH")) {
StringBuilder pathSB = new StringBuilder();
LOGGER.debug("record is Path");
//Gather Stuff
Path neo4jPath = recordData.asPath();
Node startNode = neo4jPath.start();
Node endNode = neo4jPath.end();
Iterable<Relationship> relationships = neo4jPath.relationships();
// Parse Stuff to use full Json
String start = gson.toJson(nodeToNeo4JNodeJsonRecord(startNode, lang));
String end = gson.toJson(nodeToNeo4JNodeJsonRecord(endNode, lang));
String relationshipJson = gson.toJson(relationships);
pathSB.append("{\"p\":{\"nodes\":[");
pathSB.append(start).append(',');
pathSB.append(end).append("],");
pathSB.append("\"relationships\":").append(relationshipJson);
pathSB.append("}}");
keyMap.put("path_" + key, pathSB.toString());
} else if (StringUtils.equals(recordData.type().name(), "NULL")) {
LOGGER.warn("Got record of type {} for key {} which is not parsed and is ignored",
recordData.type().name(), key);
} else {
LOGGER.warn("Got record of type {} for key {} which is not parsed",
recordData.type().name(), key);
keyMap.put(key, gson.toJson(thisRecord.asMap()));
}
}
records.add(keyMap);
}
return records;
});
}
}
private static Neo4JNodeJsonRecord nodeToNeo4JNodeJsonRecord(Node startNode, String lang) {
String elementId = startNode.elementId();
boolean mcridBool = startNode.asMap().containsKey("id");
List<Neo4JMetaData> neo4JMetaDataList = wrapPropertiesMapTranslation(startNode.asMap(), lang);
List<String> labels = new ArrayList<>();
for (String label : startNode.labels()) {
labels.add(label);
}
if (mcridBool) {
String mcrID = String.valueOf(startNode.asMap().get("id"));
return new Neo4JNodeJsonRecord(labels, elementId, mcrID, neo4JMetaDataList);
} else {
return new Neo4JNodeJsonRecord(labels, elementId, "", neo4JMetaDataList);
}
}
/**
* Wrapper between MyCore i18n translation logic and (non language specific) neo4j database representation.
* if lang is null -> use default language or de for translation
* if key is longer than 3 chars and ends with _xy checks if xy equals lang, if true translate else skip this key
* else case: translate value with corresponding lang
*
* @param map key-value-pairs, translate the values
* @param lang MyCore Language short notation
* @return List of translated Neo4JMetaData Objects
*/
private static List<Neo4JMetaData> wrapPropertiesMapTranslation(Map<String, Object> map, String lang) {
List<Neo4JMetaData> metaDataList = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (lang == null) {
translateAndMapProperties(metaDataList, key, value, LANGUAGE);
} else {
if (key.length() > 3 && key.charAt(key.length() - 3) == '_') {
if (key.substring(key.length() - 2).equals(lang)) {
translateAndMapProperties(metaDataList, key, value, lang);
}
} else {
translateAndMapProperties(metaDataList, key, value, lang);
}
}
}
return metaDataList;
}
private static void translateAndMapProperties(List<Neo4JMetaData> metaDataList, String key, Object value,
String lang) {
if (value instanceof List<?>) {
List<String> stringList = ((List<?>) value).stream().map(Object::toString).toList();
if (stringList.size() == 1) {
if (stringList.get(0).contains(NEO4J_PARAMETER_SEPARATOR)) {
String[] sep = stringList.get(0).split(NEO4J_PARAMETER_SEPARATOR);
String classification = getClassificationLabel(sep[0], sep[1], lang);
metaDataList.add(new Neo4JMetaData(key, List.of(classification)));
}
} else {
metaDataList.add(new Neo4JMetaData(key, stringList));
}
} else if (value instanceof String) {
if (((String) value).contains(NEO4J_PARAMETER_SEPARATOR)) {
String[] sep = ((String) value).split(NEO4J_PARAMETER_SEPARATOR);
String classification = getClassificationLabel(sep[0], sep[1], lang);
metaDataList.add(new Neo4JMetaData(key, List.of(classification)));
} else {
metaDataList.add(new Neo4JMetaData(key, List.of(value.toString())));
}
} else {
LOGGER.info("Value ELSE: {}", value);
}
}
}
| 10,495 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JDefaultManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/utils/MCRNeo4JDefaultManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JMetaParser;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JParser;
/**
* The MCRNeo4JUtilsDefault class is an implementation of the MCRNeo4JUtilsInterface. It provides methods for adding,
* updating, and deleting nodes in Neo4j based on MCRObject instances.
* <p>
* Note: This class assumes the usage of MyCoRe and its specific configuration conventions. It relies on the
* MCRConfiguration2 and MCRCategoryDAO classes for retrieving configuration properties and category information,
* respectively.
* <p>
* Example usage: MCRNeo4JUtilsDefault neo4jUtils = new MCRNeo4JUtilsDefault(); MCRObject mcrObject = // Obtain the
* MCRObject instance neo4jUtils.addNodeByMCRObject(mcrObject); // Perform further operations
* <p>
* Note: The LOGGER in this class uses Log4j2 for logging.
*
* @author Andreas Kluge
* @author Jens Kupferschmidt
*/
public class MCRNeo4JDefaultManager implements MCRNeo4JManager {
private static final Logger LOGGER = LogManager.getLogger(MCRNeo4JDefaultManager.class);
private final MCRNeo4JMetaParser parser;
public MCRNeo4JDefaultManager() {
parser = new MCRNeo4JParser();
}
/**
* Adds a node to Neo4j based on the provided MCRObject and its configuration according to the
* MCRNeo4JUtilsConfigurationHelper class.
*
* @param mcrObject the MCRObject to be added as a node
*/
@Override
public void addNodeByMCRObject(MCRObject mcrObject) {
String queryString = parser.createNeo4JQuery(mcrObject);
LOGGER.info("Query: {}", queryString);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(queryString);
}
/**
* Updates a node in Neo4j based on the provided MCRObject. This method delegates the operation to addNodeByMCRObject
* as there is no separate update functionality.
*
* @param mcrObject the MCRObject to be updated
*/
@Override
public void updateNodeByMCRObject(MCRObject mcrObject) {
String updateQuery = parser.createNeo4JUpdateQuery(mcrObject);
LOGGER.info("UpdateQuery: {}", updateQuery);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(updateQuery);
addNodeByMCRObject(mcrObject);
}
/**
* Deletes a node from Neo4j based on the provided MCRObject ID.
*
* @param id the ID of the MCRObject representing the node to be deleted
*/
@Override
public void deleteNodeByMCRObjectID(String id) {
String queryString = "MATCH (n {id:'" + id + "'}) DETACH DELETE n;";
MCRNeo4JQueryRunner.commitWriteOnlyQuery(queryString);
}
}
| 3,538 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/frontend/cli/MCRNeo4JCommands.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.frontend.cli;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.cli.MCRAbstractCommands;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JParser;
import org.mycore.mcr.neo4j.utils.MCRNeo4JDatabaseDriver;
import org.mycore.mcr.neo4j.utils.MCRNeo4JManager;
import org.mycore.mcr.neo4j.utils.MCRNeo4JQueryRunner;
@MCRCommandGroup(name = "Commands to handle Neo4J")
@SuppressWarnings("unused")
public class MCRNeo4JCommands extends MCRAbstractCommands {
private static final String NEO4J_MANAGER_CLASS_PROPERTY = "MCR.Neo4J.Manager.Class";
private static final Logger LOGGER = LogManager.getLogger(MCRNeo4JCommands.class.getName());
@MCRCommand(syntax = "clean neo4j for id {0}", help = "clean the Neo4J database for an ID {0}", order = 10)
public static void cleanForMCRID(final String id) {
LOGGER.info("Start clean data from Neo4J instance for an MCRID");
String queryString = "MATCH (n {id:'" + id + "'}) DETACH DELETE n";
LOGGER.info("Query: {}", queryString);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(queryString);
}
@MCRCommand(syntax = "clean neo4j for base {0}", help = "clean the Neo4J database for a MCRBase {0}", order = 20)
public static void cleanForBase(final String baseId) {
LOGGER.info("Start clean data from Neo4J instance for MCRBase {}", baseId);
List<String> selectedObjectIds = MCRXMLMetadataManager
.instance().listIDsForBase(baseId);
for (String objectId : selectedObjectIds) {
String queryString = "MATCH (n {id:'" + objectId + "'}) DETACH DELETE n";
LOGGER.info("Query: {}", queryString);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(queryString);
}
}
@MCRCommand(syntax = "clean neo4j for type {0}", help = "clean the Neo4J database for a MCRType {0}", order = 30)
public static void cleanForType(final String type) {
LOGGER.info("Start clean data from Neo4J instance for MCRType {}", type);
String queryString = "MATCH (n:" + type + ") DETACH DELETE n";
LOGGER.info("Query: {}", queryString);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(queryString);
}
@MCRCommand(syntax = "clean neo4j metadata", help = "clean the complete Neo4J database", order = 40)
public static void cleanAll() {
LOGGER.info("Start clean all data from Neo4J");
String queryString = "MATCH (n) DETACH DELETE n";
LOGGER.info("Query: {}", queryString);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(queryString);
}
@MCRCommand(syntax = "synchronize neo4j for id {0}",
help = "synchronize metadata to the Neo4J database for MCRID {0}",
order = 50)
public static void synchronizeForMCRID(final String id) {
LOGGER.info("Synchronize Neo4J with metadata for MCRID");
MCRNeo4JManager clazz = MCRConfiguration2.getOrThrow(NEO4J_MANAGER_CLASS_PROPERTY,
MCRConfiguration2::instantiateClass);
MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(id));
clazz.updateNodeByMCRObject(mcrObject);
}
@MCRCommand(syntax = "synchronize neo4j for base {0}",
help = "synchronize metadata to the Neo4J database for MCRBase {0}",
order = 60)
public static void synchronizeForBase(final String baseId) {
LOGGER.info("Synchronize Neo4J with metadata for MCRBase {}", baseId);
MCRNeo4JManager clazz = MCRConfiguration2.getOrThrow(NEO4J_MANAGER_CLASS_PROPERTY,
MCRConfiguration2::instantiateClass);
List<String> selectedObjectIds = MCRXMLMetadataManager
.instance().listIDsForBase(baseId);
for (String objectId : selectedObjectIds) {
MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(objectId));
clazz.updateNodeByMCRObject(mcrObject);
}
}
@MCRCommand(syntax = "synchronize neo4j for type {0}",
help = "synchronize metadata to the Neo4J database for MCRType {0}",
order = 70)
public static void synchronizeForType(final String type) {
LOGGER.info("Synchronize Neo4J with metadata for MCRType {}", type);
MCRNeo4JManager clazz = MCRConfiguration2.getOrThrow(NEO4J_MANAGER_CLASS_PROPERTY,
MCRConfiguration2::instantiateClass);
List<String> selectedObjectIds = MCRXMLMetadataManager
.instance().listIDsOfType(type);
for (String objectId : selectedObjectIds) {
MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(objectId));
clazz.updateNodeByMCRObject(mcrObject);
}
}
@MCRCommand(syntax = "synchronize neo4j metadata", help = "synchronize all metadata the Neo4J database", order = 80)
public static void synchronizeAll() {
LOGGER.info("Synchronisation of all metadata with the Neo4J database");
MCRNeo4JManager clazz = MCRConfiguration2.getOrThrow(NEO4J_MANAGER_CLASS_PROPERTY,
MCRConfiguration2::instantiateClass);
List<String> selectedObjectIds = MCRXMLMetadataManager
.instance()
.listIDs();
for (String objectId : selectedObjectIds) {
MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(objectId));
clazz.updateNodeByMCRObject(mcrObject);
}
}
@MCRCommand(syntax = "test neo4j connection", help = "test connectivity with the Neo4j database", order = 90)
public static void testConnection() {
LOGGER.info("Test connection to Neo4j Database");
MCRNeo4JDatabaseDriver.getInstance().getDriver();
boolean connected = MCRNeo4JDatabaseDriver.getInstance().testConnectionSettings();
LOGGER.info("Neo4j connected {}", connected);
}
@MCRCommand(syntax = "test neo4j for id {0}",
help = "Prints a Neo4J query statement for testing purpose using MCRID",
order = 90)
public static void test(final String id) {
LOGGER.info("Test Query for Neo4J with metadata for MCRID");
MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(id));
MCRNeo4JParser parser = new MCRNeo4JParser();
String neo4JQuery = parser.createNeo4JQuery(mcrObject);
LOGGER.info(neo4JQuery);
}
}
| 7,573 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JProxyServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/proxy/MCRNeo4JProxyServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.proxy;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.DEFAULT_NEO4J_SERVER_URL;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_CLASSID_CATEGID_SEPARATOR;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants.NEO4J_CONFIG_PREFIX;
import static org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JUtil.getClassificationLabel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson.Neo4JNodeJsonRecord;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson.Neo4JPathJsonRecord;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jtojson.Neo4JRelationShipJsonRecord;
import org.mycore.mcr.neo4j.utils.MCRNeo4JDatabaseDriver;
import org.mycore.mcr.neo4j.utils.MCRNeo4JQueryRunner;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Proxy Servlet for accessing and querying Neo4J
* @author Andreas Kluge (ai112vezo)
*/
public class MCRNeo4JProxyServlet extends MCRServlet {
private static final long serialVersionUID = 1L;
static final Logger LOGGER = LogManager.getLogger(MCRNeo4JProxyServlet.class);
private static final List<String> KEY_LIST = List.of("q", "id", "limit");
private static final String SERVER_URL = MCRConfiguration2.getStringOrThrow(DEFAULT_NEO4J_SERVER_URL);
private final ObjectMapper objectMapper = new ObjectMapper();
public MCRNeo4JProxyServlet() {
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
objectMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true);
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
LOGGER.error(SERVER_URL);
}
@Override
protected void doGetPost(MCRServletJob job) throws Exception {
final HttpServletRequest request = job.getRequest();
final HttpServletResponse response = job.getResponse();
if (request.getParameterMap().keySet().stream().noneMatch(KEY_LIST::contains)) {
LOGGER.info("No valid query parameter {}", request.getParameterMap().keySet());
response.sendError(400, "Query parameter \"id\" or \"q\" must be set.");
return;
}
final String currentLanguage = MCRServlet.getSession(request).getCurrentLanguage();
final String defaultLanguage = MCRConfiguration2.getString("MCR.Metadata.DefaultLang").orElse("de");
final String language = currentLanguage != null ? currentLanguage : defaultLanguage;
final String id = request.getParameter("id");
final String limit = request.getParameter("limit");
final String q = request.getParameter("q");
final StringBuilder queryStringBuilder = new StringBuilder();
String query = q;
if (id != null) {
queryStringBuilder.append("MATCH p=({id:\"");
queryStringBuilder.append(id);
queryStringBuilder.append("\"})-[*0..1]-(m)");
if (limit != null) {
queryStringBuilder.append(" WITH p,m LIMIT ");
queryStringBuilder.append(limit);
}
queryStringBuilder.append(" OPTIONAL MATCH (m)-[r]-() RETURN p,r");
query = queryStringBuilder.toString();
}
MCRNeo4JDatabaseDriver.getInstance().createConnection(SERVER_URL,
MCRConfiguration2.getStringOrThrow(NEO4J_CONFIG_PREFIX + "user"),
MCRConfiguration2.getStringOrThrow(NEO4J_CONFIG_PREFIX + "password"));
final List<Map<String, String>> result = MCRNeo4JQueryRunner.commitReadOnlyQuery(query, language);
if (result == null) {
LOGGER.info("Result is null");
response.sendError(500);
return;
}
String finalResult = transformPath(result, language);
response.setContentType("application/json");
response.getWriter().write(finalResult);
}
private String transformPath(List<Map<String, String>> result, String lang) throws JsonProcessingException {
Set<Neo4JNodeJsonRecord> nodes = new HashSet<>();
Set<Neo4JRelationShipJsonRecord> relationShips = new HashSet<>();
List<String> unprocessed = new ArrayList<>();
for (Map<String, String> resultMap : result) {
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (StringUtils.contains(key, "node_")) {
try {
Neo4JNodeJsonRecord nodeObject = objectMapper.readerFor(Neo4JNodeJsonRecord.class)
.withRootName("n").readValue(value);
nodes.add(nodeObject);
} catch (JsonProcessingException e) {
LOGGER.error(e);
}
} else if (StringUtils.contains(key, "rel_")) {
try {
Neo4JRelationShipJsonRecord relationShipObject = objectMapper
.readerFor(Neo4JRelationShipJsonRecord.class).withRootName("r").readValue(value);
relationShips.add(relationShipObject);
} catch (JsonProcessingException e) {
LOGGER.error(e);
}
} else if (StringUtils.contains(key, "path_")) {
try {
Neo4JPathJsonRecord pathObject = objectMapper.readValue(value, Neo4JPathJsonRecord.class);
nodes.addAll(pathObject.nodes());
relationShips.addAll(pathObject.relationships());
} catch (JsonProcessingException e) {
LOGGER.error(e);
}
} else {
unprocessed.add(value);
}
}
}
return buildPath(lang, nodes, relationShips, unprocessed);
}
private String buildPath(String lang, Set<Neo4JNodeJsonRecord> nodes,
Set<Neo4JRelationShipJsonRecord> relationShips, List<String> unprocessed) throws JsonProcessingException {
StringBuilder relationsBuilder = new StringBuilder();
relationsBuilder.append('[');
for (Neo4JRelationShipJsonRecord relationship : relationShips) {
//translate relation
String type = relationship.type();
try {
if (type.contains(NEO4J_CLASSID_CATEGID_SEPARATOR)) {
String[] sep = type.split(NEO4J_CLASSID_CATEGID_SEPARATOR);
type = getClassificationLabel(sep[0], sep[1], lang);
}
} catch (Exception e) {
LOGGER.error(() -> "Error at relationship " + relationship, e);
}
relationsBuilder.append("{\"from\":\"").append(relationship.startElementId()).append("\",\"to\":\"")
.append(relationship.endElementId()).append("\",\"type\":\"").append(type).append("\"}");
relationsBuilder.append(',');
}
if (relationsBuilder.length() > 1) {
relationsBuilder.deleteCharAt(relationsBuilder.length() - 1);
}
relationsBuilder.append(']');
StringBuilder resultBuilder = new StringBuilder();
String nodesArray = objectMapper.writeValueAsString(nodes);
if (nodes.size() == 1) {
resultBuilder.append("{\"nodes\":[").append(nodesArray).append("],");
} else {
resultBuilder.append("{\"nodes\":").append(nodesArray).append(',');
}
resultBuilder.append("\"relations\":").append(relationsBuilder);
if (!unprocessed.isEmpty()) {
resultBuilder.append(",\"unprocessed\":").append(unprocessed);
}
resultBuilder.append('}');
return resultBuilder.toString();
}
}
| 9,428 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNeo4JIndexEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-neo4j/src/main/java/org/mycore/mcr/neo4j/index/MCRNeo4JIndexEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.mcr.neo4j.index;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.datamodel.common.MCRMarkManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jparser.MCRNeo4JParser;
import org.mycore.mcr.neo4j.datamodel.metadata.neo4jutil.MCRNeo4JConstants;
import org.mycore.mcr.neo4j.utils.MCRNeo4JQueryRunner;
import org.mycore.util.concurrent.MCRDelayedRunnable;
import org.mycore.util.concurrent.MCRTransactionableRunnable;
/**
* Neo4J Event Handler for Indexing
* @author Thomas Scheffler (yagee)
* @author Andreas Kluge
* @author Jens Kupferschmidt
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public class MCRNeo4JIndexEventHandler extends MCREventHandlerBase {
private static final Logger LOGGER = LogManager.getLogger(MCRNeo4JIndexEventHandler.class);
private static final long DELAY_IN_MS = MCRConfiguration2
.getLong(MCRNeo4JConstants.NEO4J_CONFIG_PREFIX + "DelayIndexing_inMS").orElse(2000L);
private static final DelayQueue<MCRDelayedRunnable> NEO4J_TASK_QUEUE = new DelayQueue<>();
private static final ScheduledExecutorService NEO4J_TASK_EXECUTOR = Executors.newSingleThreadScheduledExecutor();
static {
NEO4J_TASK_EXECUTOR.scheduleWithFixedDelay(() -> {
LOGGER.debug("NEO4J Task Executor invoked: {} Nodes to process", NEO4J_TASK_QUEUE.size());
processNeo4JTaskQueue();
}, DELAY_IN_MS * 2, DELAY_IN_MS * 2, TimeUnit.MILLISECONDS);
MCRShutdownHandler.getInstance().addCloseable(new MCRShutdownHandler.Closeable() {
@Override
public int getPriority() {
return Integer.MIN_VALUE + 10;
}
@Override
public void prepareClose() {
NEO4J_TASK_EXECUTOR.shutdown();
try {
NEO4J_TASK_EXECUTOR.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
LOGGER.error("Could not shutdown Neo4J-Indexing", e);
}
if (!NEO4J_TASK_QUEUE.isEmpty()) {
LOGGER.info("There are still {} Neo4J indexing tasks to complete before shutdown",
NEO4J_TASK_QUEUE.size());
processNeo4JTaskQueue();
}
}
@Override
public void close() {
//all work done in prepareClose phase
}
});
}
private final MCRNeo4JParser parser;
public MCRNeo4JIndexEventHandler() {
parser = new MCRNeo4JParser();
}
private static synchronized void putIntoTaskQueue(MCRDelayedRunnable task) {
NEO4J_TASK_QUEUE.remove(task);
NEO4J_TASK_QUEUE.add(task);
}
private static void processNeo4JTaskQueue() {
while (!NEO4J_TASK_QUEUE.isEmpty()) {
try {
MCRDelayedRunnable processingTask = NEO4J_TASK_QUEUE.poll(DELAY_IN_MS, TimeUnit.MILLISECONDS);
if (processingTask != null) {
LOGGER.info("Sending {} to neo4j...", processingTask.getId());
processingTask.run();
}
} catch (InterruptedException e) {
LOGGER.error("Error in neo4j indexing", e);
}
}
}
@Override
protected synchronized void handleObjectCreated(MCREvent evt, MCRObject obj) {
LOGGER.info("Handle {}", obj.getId());
addObject(evt, obj);
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
updateObject(evt, obj);
}
@Override
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
updateObject(evt, obj);
}
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
deleteObject(obj.getId());
}
@Override
protected void handleObjectIndex(MCREvent evt, MCRObject obj) {
handleObjectUpdated(evt, obj);
}
protected synchronized void updateObject(MCREvent evt, MCRObject mcrObject) {
LOGGER.debug("Neo4j: update id {}", mcrObject.getId());
// do not add objects marked for deletion
if (MCRMarkManager.instance().isMarked(mcrObject.getId())) {
return;
}
MCRSessionMgr.getCurrentSession().onCommit(() -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Neo4j: submitting data of {} for indexing", mcrObject.getId());
}
putIntoTaskQueue(new MCRDelayedRunnable(mcrObject.getId().toString(), DELAY_IN_MS,
new MCRTransactionableRunnable(() -> {
try {
String updateQuery = parser.createNeo4JUpdateQuery(mcrObject);
LOGGER.debug("UpdateQuery: {}", updateQuery);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(updateQuery);
String query = parser.createNeo4JQuery(mcrObject);
LOGGER.info("Query: {}", query);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(query);
} catch (Exception e) {
LOGGER.error("Error creating transfer thread for object {}", mcrObject, e);
}
})));
});
}
protected synchronized void addObject(MCREvent evt, MCRObject mcrObject) {
LOGGER.debug("Neo4j: add id {}", mcrObject.getId());
// do not add objects marked for deletion
if (MCRMarkManager.instance().isMarked(mcrObject.getId())) {
return;
}
MCRSessionMgr.getCurrentSession().onCommit(() -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Neo4j: submitting data of {} for indexing", mcrObject.getId());
}
putIntoTaskQueue(new MCRDelayedRunnable(mcrObject.getId().toString(), DELAY_IN_MS,
new MCRTransactionableRunnable(() -> {
try {
String query = parser.createNeo4JQuery(mcrObject);
LOGGER.info("Query: {}", query);
MCRNeo4JQueryRunner.commitWriteOnlyQuery(query);
} catch (Exception e) {
LOGGER.error("Error creating transfer thread for object {}", mcrObject, e);
}
})));
});
}
protected synchronized void deleteObject(MCRObjectID id) {
LOGGER.debug("Neo4j: delete id {}", id);
MCRSessionMgr.getCurrentSession()
.onCommit(() -> putIntoTaskQueue(new MCRDelayedRunnable(id.toString(), DELAY_IN_MS,
new MCRTransactionableRunnable(() -> {
String queryString = "MATCH (n {id:'" + id + "'}) DETACH DELETE n";
MCRNeo4JQueryRunner.commitWriteOnlyQuery(queryString);
}))));
}
}
| 8,182 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/MCRORCIDException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.StatusType;
/**
* Represents the error information returned from ORCID's REST API in case request was not successful
*
* @author Frank Lützenkirchen
*/
public class MCRORCIDException extends IOException {
private static final long serialVersionUID = 1846541932326084816L;
private String message;
public MCRORCIDException(String message) {
super(message);
}
public MCRORCIDException(Response response) throws IOException {
StatusType status = response.getStatusInfo();
String responseBody = response.readEntity(String.class);
StringBuilder sb = new StringBuilder();
if (responseBody.startsWith("{")) {
JsonNode json = new ObjectMapper().readTree(responseBody);
addJSONField(json, "error-code", sb, ": ");
addJSONField(json, "developer-message", sb, "");
addJSONField(json, "error_description", sb, "");
} else {
sb.append(status.getStatusCode()).append(": ").append(status.getReasonPhrase());
}
this.message = sb.toString();
}
private void addJSONField(JsonNode json, String field, StringBuilder sb, String delimiter) {
if (json.has(field)) {
sb.append(json.get(field).asText()).append(delimiter);
}
}
@Override
public String getMessage() {
return message;
}
}
| 2,332 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDConstants.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/MCRORCIDConstants.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Namespace;
import jakarta.ws.rs.core.MediaType;
/**
* Utility class to hold constants and namespace representation used in the XML of the ORCID API.
*
* @author Frank Lützenkirchen
*/
public abstract class MCRORCIDConstants {
public static final MediaType ORCID_XML_MEDIA_TYPE = MediaType.valueOf("application/vnd.orcid+xml");
public static final List<Namespace> NAMESPACES = new ArrayList<>();
public static final Namespace NS_ACTIVITIES = buildNamespace("activities");
public static final Namespace NS_WORK = buildNamespace("work");
private static Namespace buildNamespace(String prefix) {
Namespace namespace = Namespace.getNamespace(prefix, "http://www.orcid.org/ns/" + prefix);
NAMESPACES.add(namespace);
return namespace;
}
}
| 1,615 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDProfile.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/MCRORCIDProfile.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid;
import java.io.IOException;
import org.jdom2.JDOMException;
import org.mycore.orcid.works.MCRWorksFetcher;
import org.mycore.orcid.works.MCRWorksPublisher;
import org.mycore.orcid.works.MCRWorksSection;
import org.xml.sax.SAXException;
import jakarta.ws.rs.client.WebTarget;
/**
* Represents the profile of a given ORCID ID.
*
* @author Frank Lützenkirchen
*/
public class MCRORCIDProfile {
private String orcid;
/** The base target of the REST api for this ORCID profile */
private WebTarget target;
private MCRWorksSection worksSection;
private MCRWorksPublisher publisher = new MCRWorksPublisher(this);
private MCRWorksFetcher fetcher = new MCRWorksFetcher(this);
/** The access token required to modify entries in this ORCID profile */
private String accessToken;
public MCRORCIDProfile(String orcid) {
this.orcid = orcid;
this.target = MCRORCIDClient.instance().getBaseTarget().path(orcid);
}
public String getORCID() {
return orcid;
}
public MCRWorksPublisher getPublisher() {
return publisher;
}
public MCRWorksFetcher getFetcher() {
return fetcher;
}
/** Returns the base web target of the REST API for this ORCID profile */
public WebTarget getWebTarget() {
return target;
}
/** Sets the access token required to modify entries in this ORCID profile */
public void setAccessToken(String token) {
this.accessToken = token;
}
/** Returns the access token required to modify entries in this ORCID profile */
public String getAccessToken() {
return accessToken;
}
/** Returns the "works" section of the ORCID profile, which holds the publication data */
public synchronized MCRWorksSection getWorksSection() throws JDOMException, IOException, SAXException {
if (worksSection == null) {
worksSection = new MCRWorksSection(this);
}
return worksSection;
}
}
| 2,748 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/MCRORCIDClient.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid;
import org.mycore.common.config.MCRConfiguration2;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
/**
* Utility class to work with the REST API of orcid.org.
* By setting MCR.ORCID.BaseURL, application can choose to work
* against the production registry or the sandbox of orcid.org.
*
* @author Frank Lützenkirchen
*/
public class MCRORCIDClient {
private static final MCRORCIDClient SINGLETON = new MCRORCIDClient();
private WebTarget baseTarget;
public static MCRORCIDClient instance() {
return SINGLETON;
}
private MCRORCIDClient() {
String baseURL = MCRConfiguration2.getStringOrThrow("MCR.ORCID.BaseURL");
Client client = ClientBuilder.newClient();
baseTarget = client.target(baseURL);
}
public WebTarget getBaseTarget() {
return baseTarget;
}
}
| 1,663 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROAuthServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCROAuthServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import org.mycore.orcid.user.MCRORCIDSession;
import org.mycore.orcid.user.MCRORCIDUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletResponse;
/**
* Implements ORCID OAuth2 authorization.
*
* User should invoke MCROAuthServlet without any parameters.
* The servlet will redirect the user to orcid.org authorization.
* The user will login at orcid.org and accept or deny this application as trusted party
* for the activity scopes defined in MCR.ORCID.OAuth.Scopes.
* orcid.org then redirects the user's browser to this servlet again.
* If the scopes were accepted by user, the response contains a code parameter.
* This code is exchanged for an access token and stored in the user's attributes here.
*
* See https://members.orcid.org/api/oauth/3legged-oauth
*
* @author Frank Lützenkirchen
*/
public class MCROAuthServlet extends MCRServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(MCROAuthServlet.class);
private String scopes = MCRConfiguration2.getStringOrThrow("MCR.ORCID.OAuth.Scopes");
private String userServlet = MCRConfiguration2.getStringOrThrow("MCR.ORCID.OAuth.User.Servlet");
private String redirectURL;
@Override
protected void doGetPost(MCRServletJob job) throws Exception {
String baseURL = MCRFrontendUtil.getBaseURL();
this.redirectURL = baseURL + job.getRequest().getServletPath().substring(1);
String userProfileURL = MCRServlet.getServletBaseURL() + userServlet;
String code = job.getRequest().getParameter("code");
String error = job.getRequest().getParameter("error");
if ((error != null) && !error.trim().isEmpty()) {
job.getResponse().sendRedirect(userProfileURL + "&XSL.error=" + error);
} else if ((code == null) || code.trim().isEmpty()) {
redirectToGetAuthorization(job);
} else {
String state = job.getRequest().getParameter("state");
if (!MCROAuthClient.buildStateParam().equals(state)) {
String msg = "Invalid state, possibly cross-site request forgery?";
job.getResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
}
MCRTokenResponse token = exchangeCodeForAccessToken(code);
MCRORCIDUser orcidUser = MCRORCIDSession.getCurrentUser();
orcidUser.store(token);
orcidUser.getProfile().getWorksSection();
job.getResponse().sendRedirect(userProfileURL);
}
}
private void redirectToGetAuthorization(MCRServletJob job)
throws URISyntaxException, IOException {
String url = MCROAuthClient.instance().getCodeRequestURL(redirectURL, scopes);
job.getResponse().sendRedirect(url);
}
private MCRTokenResponse exchangeCodeForAccessToken(String code)
throws JsonProcessingException, IOException {
MCRTokenRequest request = MCROAuthClient.instance().getTokenRequest();
request.set("grant_type", "authorization_code");
request.set("code", code);
request.set("redirect_uri", redirectURL);
MCRTokenResponse token = request.post();
LOGGER.info("access granted for " + token.getORCID() + " " + token.getAccessToken());
return token;
}
}
| 4,478 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROAuthClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCROAuthClient.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;
import org.apache.http.client.utils.URIBuilder;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.streams.MCRMD5InputStream;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserManager;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
/**
* Utility class working as a client for the OAuth2 API of orcid.org.
* Used to get access tokens. Minimum configuration requires to set
*
* MCR.ORCID.OAuth.BaseURL
* MCR.ORCID.OAuth.ClientID
* MCR.ORCID.OAuth.ClientSecret
*
* @author Frank Lützenkirchen
*/
public class MCROAuthClient {
private static MCROAuthClient SINGLETON = new MCROAuthClient();
private String baseURL;
private String clientID;
private String clientSecret;
private Client client;
public static MCROAuthClient instance() {
return SINGLETON;
}
private MCROAuthClient() {
String prefix = "MCR.ORCID.OAuth.";
baseURL = MCRConfiguration2.getStringOrThrow(prefix + "BaseURL");
clientID = MCRConfiguration2.getStringOrThrow(prefix + "ClientID");
clientSecret = MCRConfiguration2.getStringOrThrow(prefix + "ClientSecret");
client = ClientBuilder.newClient();
}
public String getClientID() {
return clientID;
}
/**
* Builds am OAuth2 token request.
*/
public MCRTokenRequest getTokenRequest() {
MCRTokenRequest req = new MCRTokenRequest(client.target(baseURL));
req.set("client_id", clientID);
req.set("client_secret", clientSecret);
return req;
}
public MCRRevokeRequest getRevokeRequest(String token) {
MCRRevokeRequest req = new MCRRevokeRequest(client.target(baseURL));
req.set("client_id", clientID);
req.set("client_secret", clientSecret);
req.set("token", token);
return req;
}
/**
* Builds the URL where to redirect the user's browser to initiate a three-way authorization
* and request permission to access the given scopes. If
*
* MCR.ORCID.PreFillRegistrationForm=true
*
* submits the current user's E-Mail address, first and last name to the ORCID registration form
* to simplify registration. May be disabled for more data privacy.
*
* @param redirectURL The URL to redirect back to after the user has granted permission
* @param scopes the scope(s) to request permission for, if multiple separate by blanks
*/
String getCodeRequestURL(String redirectURL, String scopes) throws URISyntaxException, MalformedURLException {
URIBuilder builder = new URIBuilder(baseURL + "/authorize");
builder.addParameter("client_id", clientID);
builder.addParameter("response_type", "code");
builder.addParameter("redirect_uri", redirectURL);
builder.addParameter("scope", scopes.trim());
builder.addParameter("state", buildStateParam());
builder.addParameter("prompt", "login");
// check if current lang is supported
List<String> supportedLanguages = Arrays
.asList(MCRConfiguration2.getStringOrThrow("MCR.ORCID.SupportedLanguages").split(",", 0));
if (supportedLanguages.contains(MCRSessionMgr.getCurrentSession().getCurrentLanguage())) {
builder.addParameter("lang", MCRSessionMgr.getCurrentSession().getCurrentLanguage());
} else {
builder.addParameter("lang", "en");
}
if (MCRConfiguration2.getOrThrow("MCR.ORCID.PreFillRegistrationForm", Boolean::parseBoolean)) {
preFillRegistrationForm(builder);
}
return builder.build().toURL().toExternalForm();
}
/**
* If
*
* MCR.ORCID.PreFillRegistrationForm=true
*
* submits the current user's E-Mail address, first and last name to the ORCID registration form
* to simplify registration. May be disabled for more data privacy.
*
* See https://members.orcid.org/api/resources/customize
*/
private void preFillRegistrationForm(URIBuilder builder) {
MCRUser user = MCRUserManager.getCurrentUser();
String eMail = user.getEMailAddress();
if (eMail != null) {
builder.addParameter("email", eMail);
}
String name = user.getRealName();
String firstName = null;
String lastName = name;
if (name.contains(",")) {
String[] nameParts = name.split(",");
if (nameParts.length == 2) {
firstName = nameParts[1].trim();
lastName = nameParts[0].trim();
}
} else if (name.contains(" ")) {
String[] nameParts = name.split(" ");
if (nameParts.length == 2) {
firstName = nameParts[0].trim();
lastName = nameParts[1].trim();
}
}
if (firstName != null) {
builder.addParameter("given_names", firstName);
}
if (lastName != null) {
builder.addParameter("family_names", lastName);
}
}
/**
* Builds a state parameter to be used with OAuth to defend against cross-site request forgery.
* Comparing state ensures the user is still the same that initiated the authorization process.
*/
static String buildStateParam() {
String userID = MCRUserManager.getCurrentUser().getUserID();
byte[] bytes = userID.getBytes(StandardCharsets.UTF_8);
MessageDigest md5Digest = MCRMD5InputStream.buildMD5Digest();
md5Digest.update(bytes);
byte[] digest = md5Digest.digest();
return MCRMD5InputStream.getMD5String(digest);
}
}
| 6,689 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDResponse.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCRORCIDResponse.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status.Family;
import jakarta.ws.rs.core.Response.StatusType;
/**
* Represents the response on a request against the OAuth2 API of orcid.org.
*
* @author Frank Lützenkirchen
* @author Kai Brandhorst
*/
public class MCRORCIDResponse {
private StatusType status;
protected JsonNode responseData;
MCRORCIDResponse(Response response) throws IOException {
this.status = response.getStatusInfo();
String jsonTree = response.readEntity(String.class);
ObjectMapper objectMapper = new ObjectMapper();
responseData = objectMapper.readTree(jsonTree);
}
public boolean wasSuccessful() {
return status.getFamily() == Family.SUCCESSFUL;
}
public String getStatusMessage() {
StringBuilder b = new StringBuilder();
b.append(status.getStatusCode()).append(' ').append(status.getReasonPhrase());
if (!wasSuccessful()) {
b.append(", ").append(responseData.get("error").asText());
b.append(": ").append(responseData.get("error_description").asText());
}
return b.toString();
}
/**
* Returns the ORCID given in the response, if any
*/
public String getORCID() {
return responseData.get("orcid").asText();
}
}
| 2,229 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTokenRequest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCRTokenRequest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.io.IOException;
import org.mycore.common.config.MCRConfigurationException;
import jakarta.ws.rs.client.WebTarget;
/**
* Represents a token request against the OAuth2 API of orcid.org.
*
* @author Frank Lützenkirchen
* @author Kai Brandhorst
*/
class MCRTokenRequest extends MCRORCIDRequest {
MCRTokenRequest(WebTarget baseTarget) {
super(baseTarget);
}
/**
* Posts the request and returns the response.
*
* @throws MCRConfigurationException if request fails, e.g. because of misconfigured client ID and secret
*/
public MCRTokenResponse post() throws MCRConfigurationException, IOException {
MCRTokenResponse response = new MCRTokenResponse(post("token"));
if (!response.wasSuccessful()) {
throw new MCRConfigurationException(response.getStatusMessage());
}
return response;
}
}
| 1,654 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDRequest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCRORCIDRequest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import org.mycore.common.config.MCRConfigurationException;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation.Builder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Form;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
/**
* Represents a request against the OAuth2 API of orcid.org.
*
* @author Frank Lützenkirchen
* @author Kai Brandhorst
*/
class MCRORCIDRequest {
private Form form = new Form();
private WebTarget baseTarget;
MCRORCIDRequest(WebTarget baseTarget) {
this.baseTarget = baseTarget;
}
void set(String name, String value) {
form.param(name, value);
}
/**
* Posts the request and returns the response.
*
* @throws MCRConfigurationException if request fails, e.g. because of misconfigured client ID and secret
*/
public Response post(String path) throws MCRConfigurationException {
Entity<Form> formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
WebTarget target = baseTarget.path(path);
Builder b = target.request().accept(MediaType.APPLICATION_JSON);
Response r = b.post(formEntity);
return r;
}
}
| 1,994 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRReadPublicTokenFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCRReadPublicTokenFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
/**
* Returns the read-public access token to read public data from ORCID.org.
* A token is needed for access to the public API, see
* https://members.orcid.org/api/tutorial/read-orcid-records#readpub
*
* The token can be configured via MCR.ORCID.OAuth.ReadPublicToken.
* In case that is not set, the token is directly requested from the OAuth2 API and logged.
*
* @author Frank Lützenkirchen *
*/
public class MCRReadPublicTokenFactory {
private static final Logger LOGGER = LogManager.getLogger(MCRReadPublicTokenFactory.class);
private static final String CONFIG_PROPERTY = "MCR.ORCID.OAuth.ReadPublicToken";
private static String token = MCRConfiguration2.getString(CONFIG_PROPERTY).orElse(null);
/**
* Returns the read-public access token
*/
public static String getToken() {
if ((token == null) || token.isEmpty()) {
requestToken();
}
return token;
}
/**
* Requests the token from the OAuth2 API of ORCID.org.
* Logs a warning, so you better check your logs and directly configure
* MCR.ORCID.OAuth.ReadPublicToken
*/
private static void requestToken() {
LOGGER.info("requesting read-public access token...");
MCRTokenRequest request = MCROAuthClient.instance().getTokenRequest();
request.set("grant_type", "client_credentials");
request.set("scope", "/read-public");
try {
MCRTokenResponse response = request.post();
token = response.getAccessToken();
} catch (IOException ex) {
String msg = "Could not get read-public access token from ORCID OAuth API";
throw new MCRConfigurationException(msg, ex);
}
LOGGER.warn("You should set the access token in mycore.properties:");
LOGGER.warn(CONFIG_PROPERTY + "={}", token);
}
}
| 2,853 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRevokeRequest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCRRevokeRequest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.io.IOException;
import org.mycore.common.config.MCRConfigurationException;
import jakarta.ws.rs.client.WebTarget;
/**
* Represents a token request against the OAuth2 API of orcid.org.
*
* @author Frank Lützenkirchen
* @author Kai Brandhorst
*/
public class MCRRevokeRequest extends MCRORCIDRequest {
MCRRevokeRequest(WebTarget baseTarget) {
super(baseTarget);
}
/**
* Posts the request and returns the response.
*
* @throws MCRConfigurationException if request fails, e.g. because of misconfigured client ID and secret
*/
public MCRRevokeResponse post() throws MCRConfigurationException, IOException {
MCRRevokeResponse response = new MCRRevokeResponse(post("revoke"));
if (!response.wasSuccessful()) {
throw new MCRConfigurationException(response.getStatusMessage());
}
return response;
}
}
| 1,667 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRevokeResponse.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCRRevokeResponse.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.io.IOException;
import jakarta.ws.rs.core.Response;
/**
* Represents the response on a token request against the OAuth2 API of orcid.org.
*
* @author Frank Lützenkirchen
* @author Kai Brandhorst
*/
public class MCRRevokeResponse extends MCRORCIDResponse {
MCRRevokeResponse(Response response) throws IOException {
super(response);
}
}
| 1,132 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTokenResponse.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/oauth/MCRTokenResponse.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.oauth;
import java.io.IOException;
import jakarta.ws.rs.core.Response;
/**
* Represents the response on a token request against the OAuth2 API of orcid.org.
*
* @author Frank Lützenkirchen
* @author Kai Brandhorst
*/
public class MCRTokenResponse extends MCRORCIDResponse {
MCRTokenResponse(Response response) throws IOException {
super(response);
}
/**
* Returns the access token, in case the request wasSuccessful()
*/
public String getAccessToken() {
return responseData.get("access_token").asText();
}
}
| 1,317 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGroupOfWorks.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/works/MCRGroupOfWorks.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.works;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Element;
import org.mycore.mods.merger.MCRMergeTool;
/**
* Represents a group of works as the activities:group element returned in the ORCID response to fetch work summaries.
* ORCID groups multiple works from different sources that are assumed to represent the same publication.
*
* @author Frank Lützenkirchen
*/
public class MCRGroupOfWorks {
private List<MCRWork> works = new ArrayList<>();
void add(MCRWork work) {
works.add(work);
}
/**
* Returns the works grouped together here.
* All these work entries are assumed to represent the same publication, but from different sources.
*/
public List<MCRWork> getWorks() {
return works;
}
/**
* Returns a single mods:mods representation of the publication represented by this group.
* The MODS from each is merged together.
*/
public Element buildMergedMODS() {
Element mods = works.get(0).getMODS().clone();
for (int i = 1; i < works.size(); i++) {
MCRMergeTool.merge(mods, works.get(i).getMODS());
}
return mods;
}
public List<Element> buildUnmergedMODS() {
List<Element> modslist = new ArrayList<>();
for (MCRWork work : works) {
modslist.add(work.getMODS().detach());
}
return modslist;
}
}
| 2,164 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWork.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/works/MCRWork.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.works;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.MCRConstants;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.orcid.MCRORCIDException;
import org.mycore.orcid.MCRORCIDProfile;
import org.xml.sax.SAXException;
/**
* Represents a single "work", that means a publication within the "works" section of an ORCID profile,
* from a single source.
*
* @author Frank Lützenkirchen
*/
public class MCRWork {
private MCRORCIDProfile orcid;
private String putCode;
private Element mods;
private MCRWorkSource source;
MCRWork(MCRORCIDProfile orcid, String putCode) {
this.orcid = orcid;
this.putCode = putCode;
}
/**
* Returns the put code, which is the unique identifier of this work within the ORCID profile
*/
public String getPutCode() {
return putCode;
}
/**
* Returns the client application that created this work entry.
*/
public MCRWorkSource getSource() {
return source;
}
void setSource(MCRWorkSource source) {
this.source = source;
}
/**
* Returns the MODS representation of the work's publication data
*/
public Element getMODS() {
return mods;
}
void setMODS(Element mods) {
this.mods = mods;
}
/**
* Returns all mods:identifier elements of this work.
*/
public List<Element> getIdentifiers() {
List<Element> identifiers = getMODS().getChildren("identifier", MCRConstants.MODS_NAMESPACE);
return Collections.unmodifiableList(identifiers);
}
/**
* Fetches the work's details with the complete publication data from the ORCID profile.
* Initially, only the work summary was fetched.
*/
public void fetchDetails() throws JDOMException, IOException {
orcid.getFetcher().fetchDetails(this);
}
/**
* If this work's source is this MyCoRe application,
* updates the work in the remote ORCID profile from the local MyCoRe object
*/
public void update(MCRObjectID objectID) throws IOException, JDOMException {
if (!source.isThisApplication()) {
throw new MCRORCIDException("can not update that work, is not from us");
}
if (!MCRMetadataManager.exists(objectID)) {
throw new MCRORCIDException("can not update that work, object " + objectID + " does not exist locally");
}
orcid.getPublisher().update(this, objectID);
}
/** Deletes this work from the remote ORCID profile */
public void delete() throws IOException, JDOMException, SAXException {
if (!source.isThisApplication()) {
throw new MCRORCIDException("can not delete that work, is not from us");
}
orcid.getPublisher().delete(this);
}
}
| 3,732 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorkEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/works/MCRWorkEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.works;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mods.MCRMODSWrapper;
import org.mycore.orcid.user.MCRORCIDUser;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserManager;
/**
* When a publication is created or updated locally in this application,
* collects all name identifiers from the MODS metadata,
* looks up login users that have one of these identifiers, e.g. ORCID iD,
* stored in their user attributes,
* checks if these users have an ORCID profile we know of
* and have authorized us to update their profile as trusted party,
* and then creates/updates the publication in the works section of that profile.
*
* @author Frank Lützenkirchen
*/
public class MCRWorkEventHandler extends MCREventHandlerBase {
private static final Logger LOGGER = LogManager.getLogger(MCRWorkEventHandler.class);
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject object) {
handlePublication(object);
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject object) {
handlePublication(object);
}
private void handlePublication(MCRObject object) {
if (!MCRMODSWrapper.isSupported(object)) {
return;
}
MCRMODSWrapper wrapper = new MCRMODSWrapper(object);
MCRObjectID oid = object.getId();
Set<String> nameIdentifierKeys = MCRORCIDUser.getNameIdentifierKeys(wrapper);
Set<MCRUser> users = getUsersForGivenNameIdentifiers(nameIdentifierKeys);
users.stream()
.map(MCRORCIDUser::new)
.filter(user -> user.getStatus().isORCIDUser())
.filter(user -> user.getStatus().weAreTrustedParty())
.forEach(user -> publishToORCID(oid, user));
}
protected void publishToORCID(MCRObjectID oid, MCRORCIDUser user) {
try {
MCRWorksSection works = user.getProfile().getWorksSection();
Optional<MCRWork> work = works.findWork(oid);
if (work.isPresent()) {
work.get().update(oid);
} else {
works.addWorkFrom(oid);
}
} catch (Exception ex) {
LOGGER.warn("Could not publish {} in ORCID profile {} of user {}", oid,
user.getORCID(), user.getUser().getUserName(), ex);
}
}
private Set<MCRUser> getUsersForGivenNameIdentifiers(Set<String> nameIdentifierKeys) {
Set<MCRUser> users = new HashSet<>();
for (String key : nameIdentifierKeys) {
String name = MCRORCIDUser.ATTR_ID_PREFIX + key.split(":")[0];
String value = key.split(":")[1];
users.addAll(MCRUserManager.getUsers(name, value).collect(Collectors.toSet()));
}
return users;
}
}
| 3,880 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorksFetcher.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/works/MCRWorksFetcher.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.works;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.MCRConstants;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.common.content.MCRStringContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRContentTransformerFactory;
import org.mycore.mods.merger.MCRMergeTool;
import org.mycore.orcid.MCRORCIDConstants;
import org.mycore.orcid.MCRORCIDProfile;
import org.mycore.orcid.oauth.MCRReadPublicTokenFactory;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
/**
* Provides functionality to fetch work groups, work summaries and work details
* from a remote ORCID profile
*
* @author Frank Lützenkirchen
*/
public class MCRWorksFetcher {
private static final Logger LOGGER = LogManager.getLogger(MCRWorksFetcher.class);
/** The maximum number of works to fetch at once in a bulk request */
private static final int BULK_FETCH_SIZE = MCRConfiguration2
.getOrThrow("MCR.ORCID.Works.BulkFetchSize", Integer::parseInt);
/** Transformer used to convert ORCID's work XML schema to MODS and a representation we use here */
private static final MCRContentTransformer T_WORK2MCR = MCRContentTransformerFactory.getTransformer("Work2MyCoRe");
/** Transformer used to parse bibTeX to MODS */
private static final MCRContentTransformer T_BIBTEX2MODS = MCRContentTransformerFactory
.getTransformer("BibTeX2MODS");
private MCRORCIDProfile orcid;
public MCRWorksFetcher(MCRORCIDProfile orcid) {
this.orcid = orcid;
}
List<MCRGroupOfWorks> fetchGroups(MCRWorksSection worksSection) throws JDOMException, IOException {
WebTarget target = orcid.getWebTarget().path("works");
Element worksXML = fetchWorksXML(target);
List<MCRGroupOfWorks> groups = new ArrayList<>();
for (Element groupXML : worksXML.getChildren("group", MCRORCIDConstants.NS_ACTIVITIES)) {
MCRGroupOfWorks group = new MCRGroupOfWorks();
groups.add(group);
for (Element workSummary : groupXML.getChildren("work-summary", MCRORCIDConstants.NS_WORK)) {
String putCode = workSummary.getAttributeValue("put-code");
MCRWork work = worksSection.getWork(putCode);
if (work == null) {
work = new MCRWork(orcid, putCode);
setFromWorkXML(work, workSummary);
}
group.add(work);
}
}
return groups;
}
void fetchDetails(MCRWorksSection worksSection) throws IOException, JDOMException {
List<String> putCodes = new ArrayList<>();
worksSection.getWorks().forEach(work -> putCodes.add(work.getPutCode()));
for (int offset = 0; offset < putCodes.size(); offset += BULK_FETCH_SIZE) {
int chunkEndIndex = Math.min(offset + BULK_FETCH_SIZE, putCodes.size());
String joinedPutCodes = StringUtils.join(putCodes.subList(offset, chunkEndIndex), ',');
WebTarget target = orcid.getWebTarget().path("works").path(joinedPutCodes);
Element bulk = fetchWorksXML(target);
for (Element workXML : bulk.getChildren("work", MCRORCIDConstants.NS_WORK)) {
String putCode = workXML.getAttributeValue("put-code");
workXML.setAttribute("path", "/" + orcid.getORCID() + "/work/" + putCode);
MCRWork work = worksSection.getWork(putCode);
setFromWorkXML(work, workXML);
}
}
}
void fetchDetails(MCRWork work) throws JDOMException, IOException {
WebTarget target = orcid.getWebTarget().path("work").path(work.getPutCode());
Element workXML = fetchWorksXML(target);
setFromWorkXML(work, workXML);
}
private Element fetchWorksXML(WebTarget target) throws JDOMException, IOException {
Response r = getResponse(target, orcid.getAccessToken() != null);
MCRContent response = new MCRStreamContent(r.readEntity(InputStream.class));
MCRContent transformed = T_WORK2MCR.transform(response);
return transformed.asXML().detachRootElement();
}
private Response getResponse(WebTarget target, boolean usePersonalToken) {
LOGGER.info("get {}", target.getUri());
Response r = target.request().accept(MCRORCIDConstants.ORCID_XML_MEDIA_TYPE)
.header("Authorization",
"Bearer " + (usePersonalToken ? orcid.getAccessToken() : MCRReadPublicTokenFactory.getToken()))
.get();
if (r.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
return r;
} else if (!usePersonalToken) {
LOGGER.warn("Bad request with public ORDiD token. "
+ "Please check respective setting in mycore.properties.");
return r;
} else {
LOGGER.info("Bad request with personal ORCiD token. Using public token instead.");
return getResponse(target, false);
}
}
/** Sets the work's properties from the pre-processed, transformed works XML */
private void setFromWorkXML(MCRWork work, Element workXML) {
Element mods = workXML.getChild("mods", MCRConstants.MODS_NAMESPACE).detach();
String bibTeX = workXML.getChildTextTrim("bibTeX");
Optional<Element> modsFromBibTeX = bibTeX2MODS(bibTeX);
modsFromBibTeX.ifPresent(m -> MCRMergeTool.merge(mods, m));
work.setMODS(mods);
String sourceID = workXML.getAttributeValue("source");
work.setSource(MCRWorkSource.getInstance(sourceID));
}
/**
* Parses the bibTeX code that may be included in the work entry
* and returns its transformation to MODS
*/
private Optional<Element> bibTeX2MODS(String bibTeX) {
if ((bibTeX != null) && !bibTeX.isEmpty()) {
try {
MCRContent result = T_BIBTEX2MODS.transform(new MCRStringContent(bibTeX));
Element modsCollection = result.asXML().getRootElement();
Element modsFromBibTeX = modsCollection.getChild("mods", MCRConstants.MODS_NAMESPACE);
// Remove mods:extension containing the original BibTeX:
modsFromBibTeX.removeChildren("extension", MCRConstants.MODS_NAMESPACE);
return Optional.of(modsFromBibTeX);
} catch (Exception ex) {
String msg = "Exception parsing BibTeX: " + bibTeX;
LOGGER.warn("{} {}", msg, ex.getMessage());
}
}
return Optional.empty();
}
}
| 7,780 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorksSection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/works/MCRWorksSection.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.works;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.MCRConstants;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mods.MCRMODSWrapper;
import org.mycore.orcid.MCRORCIDException;
import org.mycore.orcid.MCRORCIDProfile;
import org.xml.sax.SAXException;
/**
* Represents the "works" section of an ORCID profile with grouped works
*
* @author Frank Lützenkirchen
*/
public class MCRWorksSection {
private MCRORCIDProfile orcid;
/** The groups of works this ORCID profile contains */
private List<MCRGroupOfWorks> groups = new ArrayList<>();
/** All works (not grouped) */
private List<MCRWork> works = new ArrayList<>();
/** Lookup table to get work by it's put code */
private Map<String, MCRWork> putCode2Work = new HashMap<>();
/**
* Creates a representation of the ORCID's works section and
* fetches the grouping of works and the work summaries
*/
public MCRWorksSection(MCRORCIDProfile orcid) throws JDOMException, IOException, SAXException {
this.orcid = orcid;
refetchGroupsAndSummaries();
}
public MCRORCIDProfile getORCID() {
return orcid;
}
public List<MCRWork> getWorks() {
return new ArrayList<>(works);
}
void addWork(MCRWork work) {
works.add(work);
putCode2Work.put(work.getPutCode(), work);
}
void removeWork(MCRWork work) {
works.remove(work);
putCode2Work.remove(work.getPutCode());
}
/** Returns the work with the given put code, if any */
public MCRWork getWork(String putCode) {
return putCode2Work.get(putCode);
}
/**
* Returns the list of grouped works after fetching work summaries.
* Multiple works from different sources which are assumed to represent the same publication
* are grouped together by ORCID.
*/
public List<MCRGroupOfWorks> getGroups() {
return groups;
}
/**
* Returns a mods:modsCollection containing all MODS representations of the works.
* The MODS from multiple works within the same groups is merged together,
* so for each group of works there will be a single mods within the collection.
*/
public Element buildMODSCollection() {
Element modsCollection = new Element("modsCollection", MCRConstants.MODS_NAMESPACE);
groups.forEach(g -> modsCollection.addContent(g.buildMergedMODS()));
return modsCollection;
}
public Element buildUnmergedMODSCollection() {
Element modsCollection = new Element("modsCollection", MCRConstants.MODS_NAMESPACE);
groups.forEach(g -> modsCollection.addContent(g.buildUnmergedMODS()));
return modsCollection;
}
/**
* Fetches the grouping of works and all work summaries from the ORCID profile.
* Can be called to refresh information on grouping to find out how grouping of works
* may have changed after adding or deleting works.
*/
public void refetchGroupsAndSummaries() throws JDOMException, IOException {
groups = orcid.getFetcher().fetchGroups(this);
// Now, rebuild putCode2Work and works list from groups list:
putCode2Work.clear();
works.clear();
groups.stream().flatMap(g -> g.getWorks().stream()).forEach(work -> {
putCode2Work.put(work.getPutCode(), work);
works.add(work);
});
}
/** Fetches the work details for all work summaries from the ORCID profile. */
public void fetchDetails() throws IOException, JDOMException {
orcid.getFetcher().fetchDetails(this);
}
/**
* Adds a new "work" to the remote ORCID profile.
* The publication data is taken from the MODS stored in the MyCoRe object with the given ID.
*/
public MCRWork addWorkFrom(MCRObjectID objectID) throws IOException, JDOMException, SAXException {
if (!MCRMetadataManager.exists(objectID)) {
throw new MCRORCIDException("can not create work, object " + objectID + " does not exist locally");
}
MCRWork work = orcid.getPublisher().createWorkFrom(objectID);
this.addWork(work);
return work;
}
/**
* Returns the work originating from the given local object, if any.
* This is done by comparing the ID and all mods:identifier elements given in the MyCoRe MODS object
* with the identifiers given in the ORCID work.
*/
public Optional<MCRWork> findWork(MCRObjectID oid) {
MCRObject obj = MCRMetadataManager.retrieveMCRObject(oid);
return findWork(obj);
}
public Optional<MCRWork> findWork(MCRObject obj) {
return findWorks(obj).findFirst();
}
public Optional<MCRWork> findOwnWork(MCRObjectID oid) {
MCRObject obj = MCRMetadataManager.retrieveMCRObject(oid);
return findOwnWork(obj);
}
public Optional<MCRWork> findOwnWork(MCRObject obj) {
return findWorks(obj).filter(work -> work.getSource().isThisApplication()).findFirst();
}
public Stream<MCRWork> findWorks(MCRObject obj) {
MCRMODSWrapper wrapper = new MCRMODSWrapper(obj);
List<Element> objectIdentifiers = wrapper.getElements("mods:identifier");
Set<String> objectKeys = buildIdentifierKeys(objectIdentifiers);
return works.stream().filter(work -> matches(work, objectKeys));
}
private boolean matches(MCRWork work, Set<String> objectIdentifiers) {
Set<String> workIdentifiers = buildIdentifierKeys(work.getIdentifiers());
workIdentifiers.retainAll(objectIdentifiers);
return !workIdentifiers.isEmpty();
}
private Set<String> buildIdentifierKeys(List<Element> modsIdentifiers) {
Set<String> objectKeys = new HashSet<>();
for (Element modsIdentifier : modsIdentifiers) {
objectKeys.add(buildIdentifierKey(modsIdentifier));
}
return objectKeys;
}
private String buildIdentifierKey(Element modsIdentifier) {
return modsIdentifier.getAttributeValue("type") + ":" + modsIdentifier.getTextTrim();
}
/** Returns true, if there is a work in the ORCID profile that's origin is the given MyCoRe object */
public boolean containsWork(MCRObjectID oid) {
return findWork(oid).isPresent();
}
public boolean containsOwnWork(MCRObjectID oid) {
return findOwnWork(oid).isPresent();
}
/** Returns all works in the ORCID profile that have been added by ths MyCoRe application */
public Stream<MCRWork> getWorksFromThisApplication() {
return works.stream().filter(work -> work.getSource().isThisApplication());
}
}
| 7,781 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorksPublisher.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/works/MCRWorksPublisher.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.works;
import java.io.IOException;
import java.io.InputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRContentTransformerFactory;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.orcid.MCRORCIDConstants;
import org.mycore.orcid.MCRORCIDException;
import org.mycore.orcid.MCRORCIDProfile;
import org.xml.sax.SAXException;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.client.Invocation.Builder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.StatusType;
/**
* Provides functionality to create, update and delete works in the remote ORCID profile
*
* @author Frank Lützenkirchen
*/
public class MCRWorksPublisher {
private static final Logger LOGGER = LogManager.getLogger(MCRWorksPublisher.class);
/** Transformer used to transform a MyCoRe object with MODS to ORCID's work XML schema */
private static final MCRContentTransformer T_MCR2WORK = MCRContentTransformerFactory.getTransformer("MyCoRe2Work");
private MCRORCIDProfile orcid;
public MCRWorksPublisher(MCRORCIDProfile orcid) {
this.orcid = orcid;
}
/** Publishes the object (its MODS) as a new "work" in the ORCID profile */
MCRWork createWorkFrom(MCRObjectID objectID)
throws IOException, JDOMException, SAXException {
WebTarget target = orcid.getWebTarget().path("work");
Builder builder = buildInvocation(target);
Document workXML = buildWorkXMLFrom(objectID);
Entity<InputStream> input = buildRequestEntity(workXML);
LOGGER.info("post (create) {} at {}", objectID, target.getUri());
Response response = builder.post(input);
expect(response, Response.Status.CREATED);
String putCode = getPutCode(response);
MCRWork work = new MCRWork(orcid, putCode);
work.fetchDetails();
return work;
}
void update(MCRWork work, MCRObjectID oid) throws IOException, JDOMException {
WebTarget target = orcid.getWebTarget().path("work").path(work.getPutCode());
Builder builder = buildInvocation(target);
Document workXML = buildWorkXMLFrom(oid);
workXML.getRootElement().setAttribute("put-code", work.getPutCode());
Entity<InputStream> input = buildRequestEntity(workXML);
LOGGER.info("put (update) {} to {}", oid, target.getUri());
Response response = builder.put(input);
expect(response, Response.Status.OK);
}
void delete(MCRWork work) throws IOException, JDOMException, SAXException {
WebTarget target = orcid.getWebTarget().path("work").path(work.getPutCode());
Builder builder = buildInvocation(target);
Response response = builder.delete();
expect(response, Response.Status.NO_CONTENT);
orcid.getWorksSection().removeWork(work);
}
private Builder buildInvocation(WebTarget target) {
return target.request().accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + orcid.getAccessToken());
}
/** Retrieves the MyCoRe object, transforms it to ORCID work xml and validates */
private Document buildWorkXMLFrom(MCRObjectID objectID) throws IOException, JDOMException {
MCRContent mcrObject = MCRXMLMetadataManager.instance().retrieveContent(objectID);
MCRContent workXML = T_MCR2WORK.transform(mcrObject);
return MCRXMLParserFactory.getValidatingParser().parseXML(workXML);
}
private Entity<InputStream> buildRequestEntity(Document workXML) throws IOException {
InputStream in = new MCRJDOMContent(workXML).getInputStream();
return Entity.entity(in, MCRORCIDConstants.ORCID_XML_MEDIA_TYPE);
}
/** Returns the put code given in the response header after a successful POST of new work */
private String getPutCode(Response response) {
String location = response.getHeaders().getFirst("Location").toString();
return location.substring(location.lastIndexOf('/') + 1);
}
/**
* If the response is not as expected and the request was not successful,
* throws an exception with detailed error message from the ORCID REST API.
*
* @param response the response to the REST request
* @param expectedStatus the status expected when request is successful
* @throws MCRORCIDException if the ORCID API returned error information
*/
private void expect(Response response, Response.Status expectedStatus)
throws IOException {
StatusType status = response.getStatusInfo();
if (status.getStatusCode() != expectedStatus.getStatusCode()) {
throw new MCRORCIDException(response);
}
}
}
| 5,921 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorkSource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/works/MCRWorkSource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.works;
import java.util.HashMap;
import java.util.Map;
import org.mycore.orcid.oauth.MCROAuthClient;
/**
* Represents the source application that generated the work entry in the ORCID profile.
* This may be another ORCID, another client application or THIS, our MyCoRe application.
*
* @author Frank Lützenkirchen *
*/
public class MCRWorkSource {
private static Map<String, MCRWorkSource> sources = new HashMap<>();
private String sourceID;
static MCRWorkSource getInstance(String sourceID) {
return sources.computeIfAbsent(sourceID, MCRWorkSource::new);
}
private MCRWorkSource(String sourceID) {
this.sourceID = sourceID;
}
public String getID() {
return sourceID;
}
/**
* Returns true, if this is our client application, that means
* the source's ID is our MCR.ORCID.OAuth.ClientID
*/
public boolean isThisApplication() {
return MCROAuthClient.instance().getClientID().equals(sourceID);
}
@Override
public boolean equals(Object obj) {
return (obj instanceof MCRWorkSource workSource) && sourceID.equals(workSource.sourceID);
}
@Override
public int hashCode() {
return sourceID.hashCode();
}
}
| 1,997 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/resources/MCRORCIDResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.resources;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.JDOMException;
import org.mycore.common.MCRJSONManager;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.orcid.MCRORCIDProfile;
import org.mycore.orcid.user.MCRORCIDSession;
import org.mycore.orcid.user.MCRORCIDUser;
import org.mycore.orcid.user.MCRPublicationStatus;
import org.mycore.orcid.user.MCRUserStatus;
import org.mycore.orcid.works.MCRWorksSection;
import org.xml.sax.SAXException;
import com.google.gson.Gson;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response.Status;
@Path("orcid")
public class MCRORCIDResource {
private static final Logger LOGGER = LogManager.getLogger();
/**
* Returns the ORCID status of the current user as JSON, e.g.
*
* {
* "orcid": "0000-0001-5484-889X",
* "isORCIDUser": true,
* "weAreTrustedParty": true
* }
*
* @see org.mycore.orcid.user.MCRUserStatus
*/
@GET
@Path("status")
@Produces(MediaType.APPLICATION_JSON)
public String getUserStatus() {
MCRORCIDUser user = MCRORCIDSession.getCurrentUser();
Gson gson = MCRJSONManager.instance().createGson();
return gson.toJson(user.getStatus());
}
/**
* Returns the publication status for a given MCRObjectID in the current user's ORCID profile, e.g.
*
* {
* "user": {
* "orcid": "0000-0001-5484-889X",
* "isORCIDUser": true,
* "weAreTrustedParty": true
* },
* "objectID": "mir_mods_00088905",
* "isUsersPublication": true,
* "isInORCIDProfile": true
* }
*
* @see org.mycore.orcid.user.MCRPublicationStatus
*/
@GET
@Path("status/{objectID}")
@Produces(MediaType.APPLICATION_JSON)
public String getPublicationStatus(@PathParam("objectID") String objectID)
throws JDOMException, IOException, SAXException {
MCRObjectID oid = checkID(objectID);
MCRORCIDUser user = MCRORCIDSession.getCurrentUser();
return publicationStatus(oid, user);
}
/**
* Publishes a work in the current user's ORCID profile, or
* updates an existing work there, given the object ID of the local MODS object.
*
* The request path must contain the MCRObjectID to publish.
* The current user must have an ORCID profile and must have authorized this application
* to add or updated works.
*
* Returns the new publication status as by {@link #getPublicationStatus(String)}
*
* @author Frank Lützenkirchen
*/
@GET
@Path("publish/{objectID}")
@Produces(MediaType.APPLICATION_JSON)
public String publish(@PathParam("objectID") String objectID) {
MCRObjectID oid = checkID(objectID);
MCRORCIDUser user = MCRORCIDSession.getCurrentUser();
MCRUserStatus userStatus = user.getStatus();
if (!(userStatus.isORCIDUser() && userStatus.weAreTrustedParty())) {
throw new WebApplicationException(Status.FORBIDDEN);
}
try {
MCRORCIDProfile profile = user.getProfile();
MCRWorksSection works = profile.getWorksSection();
MCRPublicationStatus status = user.getPublicationStatus(oid);
if (!status.isUsersPublication()) {
throw new WebApplicationException(Status.FORBIDDEN);
} else if (status.isInORCIDProfile()) {
works.findWork(oid).get().update(oid);
} else {
works.addWorkFrom(oid);
}
return publicationStatus(oid, user);
} catch (Exception ex) {
LOGGER.warn("Exception publishing " + oid + " to ORCID", ex);
String msg = ex.getClass().getName() + " " + ex.getMessage();
throw new InternalServerErrorException(msg);
}
}
private MCRObjectID checkID(String objectID) {
if (objectID == null || objectID.isEmpty() || !MCRObjectID.isValid(objectID)) {
throw new WebApplicationException(Status.NOT_FOUND);
}
MCRObjectID oid = MCRObjectID.getInstance(objectID);
if (!MCRMetadataManager.exists(oid)) {
throw new WebApplicationException(Status.NOT_FOUND);
}
return oid;
}
private String publicationStatus(MCRObjectID oid, MCRORCIDUser user)
throws JDOMException, IOException, SAXException {
MCRPublicationStatus status = user.getPublicationStatus(oid);
Gson gson = MCRJSONManager.instance().createGson();
return gson.toJson(status);
}
}
| 5,697 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDUser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/user/MCRORCIDUser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.user;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.mods.MCRMODSWrapper;
import org.mycore.orcid.MCRORCIDProfile;
import org.mycore.orcid.oauth.MCRTokenResponse;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserAttribute;
import org.mycore.user2.MCRUserManager;
import org.xml.sax.SAXException;
/**
* Provides functionality to interact with MCRUser that is also an ORCID user.
* The user's ORCID iD and access token are stored as attributes.
*
* @author Frank Lützenkirchen
*/
public class MCRORCIDUser {
private static final Logger LOGGER = LogManager.getLogger(MCRORCIDUser.class);
public static final String ATTR_ID_PREFIX = "id_";
private static final String ATTR_ORCID_ID = ATTR_ID_PREFIX + "orcid";
private static final String ATTR_ORCID_TOKEN = "token_orcid";
private static final String MATCH_ONLY_NAME_IDENTIFIER = MCRConfiguration2
.getString("MCR.ORCID.User.NameIdentifier").orElse("");
private MCRUser user;
private MCRORCIDProfile profile;
public MCRORCIDUser(MCRUser user) {
this.user = user;
}
public MCRUser getUser() {
return user;
}
public MCRUserStatus getStatus() {
return new MCRUserStatus(this);
}
/** Called from MCROAuthServlet to store the user's ORCID iD and token after successful OAuth authorization */
public void store(MCRTokenResponse token) {
user.setUserAttribute(ATTR_ORCID_ID, token.getORCID());
user.setUserAttribute(ATTR_ORCID_TOKEN, token.getAccessToken());
MCRUserManager.updateUser(user);
}
public String getORCID() {
return user.getUserAttribute(ATTR_ORCID_ID);
}
public String getAccessToken() {
return user.getUserAttribute(ATTR_ORCID_TOKEN);
}
public MCRORCIDProfile getProfile() {
if ((profile == null) && (getORCID() != null)) {
String orcid = getORCID();
String token = getAccessToken();
profile = new MCRORCIDProfile(orcid);
if (token != null) {
profile.setAccessToken(token);
}
}
return profile;
}
public MCRPublicationStatus getPublicationStatus(MCRObjectID oid) throws JDOMException, IOException, SAXException {
return new MCRPublicationStatus(this, oid);
}
public boolean isMyPublication(MCRObjectID oid) {
MCRObject obj = MCRMetadataManager.retrieveMCRObject(oid);
MCRMODSWrapper wrapper = new MCRMODSWrapper(obj);
Set<String> nameIdentifierKeys = getNameIdentifierKeys(wrapper);
Set<String> userIdentifierKeys = getUserIdentifierKeys();
nameIdentifierKeys.retainAll(userIdentifierKeys);
if (!nameIdentifierKeys.isEmpty()) {
for (String key : nameIdentifierKeys) {
LOGGER.info("user's identifier occurs in publication: " + key);
}
}
return !nameIdentifierKeys.isEmpty();
}
private Set<String> getUserIdentifierKeys() {
Set<String> identifierKeys = new HashSet<>();
for (MCRUserAttribute attribute : user.getAttributes()) {
if (attribute.getName().startsWith("id_")) {
String idType = attribute.getName().substring(3);
String key = buildNameIdentifierKey(idType, attribute.getValue());
LOGGER.info("user has name identifier: " + key);
identifierKeys.add(key);
}
}
return identifierKeys;
}
public static Set<String> getNameIdentifierKeys(MCRMODSWrapper wrapper) {
Set<String> identifierKeys = new HashSet<>();
String xPath = "mods:name/mods:nameIdentifier";
if (!MATCH_ONLY_NAME_IDENTIFIER.isEmpty()) {
xPath += "[@type = '" + MATCH_ONLY_NAME_IDENTIFIER + "']";
}
List<Element> nameIdentifiers = wrapper.getElements(xPath);
for (Element nameIdentifier : nameIdentifiers) {
if (!"".equals(nameIdentifier.getAttributeValue("type"))) {
String key = buildNameIdentifierKey(nameIdentifier.getAttributeValue("type"), nameIdentifier.getText());
LOGGER.info("found name identifier in publication: " + key);
identifierKeys.add(key);
} else {
LOGGER.info("found name identifier without type, skipping");
}
}
return identifierKeys;
}
private static String buildNameIdentifierKey(String type, String id) {
return type + ":" + id;
}
}
| 5,709 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPublicationStatus.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/user/MCRPublicationStatus.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.user;
import java.io.IOException;
import org.jdom2.JDOMException;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.orcid.MCRORCIDProfile;
import org.mycore.orcid.works.MCRWorksSection;
import org.xml.sax.SAXException;
public class MCRPublicationStatus {
private MCRUserStatus user;
private String objectID;
private boolean isUsersPublication = false;
private boolean isInORCIDProfile = false;
private String putCode = null;
MCRPublicationStatus(MCRORCIDUser orcidUser, MCRObjectID oid)
throws JDOMException, IOException, SAXException {
this.user = orcidUser.getStatus();
this.objectID = oid.toString();
if (user.isORCIDUser()) {
isUsersPublication = orcidUser.isMyPublication(oid);
MCRORCIDProfile profile = orcidUser.getProfile();
MCRWorksSection works = profile.getWorksSection();
isInORCIDProfile = works.containsWork(oid); // Maybe containsOwnWork(oid);
if (isInORCIDProfile) {
putCode = works.findWork(oid).get().getPutCode(); // Maybe findOwnWork(oid)
}
}
}
public MCRUserStatus getUserStatus() {
return user;
}
public String getObjectID() {
return objectID;
}
public boolean isUsersPublication() {
return isUsersPublication;
}
public boolean isInORCIDProfile() {
return isInORCIDProfile;
}
public String getPutCode() {
return putCode;
}
}
| 2,271 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserStatus.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/user/MCRUserStatus.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.user;
public class MCRUserStatus {
private boolean isORCIDUser;
private String orcid;
private boolean weAreTrustedParty;
MCRUserStatus(MCRORCIDUser user) {
this.orcid = user.getORCID();
this.isORCIDUser = orcid != null;
this.weAreTrustedParty = user.getAccessToken() != null;
}
public boolean isORCIDUser() {
return isORCIDUser;
}
public String getORCID() {
return orcid;
}
public boolean weAreTrustedParty() {
return weAreTrustedParty;
}
}
| 1,293 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRORCIDSession.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-orcid/src/main/java/org/mycore/orcid/user/MCRORCIDSession.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.orcid.user;
import java.io.IOException;
import org.jdom2.JDOMException;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserManager;
import org.xml.sax.SAXException;
public class MCRORCIDSession {
private static final String KEY_ORCID_USER = "ORCID_USER";
public static MCRORCIDUser getCurrentUser() {
MCRSession session = MCRSessionMgr.getCurrentSession();
MCRUser user = MCRUserManager.getCurrentUser();
MCRORCIDUser orcidUser = (MCRORCIDUser) session.get(KEY_ORCID_USER);
if ((orcidUser == null) || !orcidUser.getUser().equals(user)) {
orcidUser = new MCRORCIDUser(user);
session.put(KEY_ORCID_USER, orcidUser);
}
return orcidUser;
}
public static int getNumWorks() throws JDOMException, IOException, SAXException {
return getCurrentUser().getProfile().getWorksSection().getWorks().size();
}
}
| 1,739 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/test/java/org/mycore/user2/MCRUserManagerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.user2;
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.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.jdom2.Document;
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.xml.MCRURIResolver;
import org.mycore.user2.utils.MCRUserTransformer;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRUserManagerTest extends MCRUserTestCase {
MCRUser user;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
user = new MCRUser("junit");
user.setRealName("Test Case");
user.setPassword("test");
user.setUserAttribute("junit", "test");
MCRUserManager.createUser(user);
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#getUser(java.lang.String, org.mycore.user2.MCRRealm)}.
*/
@Test
public final void testGetUserStringMCRRealm() {
assertNull("Should not load user.", MCRUserManager.getUser(this.user.getUserName(), ""));
MCRUser user = MCRUserManager.getUser(this.user.getUserName(), MCRRealmFactory.getLocalRealm());
assertNotNull("Could not load user.", user);
assertEquals("Password hash is not as expected", "test", user.getPassword());
}
@Test
public final void testGetUsersByProperty() {
MCRUser user2 = new MCRUser("junit2");
user2.setRealName("Test Case II");
user2.setUserAttribute("junit", "foo");
user2.setUserAttribute("bar", "test");
MCRUserManager.createUser(user2);
MCRUser user3 = new MCRUser("junit3");
user3.setRealName("Test Case III");
user3.setUserAttribute("junit", "foo");
user3.getAttributes().add(new MCRUserAttribute("junit", "test"));
user3.setUserAttribute("bar", "test failed");
MCRUserManager.createUser(user3);
startNewTransaction();
assertEquals(2, MCRUserManager.getUsers("junit", "test").count());
assertEquals(0, MCRUserManager.getUsers("junit", "test failed").count());
}
//MCR-1885
@Test
public final void testGetUserPropertiesAfterGetUsers() {
MCRUser user = new MCRUser("john");
user.setRealName("John Doe");
user.setUserAttribute("id_orcid", "1234-5678-1234-0000");
user.setUserAttribute("id_scopus", "87654321");
assertEquals(2, user.getAttributes().size());
MCRUserManager.createUser(user);
assertEquals(2, user.getAttributes().size());
startNewTransaction();
MCRUser user2 = MCRUserManager.getUsers("id_orcid", "1234-5678-1234-0000").findFirst().get();
assertEquals("john", user2.getUserName());
MCRUser user3 = MCRUserManager.getUser(user2.getUserName(), user2.getRealmID());
assertEquals(2, user3.getAttributes().size());
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#exists(java.lang.String, org.mycore.user2.MCRRealm)}.
*/
@Test
public final void testExistsStringMCRRealm() {
assertFalse("Should not find user", MCRUserManager.exists(this.user.getUserName(), ""));
assertTrue("Could not find user", MCRUserManager.exists(this.user.getUserName(), this.user.getRealm()));
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#updateUser(org.mycore.user2.MCRUser)}.
*/
@Test
public final void testUpdateUser() {
String eMail = "info@mycore.de";
this.user.setEMail(eMail);
String groupName = "admin";
this.user.getSystemRoleIDs().add(groupName);
this.user.getAttributes().add(new MCRUserAttribute("id_key1", "value1"));
this.user.getAttributes().add(new MCRUserAttribute("id_key1", "value2"));
MCRUserManager.updateUser(this.user);
startNewTransaction();
MCRUser user = MCRUserManager.getUser(this.user.getUserName(), this.user.getRealm());
assertEquals("User information was not updated", eMail, user.getEMailAddress());
assertEquals("User was created not updated", 1, MCRUserManager.countUsers(null, null, null, null));
assertTrue("User is not in group " + groupName, user.getSystemRoleIDs().contains(groupName));
final List<MCRUserAttribute> attributes = user.getAttributes()
.stream()
.filter(attr -> attr.getName().equals("id_key1"))
.collect(Collectors.toList());
assertEquals("There should be two (id_key1) attributes", 2, attributes.size());
final MCRUserAttribute value2Attr = attributes
.stream()
.filter(attr -> attr.getValue().equals("value2"))
.findFirst()
.get();
user.getAttributes().retainAll(List.of(value2Attr));
MCRUserManager.updateUser(user);
startNewTransaction();
user = MCRUserManager.getUser(this.user.getUserName(), this.user.getRealm());
/*
* currently both attributes get removed if retain all is used
* Hibernate: delete from MCRUserAttr where id=? and name=? // this is the default attribute junit=test
* Hibernate: delete from MCRUserAttr where id=? and name=? // this is the id_key1 attribute(s)
*/
assertEquals("There should be one attribute", 1, user.getAttributes().size());
}
@Test
public final void testCreateUserUpdateBug() {
//MCR-2912
MCRUser user2Created = new MCRUser("junit2");
user2Created.setRealName("Test Case 2");
user2Created.setPassword("test2");
user2Created.setUserAttribute("junit2", "test2");
MCRUserManager.createUser(user2Created);
user2Created.getAttributes().add(new MCRUserAttribute("junit4", "test3"));
user2Created.getAttributes().add(new MCRUserAttribute("junit5", "test4"));
MCRUserManager.updateUser(user2Created);
MCRUser junit2 = MCRUserManager.getUser("junit2", MCRRealmFactory.getLocalRealm());
assertEquals(3, junit2.getAttributes().size());
startNewTransaction();
junit2 = MCRUserManager.getUser("junit2", MCRRealmFactory.getLocalRealm());
System.out.println(junit2.getAttributes().stream().map(attr -> attr.getName() + "=" + attr.getValue())
.collect(Collectors.toList()));
assertEquals(3, junit2.getAttributes().size());
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#deleteUser(java.lang.String, org.mycore.user2.MCRRealm)}.
*/
@Test
public final void testDeleteUserStringMCRRealm() {
MCRUserManager.deleteUser(this.user.getUserName(), this.user.getRealm());
assertNull("Should not find user", MCRUserManager.getUser(this.user.getUserName(), this.user.getRealm()));
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#deleteUser(org.mycore.user2.MCRUser)}.
*/
@Test
public final void testDeleteUserMCRUser() {
MCRUserManager.deleteUser(user);
assertNull("Should not find user", MCRUserManager.getUser(this.user.getUserName(), this.user.getRealm()));
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#listUsers(org.mycore.user2.MCRUser)}.
*/
@Test
public final void testListUsersMCRUser() {
List<MCRUser> listUsers = MCRUserManager.listUsers(null);
assertEquals("Should not find a user", 0, listUsers.size());
user.setOwner(user);
MCRUserManager.updateUser(user);
startNewTransaction();
listUsers = MCRUserManager.listUsers(user);
assertEquals("Could not find a user", 1, listUsers.size());
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#listUsers(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
public final void testListUsersStringStringString() {
List<MCRUser> listUsers = MCRUserManager.listUsers(null, null, "Test*", null);
assertEquals("Could not find a user", 1, listUsers.size());
}
/**
* Test method buildCondition with user attribute name pattern
*/
@Test
public final void testConditionWithUserAttributeNamePattern() {
assertEquals("Attribute name search failed", 0, MCRUserManager.countUsers(null, null, null, null,
"bar", null));
MCRUser user2 = new MCRUser("junit2");
user2.setRealName("Test Case II");
user2.setUserAttribute("junit2", "foo");
user2.setUserAttribute("bar", "test");
MCRUserManager.createUser(user2);
assertEquals("Attribute name search failed", 1, MCRUserManager.countUsers(null, null, null, null,
"bar", null));
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#countUsers(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
*/
@Test
public final void testCountUsers() {
assertEquals("Could not find a user", 1, MCRUserManager.countUsers(null, null, "*Case*", null));
}
/**
* Test method for {@link org.mycore.user2.MCRUserManager#login(java.lang.String, java.lang.String)}.
*/
@Test
public final void testLogin() {
String clearPasswd = user.getPassword();
Date curTime = new Date();
MCRUser user = MCRUserManager.login(this.user.getUserName(), clearPasswd);
assertNull("Should not login user", user);
MCRUserManager.updatePasswordHashToSHA256(this.user, clearPasswd);
MCRUserManager.updateUser(this.user);
startNewTransaction();
user = MCRUserManager.login(this.user.getUserName(), clearPasswd);
assertNotNull("Could not login user", user);
assertNotNull("Hash value was not updated", user.getHashType());
user = MCRUserManager.login(this.user.getUserName(), clearPasswd);
assertNotNull("No date set for last login.", user.getLastLogin());
assertTrue("Date was not updated", curTime.before(user.getLastLogin()));
user.disableLogin();
MCRUserManager.updateUser(user);
startNewTransaction();
assertNull("Should not login user when account is disabled",
MCRUserManager.login(this.user.getUserName(), clearPasswd));
user.enableLogin();
user.setValidUntil(new Date());
MCRUserManager.updateUser(user);
startNewTransaction();
assertNull("Should not login user when password is expired",
MCRUserManager.login(this.user.getUserName(), clearPasswd));
}
@Test
public final void toXML() throws IOException {
MCRUserManager.updatePasswordHashToSHA256(this.user, this.user.getPassword());
this.user.setEMail("info@mycore.de");
this.user.setHint("JUnit Test");
this.user.getSystemRoleIDs().add("admin");
this.user.getSystemRoleIDs().add("editor");
this.user.setLastLogin(new Date());
this.user.setRealName("Test Case");
this.user.setUserAttribute("tel", "555 4812");
this.user.setUserAttribute("street", "Heidestraße 12");
this.user.getAttributes().add(new MCRUserAttribute("tel", "555 4711"));
this.user.setOwner(this.user);
MCRUserManager.updateUser(this.user);
startNewTransaction();
assertEquals("Too many users", 1, MCRUserManager.countUsers(null, null, null, null));
assertEquals("Too many users", 1, MCRUserManager.listUsers(this.user).size());
Document exportableXML = MCRUserTransformer.buildExportableXML(this.user);
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(exportableXML, System.out);
}
@Test
public final void testLoadTestUser() {
Element input = MCRURIResolver.instance().resolve("resource:test-user.xml");
MCRUser mcrUser = MCRUserTransformer.buildMCRUser(input);
mcrUser.setUserName("junit2");
MCRUserManager.createUser(mcrUser);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.URIResolver.CachingResolver.Capacity", "0");
testProperties.put("MCR.URIResolver.CachingResolver.MaxAge", "0");
return testProperties;
}
}
| 13,338 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserAttributeMapperTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/test/java/org/mycore/user2/MCRUserAttributeMapperTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.user2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.jdom2.Document;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.user2.login.MCRShibbolethUserInformation;
import org.mycore.user2.utils.MCRUserTransformer;
/**
* @author René Adler (eagle)
*
*/
public class MCRUserAttributeMapperTest extends MCRUserTestCase {
private static String realmId = "mycore.de";
private static String roles = "staff,member";
private MCRUser mcrUser;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
mcrUser = MCRUserTransformer.buildMCRUser(MCRURIResolver.instance().resolve("resource:test-user.xml"));
}
@Test
public void testUserMapping() throws Exception {
MCRUserAttributeMapper attributeMapper = MCRRealmFactory.getAttributeMapper(realmId);
assertNotNull("no attribute mapping defined", attributeMapper);
HashMap<String, Object> attributes = new HashMap<>();
attributes.put("eduPersonPrincipalName", mcrUser.getUserName() + "@" + realmId);
attributes.put("displayName", mcrUser.getRealName());
attributes.put("mail", mcrUser.getEMailAddress());
attributes.put("eduPersonAffiliation", roles);
MCRUser user = new MCRUser(null, realmId);
attributeMapper.mapAttributes(user, attributes);
assertEquals(mcrUser.getUserName(), user.getUserName());
assertEquals(mcrUser.getRealName(), user.getRealName());
assertEquals(mcrUser.getEMailAddress(), user.getEMailAddress());
assertTrue(user.isUserInRole("editor"));
}
@Test
public void testUserInformationMapping() throws Exception {
Map<String, Object> attributes = new HashMap<>();
attributes.put("eduPersonPrincipalName", mcrUser.getUserName() + "@" + realmId);
attributes.put("displayName", mcrUser.getRealName());
attributes.put("mail", mcrUser.getEMailAddress());
attributes.put("eduPersonAffiliation", roles);
MCRUserInformation userInfo = new MCRShibbolethUserInformation(mcrUser.getUserName(), realmId, attributes);
MCRTransientUser user = new MCRTransientUser(userInfo);
assertEquals(mcrUser.getUserName(), user.getUserName());
assertEquals(mcrUser.getRealName(), user.getRealName());
assertEquals(mcrUser.getEMailAddress(), user.getEMailAddress());
assertTrue(user.isUserInRole("editor"));
}
@Test
public void testUserCreate() throws Exception {
Map<String, Object> attributes = new HashMap<>();
attributes.put("eduPersonPrincipalName", mcrUser.getUserName() + "@" + realmId);
attributes.put("displayName", mcrUser.getRealName());
attributes.put("mail", mcrUser.getEMailAddress());
attributes.put("eduPersonAffiliation", roles);
MCRUserInformation userInfo = new MCRShibbolethUserInformation(mcrUser.getUserName(), realmId, attributes);
MCRTransientUser user = new MCRTransientUser(userInfo);
assertEquals(mcrUser.getUserName(), user.getUserName());
assertEquals(mcrUser.getRealName(), user.getRealName());
assertTrue(user.isUserInRole("editor"));
Map<String, String> extraAttribs = new HashMap<>();
extraAttribs.put("attrib1", "test123");
extraAttribs.put("attrib2", "test321");
extraAttribs.forEach((key, value) -> user.setUserAttribute(key, value));
MCRUserManager.createUser(user);
startNewTransaction();
MCRUser storedUser = MCRUserManager.getUser(user.getUserName(), realmId);
assertEquals(mcrUser.getEMailAddress(), storedUser.getEMailAddress());
assertEquals(extraAttribs.get("attrib1"), storedUser.getUserAttribute("attrib1"));
assertEquals(extraAttribs.get("attrib2"), storedUser.getUserAttribute("attrib2"));
Document exportableXML = MCRUserTransformer.buildExportableXML(storedUser);
new XMLOutputter(Format.getPrettyFormat()).output(exportableXML, System.out);
}
@Test
public void testUserUpdate() throws Exception {
Map<String, Object> attributes = new HashMap<>();
attributes.put("eduPersonPrincipalName", mcrUser.getUserName() + "@" + realmId);
attributes.put("displayName", mcrUser.getRealName());
attributes.put("mail", mcrUser.getEMailAddress());
attributes.put("eduPersonAffiliation", roles);
MCRUserInformation userInfo = new MCRShibbolethUserInformation(mcrUser.getUserName(), realmId, attributes);
MCRTransientUser user = new MCRTransientUser(userInfo);
assertEquals(mcrUser.getUserName(), user.getUserName());
assertEquals(mcrUser.getRealName(), user.getRealName());
assertTrue(user.isUserInRole("editor"));
Map<String, String> extraAttribs = new HashMap<>();
extraAttribs.put("attrib1", "test123");
extraAttribs.put("attrib2", "test321");
extraAttribs.forEach((key, value) -> user.setUserAttribute(key, value));
MCRUserManager.createUser(user);
startNewTransaction();
attributes = new HashMap<>();
attributes.put("eduPersonPrincipalName", mcrUser.getUserName() + "@" + realmId);
attributes.put("displayName", mcrUser.getRealName());
attributes.put("mail", "new@mycore.de");
attributes.put("eduPersonAffiliation", "admin");
MCRUser storedUser = MCRUserManager.getUser(user.getUserName(), realmId);
MCRUserAttributeMapper attributeMapper = MCRRealmFactory.getAttributeMapper(realmId);
boolean changed = attributeMapper.mapAttributes(storedUser, attributes);
assertTrue("should changed", changed);
assertNotEquals(user.getEMailAddress(), storedUser.getEMailAddress());
Document exportableXML = MCRUserTransformer.buildExportableXML(storedUser);
new XMLOutputter(Format.getPrettyFormat()).output(exportableXML, System.out);
}
}
| 7,052 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserTestCase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/test/java/org/mycore/user2/MCRUserTestCase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.user2;
import java.util.Map;
import org.junit.Before;
import org.junit.Ignore;
import org.mycore.common.MCRJPATestCase;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImplTest;
/**
* @author Thomas Scheffler (yagee)
*
*/
@Ignore
public class MCRUserTestCase extends MCRJPATestCase {
@Before
@Override
public void setUp() throws Exception {
super.setUp();
MCRCategory groupsCategory = MCRCategoryDAOImplTest.loadClassificationResource("/mcr-roles.xml");
MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance();
DAO.addCategory(null, groupsCategory);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put(MCRRealmFactory.REALMS_URI_CFG_KEY, MCRRealmFactory.RESOURCE_REALMS_URI);
return testProperties;
}
}
| 1,841 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserTransformerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/test/java/org/mycore/user2/utils/MCRUserTransformerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.user2.utils;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.transform.stream.StreamSource;
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.xml.MCRURIResolver;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserTestCase;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlValue;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRUserTransformerTest extends MCRUserTestCase {
/**
* Test method for {@link org.mycore.user2.utils.MCRUserTransformer#buildMCRUser(org.jdom2.Element)}.
* @throws IOException
*/
@Test
public final void testBuildMCRUser() throws IOException {
Element input = MCRURIResolver.instance().resolve("resource:test-user.xml");
MCRUser mcrUser = MCRUserTransformer.buildMCRUser(input);
Document output = MCRUserTransformer.buildExportableXML(mcrUser);
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(input, System.out);
System.out.println();
xout.output(output, System.out);
assertTrue("Input element is not the same as outputElement",
MCRXMLHelper.deepEqual(input, output.getRootElement()));
}
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.NONE)
public static class HashMapTest2 {
public Map<String, String> map = new HashMap<>();
@XmlElement(name = "entry")
public MapEntry[] getMap() {
List<MapEntry> list = new ArrayList<>();
for (Entry<String, String> entry : map.entrySet()) {
MapEntry mapEntry = new MapEntry();
mapEntry.key = entry.getKey();
mapEntry.value = entry.getValue();
list.add(mapEntry);
}
return list.toArray(new MapEntry[list.size()]);
}
public void setMap(MapEntry[] arr) {
for (MapEntry entry : arr) {
this.map.put(entry.key, entry.value);
}
}
public static class MapEntry {
@XmlAttribute
public String key;
@XmlValue
public String value;
}
}
@Test
public void main() throws Exception {
HashMapTest2 mp = new HashMapTest2();
mp.map.put("key1", "value1");
mp.map.put("key2", "value2");
JAXBContext jc = JAXBContext.newInstance(HashMapTest2.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(mp, System.out);
Unmarshaller u = jc.createUnmarshaller();
String xmlStr
= "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><root><entry key=\"key2\">value2</entry><entry key=\"key1\">value1</entry></root>";
HashMapTest2 mp2 = (HashMapTest2) u.unmarshal(new StreamSource(new StringReader(xmlStr)));
m.marshal(mp2, System.out);
}
}
| 4,374 | 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.