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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRZonedDateTimeConverterTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/backend/jpa/MCRZonedDateTimeConverterTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa;
import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Test;
public class MCRZonedDateTimeConverterTest {
@Test
public void convertToEntityAttribute() throws Exception {
MCRZonedDateTimeConverter c = new MCRZonedDateTimeConverter();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = format.parse("2001-01-01T14:00:00Z");
ZonedDateTime zonedDateTime = c.convertToEntityAttribute(date);
ZonedDateTime compareDateTime = ZonedDateTime.of(2001, 1, 1, 14, 0, 0, 0, ZoneId.of("UTC"));
assertEquals(zonedDateTime.toInstant().getEpochSecond(), compareDateTime.toInstant().getEpochSecond());
}
}
| 1,655 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJPAAccessStoreTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/backend/jpa/access/MCRJPAAccessStoreTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.backend.jpa.access;
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.sql.Timestamp;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mycore.access.mcrimpl.MCRRuleMapping;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRJPATestCase;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRJPAAccessStoreTest extends MCRJPATestCase {
private static final MCRACCESSRULE TRUE_RULE = getTrueRule();
private static final MCRACCESSRULE FALSE_RULE = getFalseRule();
private static MCRJPAAccessStore ACCESS_STORE;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
if (ACCESS_STORE == null) {
ACCESS_STORE = new MCRJPAAccessStore();
}
MCREntityManagerProvider.getCurrentEntityManager().persist(TRUE_RULE);
MCREntityManagerProvider.getCurrentEntityManager().persist(FALSE_RULE);
startNewTransaction();
}
private static MCRACCESSRULE getTrueRule() {
MCRACCESSRULE rule = new MCRACCESSRULE();
rule.setCreationdate(new Timestamp(new Date().getTime()));
rule.setCreator("JUnit");
rule.setDescription("JUnit-Test rule");
rule.setRid("junit001");
rule.setRule("true");
return rule;
}
private static MCRACCESSRULE getFalseRule() {
MCRACCESSRULE rule = new MCRACCESSRULE();
rule.setCreationdate(new Timestamp(new Date().getTime()));
rule.setCreator("JUnit");
rule.setDescription("JUnit-Test rule");
rule.setRid("junit002");
rule.setRule("false");
return rule;
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#createAccessDefinition(org.mycore.access.mcrimpl.MCRRuleMapping)}.
*/
@Test
public void createAccessDefinition() {
final String objID = "test";
final String permission = "maytest";
addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
assertNotNull(
MCREntityManagerProvider.getCurrentEntityManager().find(MCRACCESS.class,
new MCRACCESSPK(permission, objID)));
}
private MCRRuleMapping addRuleMapping(final String objID, final String permission, final String rid) {
MCRRuleMapping rulemapping = new MCRRuleMapping();
rulemapping.setCreationdate(new Date());
rulemapping.setCreator("JUnit");
rulemapping.setObjId(objID);
rulemapping.setPool(permission);
rulemapping.setRuleId(rid);
ACCESS_STORE.createAccessDefinition(rulemapping);
return rulemapping;
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#getRuleID(String, String)}.
*/
@Test
public void getRuleID() {
final String objID = "test";
final String permission = "maytest";
addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
String rid = ACCESS_STORE.getRuleID(objID, permission);
assertEquals(TRUE_RULE.getRid(), rid);
rid = ACCESS_STORE.getRuleID(objID, "notdefined");
assertEquals(null, rid);
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#deleteAccessDefinition(org.mycore.access.mcrimpl.MCRRuleMapping)}.
*/
@Test
public void deleteAccessDefinition() {
final String objID = "test";
final String permission = "maytest";
MCRRuleMapping ruleMapping = addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
ACCESS_STORE.deleteAccessDefinition(ruleMapping);
startNewTransaction();
assertNull(
MCREntityManagerProvider.getCurrentEntityManager().find(MCRACCESS.class,
new MCRACCESSPK(permission, objID)));
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#updateAccessDefinition(org.mycore.access.mcrimpl.MCRRuleMapping)}.
*/
@Test
public void updateAccessDefinition() {
final String objID = "test";
final String permission = "maytest";
MCRRuleMapping ruleMapping = addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
ruleMapping.setRuleId(FALSE_RULE.getRid());
ACCESS_STORE.updateAccessDefinition(ruleMapping);
startNewTransaction();
MCRACCESS access = MCREntityManagerProvider.getCurrentEntityManager().find(MCRACCESS.class,
new MCRACCESSPK(permission, objID));
assertEquals(FALSE_RULE, access.getRule());
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#getAccessDefinition(java.lang.String, java.lang.String)}.
*/
@Test
public void getAccessDefinition() {
final String objID = "test";
final String permission = "maytest";
MCRRuleMapping ruleMapping = addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
MCRRuleMapping ruleMapping2 = ACCESS_STORE.getAccessDefinition(permission, objID);
// We will remove milliseconds as they don't need to be saved
assertEquals((long) Math.floor(ruleMapping.getCreationdate().getTime() / 1000), ruleMapping2.getCreationdate()
.getTime() / 1000);
assertEquals(ruleMapping.getCreator(), ruleMapping2.getCreator());
assertEquals(ruleMapping.getObjId(), ruleMapping2.getObjId());
assertEquals(ruleMapping.getPool(), ruleMapping2.getPool());
assertEquals(ruleMapping.getRuleId(), ruleMapping2.getRuleId());
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#getMappedObjectId(java.lang.String)}.
*/
@Test
public void getMappedObjectId() {
final String objID = "test";
final String permission = "maytest";
addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
List<String> results = ACCESS_STORE.getMappedObjectId(permission);
assertEquals(1, results.size());
assertEquals(objID, results.get(0));
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#getPoolsForObject(java.lang.String)}.
*/
@Test
public void getPoolsForObject() {
final String objID = "test";
final String permission = "maytest";
addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
List<String> results = ACCESS_STORE.getPoolsForObject(objID);
assertEquals(1, results.size());
assertEquals(permission, results.get(0));
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#getDatabasePools()}.
*/
@Test
public void getDatabasePools() {
final String objID = "test";
final String permission = "maytest";
addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
List<String> results = ACCESS_STORE.getDatabasePools();
assertEquals(1, results.size());
assertEquals(permission, results.get(0));
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#existsRule(java.lang.String, java.lang.String)}.
*/
@Test
public void existsRule() {
final String objID = "test";
final String permission = "maytest";
assertFalse(ACCESS_STORE.existsRule(objID, permission));
addRuleMapping(objID, permission, TRUE_RULE.getRid());
startNewTransaction();
assertTrue(ACCESS_STORE.existsRule(objID, permission));
}
/**
* Test method for
* {@link org.mycore.backend.jpa.access.MCRJPAAccessStore#getDistinctStringIDs()}.
*/
@Test
public void getDistinctStringIDs() {
final String objID = "test";
final String permission = "maytest";
final String permission2 = "maytesttoo";
addRuleMapping(objID, permission, TRUE_RULE.getRid());
addRuleMapping(objID, permission2, FALSE_RULE.getRid());
startNewTransaction();
List<String> results = ACCESS_STORE.getDistinctStringIDs();
assertEquals(1, results.size());
assertEquals(objID, results.get(0));
}
}
| 9,386 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURLTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/MCRURLTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
public class MCRURLTest extends MCRTestCase {
@Test
public void getParameter() throws Exception {
MCRURL url = new MCRURL("http://localhost:8080/test?a=hallo&b=mycore&c=münchen");
assertEquals("hallo", url.getParameter("a"));
assertEquals("mycore", url.getParameter("b"));
assertEquals("münchen", url.getParameter("c"));
MCRURL url2 = new MCRURL("http://localhost:8080/test?a=m%C3%BCnchen");
assertEquals("m%C3%BCnchen", url2.getParameter("a"));
}
@Test
public void getParameterMap() throws Exception {
MCRURL url = new MCRURL("http://localhost:8080/test?a=hallo&b=mycore&a=");
Map<String, List<String>> p = url.getParameterMap();
assertEquals(2, p.size());
List<String> a = p.get("a");
List<String> b = p.get("b");
assertEquals(2, a.size());
assertEquals(1, b.size());
assertEquals("mycore", b.get(0));
assertTrue(a.contains("hallo"));
assertTrue(a.contains(""));
}
@Test
public void addParameter() throws Exception {
MCRURL url = new MCRURL("http://localhost:8080/test?a=hallo&b=mycore");
url.addParameter("c", "alleswirdgut");
assertEquals("alleswirdgut", url.getParameter("c"));
url.addParameter("a", "repository");
List<String> aValues = url.getParameterValues("a");
assertTrue(aValues.contains("hallo"));
assertTrue(aValues.contains("repository"));
MCRURL url2 = new MCRURL("http://localhost:8080/test?a=hinz%20%26%20kunz");
url2.addParameter("b", "b%C3%A4r");
assertEquals("http://localhost:8080/test?a=hinz%20%26%20kunz&b=b%C3%A4r", url2.getURL().toString());
}
@Test
public void removeParameter() throws Exception {
MCRURL url = new MCRURL("http://localhost:8080/test?a=hallo&b=mycore&a=alleswirdgut");
url.removeParameter("a");
assertNull(url.getParameter("a"));
assertEquals("mycore", url.getParameter("b"));
url.removeParameter("b");
assertNull(url.getParameter("b"));
MCRURL url2 = new MCRURL("http://localhost:8080/test?a=hinz%20%26%20kunz&b=removeme");
url2.removeParameter("b");
assertEquals("http://localhost:8080/test?a=hinz%20%26%20kunz", url2.getURL().toString());
}
@Test
public void removeParameterValue() throws Exception {
MCRURL url = new MCRURL("http://localhost:8080/test?a=hallo&b=mycore&a=alleswirdgut");
url.removeParameterValue("a", "alleswirdgut");
assertEquals("hallo", url.getParameter("a"));
url.removeParameterValue("b", "mycore");
assertNull(url.getParameter("b"));
}
}
| 3,692 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJerseyJPATest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/jersey/resources/MCRJerseyJPATest.java | package org.mycore.frontend.jersey.resources;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mycore.access.MCRAccessBaseImpl;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRStoreTestCase;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.jersey.filter.MCRDBTransactionFilter;
import org.mycore.frontend.jersey.filter.MCRSessionHookFilter;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.core.Response;
public class MCRJerseyJPATest extends MCRStoreTestCase {
private MCRJerseyTestFeature jersey;
@Before
public void setUpJersey() throws Exception {
jersey = new MCRJerseyTestFeature();
jersey.setUp(Set.of(
MCRSessionHookFilter.class,
MCRDBTransactionFilter.class,
ObjectResource.class,
MCRJerseyExceptionMapper.class));
}
@After
public void tearDownJersey() throws Exception {
jersey.tearDown();
}
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName());
testProperties.put("MCR.Metadata.Type.object", "true");
return testProperties;
}
@Test
public void rollback() throws MCRAccessException, InterruptedException {
MCRObjectID id = MCRObjectID.getInstance("mycore_object_00000001");
try (Response ignored = jersey.target("object/create/" + id).request().post(null)) {
printTable("MCRObject");
assertCreateDate("create date should not be null after creation");
}
try (Response ignored = jersey.target("object/break/" + id).request().post(null)) {
printTable("MCRObject");
assertCreateDate("create date should be rolled back and not be null");
}
}
private void assertCreateDate(String message) {
queryTable("MCRObject", (resultSet) -> {
try {
resultSet.next();
String createDate = resultSet.getString(2);
Assert.assertNotNull(message, createDate);
} catch (SQLException e) {
Assert.fail("Unable to query MCRObject table");
}
});
}
@Path("object")
public static class ObjectResource {
@Path("create/{id}")
@POST
public void create(@PathParam("id") String id) throws MCRAccessException {
MCRObjectID mcrId = MCRObjectID.getInstance(id);
MCRObject root = createObject(mcrId.toString());
MCRMetadataManager.create(root);
}
@Path("break/{id}")
@POST
public void breakIt(@PathParam("id") String id) {
String tableName = getTableName("MCRObject");
executeUpdate("UPDATE " + tableName + " SET CREATEDATE=null WHERE ID='" + id + "'");
printTable("MCRObject");
throw new APIException("Breaking!!!");
}
private MCRObject createObject(String id) {
MCRObject object = new MCRObject();
object.setId(MCRObjectID.getInstance(id));
object.setSchema("noSchema");
return object;
}
}
private static final class APIException extends RuntimeException {
APIException(String message) {
super(message);
}
}
}
| 3,712 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJerseyTestFeature.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/jersey/resources/MCRJerseyTestFeature.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.jersey.resources;
import java.util.Set;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.mycore.frontend.jersey.MCRJerseyDefaultConfiguration;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Application;
/**
* Jersey test feature.
*
* @author Matthias Eichner
*/
public class MCRJerseyTestFeature {
private MCRJerseyTest jerseyTest;
public void setUp(Set<Class<?>> jerseyComponents) throws Exception {
MCRJerseyTest.COMPONENTS.set(jerseyComponents);
this.jerseyTest = new MCRJerseyTest();
this.jerseyTest.setUp();
}
public void tearDown() throws Exception {
this.jerseyTest.tearDown();
}
public WebTarget target(final String path) {
return this.jerseyTest.target().path(path);
}
public MCRJerseyTest test() {
return jerseyTest;
}
public static class MCRJerseyTest extends JerseyTest {
private static final ThreadLocal<Set<Class<?>>> COMPONENTS = new ThreadLocal<>();
@Override
protected Application configure() {
return new MCRJerseyTestResourceConfig(COMPONENTS.get());
}
@Override
protected void configureClient(ClientConfig config) {
config.register(MultiPartFeature.class);
}
@Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
@Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.forServlet(new ServletContainer((ResourceConfig) configure())).build();
}
}
protected static class MCRJerseyTestResourceConfig extends ResourceConfig {
public MCRJerseyTestResourceConfig(Set<Class<?>> components) {
new MCRJerseyTestConfiguration(components).configure(this);
}
}
protected static class MCRJerseyTestConfiguration extends MCRJerseyDefaultConfiguration {
private final Set<Class<?>> components;
public MCRJerseyTestConfiguration(Set<Class<?>> components) {
this.components = components;
}
@Override
protected void setupResources(ResourceConfig resourceConfig) {
resourceConfig.registerClasses(this.components);
}
@Override
protected void setupFeatures(ResourceConfig resourceConfig) {
// no features
}
}
}
| 3,765 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJerseyResourceTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/jersey/resources/MCRJerseyResourceTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.jersey.resources;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
public class MCRJerseyResourceTest {
private MCRJerseyTestFeature jersey;
@Before
public void setUpJersey() throws Exception {
jersey = new MCRJerseyTestFeature();
jersey.setUp(Set.of(TestCase.class));
}
@After
public void tearDownJersey() throws Exception {
jersey.tearDown();
}
@Test
public void test() {
System.out.println("Running test");
final String hello = jersey.target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
final String logout = jersey.target("hello/logout/Peter").request().get(String.class);
assertEquals("GoodBye Peter!", logout);
}
@Path("hello")
public static class TestCase {
@GET
public String get() {
return "Hello World!";
}
@GET
@Path("logout/{id}")
public String logout(@PathParam("id") String id) {
return "GoodBye " + id + "!";
}
}
}
| 2,000 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLocaleResourceTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/jersey/resources/MCRLocaleResourceTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.jersey.resources;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import jakarta.ws.rs.core.MediaType;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.frontend.jersey.filter.MCRSessionHookFilter;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
public class MCRLocaleResourceTest extends MCRTestCase {
private MCRJerseyTestFeature jersey;
@Before
public void setUp() throws Exception {
super.setUp();
jersey = new MCRJerseyTestFeature();
jersey.setUp(Set.of(
MCRSessionHookFilter.class,
MCRLocaleResource.class));
}
@After
public void tearDown() throws Exception {
super.tearDown();
jersey.tearDown();
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> map = new HashMap<>();
map.put("MCR.Metadata.Languages", "de,en,it");
return map;
}
@Test
public void language() {
final String language = jersey.target("locale/language").request().acceptLanguage(Locale.ITALY)
.get(String.class);
assertEquals("it", language);
}
@Test
public void languages() {
final String languagesString = jersey.target("locale/languages").request().get(String.class);
JsonArray languages = JsonParser.parseString(languagesString).getAsJsonArray();
assertEquals(3, languages.size());
}
@Test
public void translate() {
String hello = jersey.target("locale/translate/junit.hello").request().get(String.class);
assertEquals("Hallo Welt", hello);
}
@Test
public void translateToLocale() {
String hello = jersey.target("locale/translate/en/junit.hello").request(MediaType.TEXT_PLAIN).get(String.class);
assertEquals("Hello World", hello);
}
}
| 2,764 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSecureTokenV2Test.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/support/MCRSecureTokenV2Test.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.support;
import static org.junit.Assert.assertEquals;
import java.net.URISyntaxException;
import org.junit.Test;
/**
* @author Thomas Scheffler(yagee)
*/
public class MCRSecureTokenV2Test {
/**
* Test method for {@link org.mycore.frontend.support.MCRSecureTokenV2#getHash()}.
*/
@Test
public final void testGetHash() {
MCRSecureTokenV2 token = getWowzaSample();
assertEquals("TgJft5hsjKyC5Rem_EoUNP7xZvxbqVPhhd0GxIcA2oo=", token.getHash());
token = getWowzaSample2();
assertEquals("5_A2m7LV6pTuLN3lUPvAUN2xI8x_BDrgfXfVi_gT-GA=", token.getHash());
}
/**
* Test method for {@link org.mycore.frontend.support.MCRSecureTokenV2#toURI(java.lang.String, java.lang.String)}.
*/
@Test
public final void testToURL() throws URISyntaxException {
MCRSecureTokenV2 token = getWowzaSample();
String baseURL = "http://192.168.1.1:1935/";
String suffix = "/playlist.m3u8";
String hashParameterName = "myTokenPrefixhash";
String expectedURL = baseURL + "vod/sample.mp4" + suffix
+ "?myTokenPrefixstarttime=1395230400&myTokenPrefixendtime=1500000000&myTokenPrefixCustomParameter=abcdef&"
+ hashParameterName + "=TgJft5hsjKyC5Rem_EoUNP7xZvxbqVPhhd0GxIcA2oo=";
assertEquals(expectedURL, token.toURI(baseURL, suffix, hashParameterName).toString());
}
private static MCRSecureTokenV2 getWowzaSample() {
String contentPath = "vod/sample.mp4";
String sharedSecret = "mySharedSecret";
String ipAddress = "192.168.1.2";
String[] parameters = { "myTokenPrefixstarttime=1395230400", "myTokenPrefixendtime=1500000000",
"myTokenPrefixCustomParameter=abcdef" };
return new MCRSecureTokenV2(contentPath, ipAddress, sharedSecret, parameters);
}
private static MCRSecureTokenV2 getWowzaSample2() {
String contentPath = "vod/_definst_/mp4:Überraschung.mp4";
String sharedSecret = "JUnitSecret";
String ipAddress = "192.168.1.2";
String[] parameters = {};
return new MCRSecureTokenV2(contentPath, ipAddress, sharedSecret, parameters);
}
}
| 2,933 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUploadHelperTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/fileupload/MCRUploadHelperTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.fileupload;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.mycore.common.MCRException;
import org.mycore.common.MCRStreamUtils;
import org.mycore.common.MCRTestCase;
/**
* @author Thomas Scheffler (yagee)
*
*/
@RunWith(Parameterized.class)
public class MCRUploadHelperTest extends MCRTestCase {
static String prefix = "junit";
static String suffix = "test..file";
static String[] genDelims = { ":", "?", "#", "[", "]", "@" };
static String[] subDelims = { "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" };
private static final String[] WINDOWS_RESERVED_CHARS = { "<", ">", ":", "\"", "|", "?", "*", "\\" };
private static final String[] RESERVED_NAMES = { "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8",
"com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn", "aux" };
@Parameter(0)
public String path;
@Parameter(1)
public Class<? extends Exception> expectedException;
@Parameters
public static Iterable<Object[]> data() {
return Stream.concat(toParameter(validNames(), null),
toParameter(invalidNames(), MCRException.class))::iterator;
}
private static Stream<String> invalidNames() {
return MCRStreamUtils.concat(
Stream.of(RESERVED_NAMES),
validNames().map(s -> "../" + s),
validNames().map(s -> "./" + s),
validNames().map(s -> "/" + s),
validNames().map(s -> "foo//" + s),
MCRStreamUtils.concat(IntStream.range(0, 32).mapToObj(i -> "" + (char) i),
Stream.of(WINDOWS_RESERVED_CHARS),
Stream.concat(Stream.of(genDelims), Stream.of(subDelims)).distinct().map(c -> prefix + c + suffix)));
}
private static Stream<String> validNames() {
return Stream.of(prefix + " " + suffix, prefix + suffix, "." + prefix + suffix);
}
private static Stream<Object[]> toParameter(Stream<String> input, Class<? extends Exception> exp) {
return input.map(s -> new Object[] { s, exp });
}
@Test
public void checkPathName() {
try {
MCRUploadHelper.checkPathName(path);
if (expectedException != null) {
throw new AssertionError(
"Expected test to throw instance of " + expectedException.getName() + " for path=\"" + path + "\"");
}
} catch (RuntimeException e) {
if (expectedException == null || !expectedException.isAssignableFrom(e.getClass())) {
throw e;
}
}
}
}
| 3,596 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSecureTokenV2FilterConfigTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/frontend/filter/MCRSecureTokenV2FilterConfigTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.filter;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.regex.Pattern;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRSecureTokenV2FilterConfigTest extends MCRTestCase {
/**
* Test method for {@link org.mycore.frontend.filter.MCRSecureTokenV2FilterConfig#getExtensionPattern(java.util.Collection)}.
*/
@Test
public void testGetExtensionPattern() {
testMP4Files(MCRSecureTokenV2FilterConfig.getExtensionPattern(Collections.singletonList("mp4")));
testMP4Files(MCRSecureTokenV2FilterConfig.getExtensionPattern(Arrays.asList("flv", "mp4")));
testMP4Files(MCRSecureTokenV2FilterConfig.getExtensionPattern(Arrays.asList("mp4", "flv")));
}
private void testMP4Files(Pattern mp4) {
testPattern(mp4, "test.mp4", true);
testPattern(mp4, "test.mymp4", false);
testPattern(mp4, "test.mp45", false);
testPattern(mp4, "my test.mp4", true);
}
private void testPattern(Pattern p, String filename, boolean result) {
if (result) {
assertTrue("Filename " + filename + " should match " + p, p.matcher(filename).matches());
} else {
assertFalse("Filename " + filename + " should not match " + p, p.matcher(filename).matches());
}
}
}
| 2,211 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRQueryTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/services/fieldquery/MCRQueryTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.fieldquery;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
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.MCRTestCase;
import org.mycore.common.xml.MCRXMLHelper;
public class MCRQueryTest extends MCRTestCase {
@Before
public void setUp() throws Exception {
super.setUp();
}
@Test
public final void testQueryAsXML() {
Document doc = new Document();
Element query = new Element("query");
query.setAttribute("maxResults", "50");
query.setAttribute("numPerPage", "25");
doc.addContent(query);
Element sortby = new Element("sortBy");
query.addContent(sortby);
Element sortfield = new Element("field");
sortfield.setAttribute("name", "dict01_sort");
sortfield.setAttribute("order", "ascending");
sortby.addContent(sortfield);
Element return_fields = new Element("returnFields");
return_fields.setText("id,returnId,objectType");
query.addContent(return_fields);
Element conditions = new Element("conditions");
conditions.setAttribute("format", "xml");
query.addContent(conditions);
Element bool = new Element("boolean");
bool.setAttribute("operator", "and");
conditions.addContent(bool);
Element condition01 = new Element("condition");
condition01.setAttribute("field", "objectType");
condition01.setAttribute("operator", "=");
condition01.setAttribute("value", "viaf");
bool.addContent(condition01);
Element condition02 = new Element("condition");
condition02.setAttribute("field", "title");
condition02.setAttribute("operator", "contains");
condition02.setAttribute("value", "Amt");
bool.addContent(condition02);
Element not = new Element("boolean");
not.setAttribute("operator", "not");
bool.addContent(not);
Element condition03 = new Element("condition");
condition03.setAttribute("field", "title");
condition03.setAttribute("operator", "contains");
condition03.setAttribute("value", "Ehre");
not.addContent(condition03);
try {
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
xmlOutputter.output(doc, System.out);
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println();
MCRQuery mcrquery = MCRQuery.parseXML(doc);
Document mcrquerydoc = mcrquery.buildXML();
try {
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
xmlOutputter.output(mcrquerydoc, System.out);
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println();
assertTrue("Elements should be equal", MCRXMLHelper.deepEqual(doc, mcrquerydoc));
}
}
| 3,838 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRQueryParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/services/fieldquery/MCRQueryParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.fieldquery;
import static org.junit.Assert.assertEquals;
import org.jdom2.Element;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.parsers.bool.MCRCondition;
/**
* This class is a JUnit test case for org.mycore.MCRBooleanClausParser.
*
* @author Jens Kupferschmidt
* @author Christoph Neidahl (OPNA2608)
*/
public class MCRQueryParserTest extends MCRTestCase {
private final MCRQueryParser queryParser = new MCRQueryParser();
/**
* Test method for
* {@link org.mycore.services.fieldquery.MCRQueryParser#parse(org.jdom2.Element) MCRQueryParser.parse} for XML
*/
@Test
public final void testQueryAsXML() {
Element c1 = new Element("condition");
c1.setAttribute("field", "title");
c1.setAttribute("operator", "contains");
c1.setAttribute("value", "Amt und Würde");
MCRCondition<Void> queryStringParsed = queryParser.parse(c1);
System.out.println("XML query parser test 1 :" + queryStringParsed);
assertEquals("Returned value is not",
"(title contains \"Amt\") AND (title contains \"und\") AND (title contains \"Würde\")",
queryStringParsed.toString());
Element c2 = new Element("condition");
c2.setAttribute("field", "title");
c2.setAttribute("operator", "contains");
c2.setAttribute("value", "Amt 'und Würde'");
queryStringParsed = queryParser.parse(c2);
System.out.println("XML query parser test 2 :" + queryStringParsed);
assertEquals("Returned value is not", "(title contains \"Amt\") AND (title phrase \"und Würde\")",
queryStringParsed.toString());
Element c3 = new Element("condition");
c3.setAttribute("field", "title");
c3.setAttribute("operator", "contains");
c3.setAttribute("value", "Amt und (Würde)");
queryStringParsed = queryParser.parse(c3);
System.out.println("XML query parser test 3 :" + queryStringParsed);
assertEquals("Returned value is not",
"(title contains \"Amt\") AND (title contains \"und\") AND (title contains \"(Würde)\")",
queryStringParsed.toString());
Element bool = new Element("boolean");
bool.setAttribute("operator", "oR");
bool.addContent(c1);
bool.addContent(c2);
bool.addContent(c3);
queryStringParsed = queryParser.parse(bool);
System.out.println("XML query parser test 4 :" + queryStringParsed);
assertEquals("Returned value is not",
"((title contains \"Amt\") AND (title contains \"und\") AND (title contains \"Würde\")) OR "
+ "((title contains \"Amt\") AND (title phrase \"und Würde\")) OR ((title contains \"Amt\") AND "
+ "(title contains \"und\") AND (title contains \"(Würde)\"))",
queryStringParsed.toString());
}
/**
* Test method for
* {@link org.mycore.services.fieldquery.MCRQueryParser#parse(java.lang.String) MCRQueryParser.parse} for String
*/
@Test
public final void testQueryAsString() {
String query_string = "()";
MCRCondition<Void> queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 1 :" + queryStringParsed);
assertEquals("Returned value is not", "true", queryStringParsed.toString());
query_string = "((true) or (false))";
queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 2 :" + queryStringParsed);
assertEquals("Returned value is not", "(true) OR (false)", queryStringParsed.toString());
query_string = " ( (true)) ";
queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 3 :" + queryStringParsed);
assertEquals("Returned value is not", "true", queryStringParsed.toString());
query_string = "(group = admin ) OR (group = authorgroup ) OR (group = readergroup )";
queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 4 :" + queryStringParsed);
assertEquals("Returned value is not",
"(group = \"admin\") OR (group = \"authorgroup\") OR (group = \"readergroup\")",
queryStringParsed.toString());
query_string = "title contains \"Amt\"";
queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 5 :" + queryStringParsed);
assertEquals("Returned value is not", "title contains \"Amt\"", queryStringParsed.toString());
query_string = "title contains \"Amt und Würde\"";
queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 6 :" + queryStringParsed);
assertEquals("Returned value is not",
"(title contains \"Amt\") AND (title contains \"und\") AND (title contains \"Würde\")",
queryStringParsed.toString());
query_string = "title contains \"Amt \'und Würde\'\"";
queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 7 :" + queryStringParsed);
assertEquals("Returned value is not", "(title contains \"Amt\") AND (title phrase \"und Würde\")",
queryStringParsed.toString());
query_string = "title contains \"Amt (und Würde)\"";
queryStringParsed = queryParser.parse(query_string);
System.out.println("String query parser test 8 :" + queryStringParsed);
assertEquals("Returned value is not",
"(title contains \"Amt\") AND (title contains \"(und\") AND (title contains \"Würde)\")",
queryStringParsed.toString());
}
}
| 6,567 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectStaticContentGeneratorTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/services/staticcontent/MCRObjectStaticContentGeneratorTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.staticcontent;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Paths;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
public class MCRObjectStaticContentGeneratorTest extends MCRTestCase {
@Test
public void getSlotDirPath() {
final MCRObjectStaticContentGenerator generator = new MCRObjectStaticContentGenerator(
null, Paths.get("/"), "test");
MCRConfiguration2.set("MCR.Metadata.ObjectID.NumberPattern", "00000");
resetObjectIDFormatter();
MCRObjectID derivate = MCRObjectID.getInstance("mcr_derivate_00001");
Assert.assertEquals("Paths should match", Paths.get("/000/01"), generator.getSlotDirPath(derivate));
}
@Test
public void getSlotDirPath2() {
final MCRObjectStaticContentGenerator generator = new MCRObjectStaticContentGenerator(
null, Paths.get("/"), "test");
MCRConfiguration2.set("MCR.Metadata.ObjectID.NumberPattern", "000000");
resetObjectIDFormatter();
MCRObjectID derivate = MCRObjectID.getInstance("mcr_derivate_000001");
Assert.assertEquals("Paths should match", Paths.get("/000/001"), generator.getSlotDirPath(derivate));
}
@Test
public void getSlotDirPath3() {
final MCRObjectStaticContentGenerator generator = new MCRObjectStaticContentGenerator(
null, Paths.get("/"), "test");
MCRConfiguration2.set("MCR.Metadata.ObjectID.NumberPattern", "0000000");
resetObjectIDFormatter();
MCRObjectID derivate = MCRObjectID.getInstance("mcr_derivate_0000001");
Assert.assertEquals("Paths should match", Paths.get("/000/000/1"), generator.getSlotDirPath(derivate));
}
/** resets the objectID formatter via reflection in MCRObjectID **/
private void resetObjectIDFormatter() {
try {
Field fNumberformat = MCRObjectID.class.getDeclaredField("NUMBER_FORMAT");
fNumberformat.setAccessible(true);
Method mInitNumberformat = MCRObjectID.class.getDeclaredMethod("initNumberFormat");
mInitNumberformat.setAccessible(true); //if security settings allow this
Object oNumberFormat = mInitNumberformat.invoke(null);
fNumberformat.set(null, oNumberFormat);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
}
| 3,263 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTranslationTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/services/i18n/MCRTranslationTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.i18n;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
public class MCRTranslationTest extends MCRTestCase {
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Languages", "de,en,fr,pl");
return testProperties;
}
@Test
public void translate() {
// default locale should be 'de'
assertEquals("Hallo Welt", MCRTranslation.translate("junit.hello"));
// fall back to 'de'
assertEquals("Hallo Welt", MCRTranslation.translateToLocale("junit.hello", Locale.FRENCH));
}
/*
* Test method for 'org.mycore.services.i18n.MCRTranslation.getStringArray(String)'
*/
@Test
public void getStringArray() {
assertEquals(0, MCRTranslation.getStringArray(null).length);
assertEquals(1, MCRTranslation.getStringArray("test").length);
assertEquals(2, MCRTranslation.getStringArray("string1;string2").length);
assertEquals("string1", MCRTranslation.getStringArray("string1;string2")[0]);
assertEquals(2, MCRTranslation.getStringArray("string1\\;;string2").length);
assertEquals("string1;", MCRTranslation.getStringArray("string1\\;;string2")[0]);
assertEquals("string1\\", MCRTranslation.getStringArray("string1\\\\;string2")[0]);
}
@Test
public void getAvailableLanguages() {
Set<String> availableLanguages = MCRTranslation.getAvailableLanguages();
assertEquals(4, availableLanguages.size());
}
@Test
public void getDeprecatedMessageKeys() {
assertEquals("Depreacted I18N keys do not work", "MyCoRe ID",
MCRTranslation.translateToLocale("oldLabel", Locale.ENGLISH));
}
}
| 2,669 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessMock.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/MCRAccessMock.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.mycore.common.MCRUserInformation;
import jakarta.inject.Singleton;
/**
* Can be used to write Tests against the {@link MCRAccessManager}.
* Just add MCR.Access.Class with MCRAccessMock.class.getName() to the test-properties in the overwritten
* {@link org.mycore.common.MCRTestCase} getTestProperties() method.
*/
@Singleton
public class MCRAccessMock implements MCRAccessInterface {
private static final List<MCRCheckPermissionCall> CALLS = new ArrayList<>();
private static boolean checkPermissionReturn = true;
public static List<MCRCheckPermissionCall> getCheckPermissionCalls() {
return Collections.unmodifiableList(CALLS);
}
public static void clearCheckPermissionCallsList() {
CALLS.clear();
}
public static boolean getMethodResult() {
return checkPermissionReturn;
}
public static void setMethodResult(boolean methodResult) {
checkPermissionReturn = methodResult;
}
@Override
public boolean checkPermission(String permission) {
CALLS.add(new MCRCheckPermissionCall(null, permission));
return checkPermissionReturn;
}
@Override
public boolean checkPermission(String id, String permission) {
CALLS.add(new MCRCheckPermissionCall(id, permission));
return checkPermissionReturn;
}
@Override
public boolean checkPermissionForUser(String permission, MCRUserInformation userInfo) {
return checkPermission(permission);
}
@Override
public boolean checkPermission(String id, String permission, MCRUserInformation userInfo) {
return checkPermission(id, permission);
}
public static class MCRCheckPermissionCall {
private final String id;
private final String permission;
private MCRCheckPermissionCall(String id, String permission) {
this.id = id;
this.permission = Objects.requireNonNull(permission);
}
public String getId() {
return id;
}
public String getPermission() {
return permission;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MCRCheckPermissionCall that = (MCRCheckPermissionCall) o;
return Objects.equals(id, that.id) && permission.equals(that.permission);
}
@Override
public int hashCode() {
return Objects.hash(id, permission);
}
}
}
| 3,490 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAndConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/combined/MCRAndConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class MCRAndConditionTest {
@Test
void matches() {
MCRAndCondition xor=new MCRAndCondition();
xor.add(new MCRTestCondition(()->false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(()->false));
assertFalse(xor.matches(null));
xor.getChildConditions().clear();
xor.add(new MCRTestCondition(()->true));
assertTrue(xor.matches(null));
xor.add(new MCRTestCondition(()->true));
assertTrue(xor.matches(null));
xor.add(new MCRTestCondition(()->false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> {
throw new UnsupportedOperationException("Should not be checked");
}));
assertFalse(xor.matches(null));
}
}
| 1,720 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/combined/MCRTestCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.condition.MCRAbstractCondition;
import java.util.function.Supplier;
class MCRTestCondition extends MCRAbstractCondition {
Supplier<Boolean> match;
MCRTestCondition(Supplier<Boolean> match) {
this.match = match;
}
@Override
public boolean matches(MCRFactsHolder facts) {
return match.get();
}
}
| 1,196 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROrConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/combined/MCROrConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class MCROrConditionTest {
@Test
void matches() {
MCROrCondition xor = new MCROrCondition();
xor.add(new MCRTestCondition(() -> false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> true));
assertTrue(xor.matches(null));
xor.add(new MCRTestCondition(() -> false));
assertTrue(xor.matches(null));
xor.add(new MCRTestCondition(() -> true));
assertTrue(xor.matches(null));
xor.add(new MCRTestCondition(() -> {
throw new UnsupportedOperationException("Should not be checked");
}));
assertTrue(xor.matches(null));
}
}
| 1,777 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXorConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/combined/MCRXorConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class MCRXorConditionTest {
@Test
void matches() {
MCRXorCondition xor = new MCRXorCondition();
xor.add(new MCRTestCondition(() -> false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> false));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> true));
assertTrue(xor.matches(null));
xor.add(new MCRTestCondition(() -> false));
assertTrue(xor.matches(null));
xor.add(new MCRTestCondition(() -> true));
assertFalse(xor.matches(null));
xor.add(new MCRTestCondition(() -> {
throw new UnsupportedOperationException("Should not be checked");
}));
assertFalse(xor.matches(null));
}
}
| 1,781 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNotConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/combined/MCRNotConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class MCRNotConditionTest {
@Test
void matches() {
MCRNotCondition xor = new MCRNotCondition();
xor.add(new MCRTestCondition(() -> false));
xor.add(new MCRTestCondition(() -> {
throw new UnsupportedOperationException("Should not be checked");
}));
assertTrue(xor.matches(null));
xor.getChildConditions().clear();
xor.add(new MCRTestCondition(() -> true));
xor.add(new MCRTestCondition(() -> {
throw new UnsupportedOperationException("Should not be checked");
}));
assertFalse(xor.matches(null));
}
}
| 1,554 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStateConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRStateConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import static org.mycore.access.facts.condition.fact.MCRFactsTestUtil.hackObjectIntoCache;
import java.util.ArrayList;
import java.util.Map;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
public class MCRStateConditionTest extends MCRJPATestCase {
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
return testProperties;
}
@Override
public void setUp() throws Exception {
super.setUp();
MCRCategoryDAO instance = MCRCategoryDAOFactory.getInstance();
MCRCategoryImpl state = new MCRCategoryImpl();
state.setRootID("state");
state.setRootID("state");
MCRCategoryImpl newState = new MCRCategoryImpl();
newState.setRootID("state");
newState.setCategID("new");
MCRCategoryImpl published = new MCRCategoryImpl();
published.setRootID("state");
published.setCategID("published");
instance.addCategory(null, state);
instance.addCategory(state.getId(), newState);
instance.addCategory(state.getId(), published);
}
@Test
public void testConditionMatch() throws NoSuchFieldException, IllegalAccessException {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRObject object = new MCRObject();
object.getService().setState("published");
MCRObjectID testId = MCRObjectID.getInstance("test_test_00000001");
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
hackObjectIntoCache(object, testId);
holder.add(new MCRObjectIDFact("objid", testId.toString(), testId));
MCRStateCondition mcrStateCondition = new MCRStateCondition();
mcrStateCondition.parse(new Element("state").setText("published"));
Assert.assertTrue("State should be 'published'!", mcrStateCondition.matches(holder));
}
@Test
public void testConditionNotMatch() throws NoSuchFieldException, IllegalAccessException {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRObject object = new MCRObject();
object.getService().setState("published");
MCRObjectID testId = MCRObjectID.getInstance("test_test_00000001");
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
hackObjectIntoCache(object, testId);
holder.add(new MCRObjectIDFact("objid", testId.toString(), testId));
MCRStateCondition mcrStateCondition = new MCRStateCondition();
mcrStateCondition.parse(new Element("state").setText("new"));
Assert.assertFalse("State should not be 'published'!", mcrStateCondition.matches(holder));
}
}
| 4,207 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIPConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRIPConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Collections;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTestCase;
public class MCRIPConditionTest extends MCRTestCase {
@Test
public void testConditionMatch() {
MCRSessionMgr.getCurrentSession().setCurrentIP("111.111.111.111");
MCRIPCondition condition = new MCRIPCondition();
condition.parse(new Element("ip").setText("111.111.111.111"));
MCRFactsHolder facts = new MCRFactsHolder(Collections.emptyList());
Assert.assertTrue("The ip should match", condition.matches(facts));
}
@Test
public void testRangeConditionMatch() {
MCRSessionMgr.getCurrentSession().setCurrentIP("111.111.111.111");
MCRIPCondition condition = new MCRIPCondition();
condition.parse(new Element("ip").setText("111.111.0.0/255.255.0.0"));
MCRFactsHolder facts = new MCRFactsHolder(Collections.emptyList());
Assert.assertTrue("The ip should match", condition.matches(facts));
}
@Test
public void testConditionNotMatch() {
MCRSessionMgr.getCurrentSession().setCurrentIP("222.222.222.222");
MCRIPCondition condition = new MCRIPCondition();
condition.parse(new Element("ip").setText("111.111.111.111"));
MCRFactsHolder facts = new MCRFactsHolder(Collections.emptyList());
Assert.assertFalse("The ip should not match", condition.matches(facts));
}
}
| 2,318 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCreatedByConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRCreatedByConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import static org.mycore.access.facts.condition.fact.MCRFactsTestUtil.hackObjectIntoCache;
import java.util.ArrayList;
import java.util.Map;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRTestCase;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
public class MCRCreatedByConditionTest extends MCRTestCase {
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
return testProperties;
}
@Test
public void testConditionMatch() throws NoSuchFieldException, IllegalAccessException {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRObject object = new MCRObject();
object.getService().addFlag("createdby", "administrator");
MCRObjectID testId = MCRObjectID.getInstance("test_test_00000001");
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
hackObjectIntoCache(object, testId);
holder.add(new MCRObjectIDFact("objid", testId.toString(), testId));
MCRCreatedByCondition createdByCondition = new MCRCreatedByCondition();
createdByCondition.parse(new Element("createdby"));
Assert.assertTrue("current user should be creator", createdByCondition.matches(holder));
}
@Test
public void testNotMatch() throws NoSuchFieldException, IllegalAccessException {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getGuestInstance());
MCRObject object = new MCRObject();
object.getService().addFlag("createdby", "administrator");
MCRObjectID testId = MCRObjectID.getInstance("test_test_00000001");
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
hackObjectIntoCache(object, testId);
holder.add(new MCRObjectIDFact("objid", testId.toString(), testId));
MCRCreatedByCondition createdByCondition = new MCRCreatedByCondition();
createdByCondition.parse(new Element("createdby"));
Assert.assertFalse("current user should not be the creator", createdByCondition.matches(holder));
}
}
| 3,322 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRegExConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRRegExConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.ArrayList;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.common.MCRTestCase;
public class MCRRegExConditionTest extends MCRTestCase {
@Test
public void testConditionMatch() {
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
holder.add(new MCRStringFact("fact1", "a_nice_sample"));
MCRRegExCondition regExCondition = new MCRRegExCondition();
regExCondition.parse(new Element("regex").setAttribute("basefact", "fact1").setText("a_.*_sample"));
Assert.assertTrue("regex should match", regExCondition.matches(holder));
}
@Test
public void testConditionNotMatch() {
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
holder.add(new MCRStringFact("fact1", "no_nice_sample"));
MCRRegExCondition regExCondition = new MCRRegExCondition();
regExCondition.parse(new Element("regex").setAttribute("basefact", "fact1").setText("a_.*_sample"));
Assert.assertFalse("regex should not match", regExCondition.matches(holder));
}
}
| 1,984 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRUserConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.ArrayList;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRTestCase;
public class MCRUserConditionTest extends MCRTestCase {
@Test
public void testConditionMatch() {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
MCRUserCondition userCondition = new MCRUserCondition();
userCondition.parse(new Element("user").setText("administrator"));
Assert.assertTrue("User should be administrator", userCondition.matches(holder));
}
@Test
public void testConditionNotMatch() {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
MCRUserCondition userCondition = new MCRUserCondition();
userCondition.parse(new Element("user").setText("guest"));
Assert.assertFalse("User should not be administrator", userCondition.matches(holder));
}
}
| 2,051 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFactsTestUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRFactsTestUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.lang.reflect.Field;
import org.mycore.access.facts.MCRObjectCacheFactory;
import org.mycore.common.MCRCache;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
public class MCRFactsTestUtil {
public static void hackObjectIntoCache(MCRObject object, MCRObjectID testId) throws NoSuchFieldException,
IllegalAccessException {
MCRObjectCacheFactory instance = MCRObjectCacheFactory.instance();
Field objectCacheField = instance.getClass().getDeclaredField("objectCache");
objectCacheField.setAccessible(true);
MCRCache<MCRObjectID, MCRObject> o = (MCRCache<MCRObjectID, MCRObject>) objectCacheField.get(instance);
objectCacheField.setAccessible(false);
o.put(testId, object);
}
}
| 1,579 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRoleConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRRoleConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.ArrayList;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRTestCase;
public class MCRRoleConditionTest extends MCRTestCase {
@Test
public void testConditionMatch() {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
MCRRoleCondition userCondition = new MCRRoleCondition();
userCondition.parse(new Element("role").setText("editor"));
Assert.assertTrue("User should have editor role", userCondition.matches(holder));
}
@Test
public void testConditionNotMatch() {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getGuestInstance());
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
MCRRoleCondition userCondition = new MCRRoleCondition();
userCondition.parse(new Element("role").setText("editor"));
Assert.assertFalse("User should not have editor role", userCondition.matches(holder));
}
}
| 2,040 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryConditionTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/facts/condition/fact/MCRCategoryConditionTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import static org.mycore.access.facts.condition.fact.MCRFactsTestUtil.hackObjectIntoCache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jdom2.Element;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
public class MCRCategoryConditionTest extends MCRJPATestCase {
MCRCategoryImpl clazz2;
MCRCategoryImpl clazz1;
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> testProperties = super.getTestProperties();
testProperties.put("MCR.Metadata.Type.test", Boolean.TRUE.toString());
return testProperties;
}
@Override
public void setUp() throws Exception {
super.setUp();
MCRCategoryDAO instance = MCRCategoryDAOFactory.getInstance();
MCRCategoryImpl clazz = new MCRCategoryImpl();
clazz.setRootID("clazz");
clazz.setRootID("clazz");
clazz1 = new MCRCategoryImpl();
clazz1.setRootID("clazz");
clazz1.setCategID("clazz1");
clazz2 = new MCRCategoryImpl();
clazz2.setRootID("clazz");
clazz2.setCategID("clazz2");
instance.addCategory(null, clazz);
instance.addCategory(clazz.getId(), clazz1);
instance.addCategory(clazz.getId(), clazz2);
}
@Test
public void testConditionMatch() throws NoSuchFieldException, IllegalAccessException {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRObject object = new MCRObject();
MCRObjectID testId = MCRObjectID.getInstance("test_test_00000001");
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
hackObjectIntoCache(object, testId);
holder.add(new MCRObjectIDFact("objid", testId.toString(), testId));
Collection<MCRCategoryID> collect = Stream.of(clazz1.getId()).collect(Collectors.toList());
MCRCategLinkServiceFactory.getInstance().setLinks(new MCRCategLinkReference(testId), collect);
MCRCategoryCondition categoryCondition = new MCRCategoryCondition();
categoryCondition.parse(new Element("classification").setText("clazz:clazz1"));
Assert.assertTrue("Object should be linked with clazz1",
categoryCondition.matches(holder));
}
@Test
public void testConditionNotMatch() throws NoSuchFieldException, IllegalAccessException {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getSuperUserInstance());
MCRObject object = new MCRObject();
MCRObjectID testId = MCRObjectID.getInstance("test_test_00000001");
MCRFactsHolder holder = new MCRFactsHolder(new ArrayList<>());
hackObjectIntoCache(object, testId);
holder.add(new MCRObjectIDFact("objid", testId.toString(), testId));
Collection<MCRCategoryID> collect = Stream.of(clazz1.getId()).collect(Collectors.toList());
MCRCategLinkServiceFactory.getInstance().setLinks(new MCRCategLinkReference(testId), collect);
MCRCategoryCondition categoryCondition = new MCRCategoryCondition();
categoryCondition.parse(new Element("classification").setText("clazz:clazz2"));
Assert.assertFalse("Object not should be linked with clazz2",
categoryCondition.matches(holder));
}
}
| 4,905 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGroupClauseTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/access/mcrimpl/MCRGroupClauseTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTestCase;
import org.mycore.common.MCRUserInformation;
public class MCRGroupClauseTest extends MCRTestCase {
private static final String INGROUP_NAME = "ingroup";
@Before
public void setUp() throws Exception {
super.setUp();
MCRUserInformation userInfo = new MCRUserInformation() {
@Override
public boolean isUserInRole(String role) {
return INGROUP_NAME.equals(role);
}
@Override
public String getUserID() {
return "junit";
}
@Override
public String getUserAttribute(String attribute) {
// TODO Auto-generated method stub
return null;
}
};
MCRSessionMgr.getCurrentSession().setUserInformation(userInfo);
}
@After
public void tearDown() {
}
@Test
public final void testEvaluate() {
String outGroup = "outgroup";
MCRGroupClause groupClause = new MCRGroupClause(INGROUP_NAME, false);
assertTrue("Did not accept " + INGROUP_NAME, groupClause.evaluate(null));
groupClause = new MCRGroupClause(outGroup, true);
assertTrue("Did not accept " + outGroup, groupClause.evaluate(null));
}
}
| 2,220 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTransactionableRunnableTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/util/concurrent/MCRTransactionableRunnableTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTestCase;
public class MCRTransactionableRunnableTest extends MCRTestCase {
private static Logger LOGGER = LogManager.getLogger();
@Test
public void run() {
// with session
MCRSession session = MCRSessionMgr.getCurrentSession();
String sessionID = session.getID();
TestRunnable testRunnable = new TestRunnable();
MCRTransactionableRunnable transactionableRunnable = new MCRTransactionableRunnable(testRunnable, session);
transactionableRunnable.run();
assertTrue(testRunnable.isExecuted());
assertEquals(sessionID, testRunnable.getSessionContextID());
session.close();
// without session
transactionableRunnable = new MCRTransactionableRunnable(testRunnable);
transactionableRunnable.run();
assertTrue(testRunnable.isExecuted());
assertNotEquals(sessionID, testRunnable.getSessionContextID());
assertFalse(MCRSessionMgr.hasCurrentSession());
}
private class TestRunnable implements Runnable {
private boolean executed;
private String sessionContextID;
@Override
public void run() {
try {
Thread.sleep(100);
sessionContextID = MCRSessionMgr.getCurrentSession().getID();
executed = true;
LOGGER.info("thread executed");
} catch (InterruptedException e) {
LOGGER.error("thread interrupted", e);
}
}
public String getSessionContextID() {
return sessionContextID;
}
public boolean isExecuted() {
return executed;
}
}
}
| 2,839 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTransactionableCallableTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/util/concurrent/MCRTransactionableCallableTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.concurrent.Callable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTestCase;
public class MCRTransactionableCallableTest extends MCRTestCase {
private static Logger LOGGER = LogManager.getLogger();
@Test
public void run() {
// with session
MCRSession session = MCRSessionMgr.getCurrentSession();
String sessionID = session.getID();
TestCallable testCallable = new TestCallable();
MCRTransactionableCallable<Boolean> transactionableRunnable = new MCRTransactionableCallable<>(testCallable,
session);
try {
assertTrue(transactionableRunnable.call());
} catch (Exception e) {
fail(e.getMessage());
}
assertEquals(sessionID, testCallable.getSessionContextID());
session.close();
// without session
transactionableRunnable = new MCRTransactionableCallable<>(testCallable);
try {
assertTrue(transactionableRunnable.call());
} catch (Exception e) {
fail(e.getMessage());
}
assertNotEquals(sessionID, testCallable.getSessionContextID());
assertFalse(MCRSessionMgr.hasCurrentSession());
}
private class TestCallable implements Callable<Boolean> {
private String sessionContextID;
@Override
public Boolean call() throws Exception {
Thread.sleep(100);
sessionContextID = MCRSessionMgr.getCurrentSession().getID();
LOGGER.info("thread executed");
return true;
}
public String getSessionContextID() {
return sessionContextID;
}
}
}
| 2,823 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPrioritySupplierTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/util/concurrent/MCRPrioritySupplierTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.mycore.util.concurrent.processing.MCRProcessableFactory;
public class MCRPrioritySupplierTest {
private static Logger LOGGER = LogManager.getLogger(MCRPrioritySupplierTest.class);
static int[] EXCPECTED = { 1, 10, 5, 4, 3, 2 };
@Test
public void priortiy() throws Exception {
ThreadPoolExecutor es = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
MCRProcessableFactory.newPriorityBlockingQueue());
TaskConsumer callback = new TaskConsumer();
new MCRPrioritySupplier<>(new Task(1), 1).runAsync(es).thenAccept(callback);
new MCRPrioritySupplier<>(new Task(2), 2).runAsync(es).thenAccept(callback);
new MCRPrioritySupplier<>(new Task(3), 3).runAsync(es).thenAccept(callback);
new MCRPrioritySupplier<>(new Task(4), 4).runAsync(es).thenAccept(callback);
new MCRPrioritySupplier<>(new Task(5), 5).runAsync(es).thenAccept(callback);
new MCRPrioritySupplier<>(new Task(10), 10).runAsync(es).thenAccept(callback);
es.awaitTermination(1, TimeUnit.SECONDS);
assertEquals("all threads should be executed after termination", 6, TaskConsumer.COUNTER);
assertArrayEquals("threads should be executed in order: " + Arrays.toString(EXCPECTED), EXCPECTED,
TaskConsumer.ORDER);
}
private static class TaskConsumer implements Consumer<Integer> {
static int COUNTER = 0;
static int[] ORDER = { 0, 0, 0, 0, 0, 0 };
@Override
public void accept(Integer value) {
ORDER[COUNTER++] = value;
}
}
private static class Task implements Supplier<Integer> {
private int id;
Task(Integer id) {
this.id = id;
}
@Override
public Integer get() {
try {
LOGGER.info("Executing task {}", id);
Thread.sleep(100);
return id;
} catch (Exception exc) {
throw new RuntimeException(exc);
}
}
}
}
| 3,199 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDecoratorTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/util/concurrent/MCRDecoratorTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Optional;
import org.junit.Test;
public class MCRDecoratorTest {
@Test
public void isDecorated() {
Container container = new Container("base");
TestDecorator a = new TestDecorator(container, "a");
assertTrue("a should be decorated", MCRDecorator.isDecorated(a));
assertFalse("container does not implement the MCRDecorator interface", MCRDecorator.isDecorated(container));
}
@Test
public void get() {
Container container = new Container("base");
TestDecorator a = new TestDecorator(container, "a");
TestDecorator b = new TestDecorator(a, "b");
Optional<Container> resolved = MCRDecorator.get(b);
assertTrue(resolved.isPresent());
assertEquals(a.getValue(), resolved.map(Container::getValue).orElse("empty"));
assertFalse(MCRDecorator.get(container).isPresent());
}
@Test
public void resolve() {
Container container = new Container("base");
TestDecorator a = new TestDecorator(container, "a");
TestDecorator b = new TestDecorator(a, "b");
Optional<Container> resolved = MCRDecorator.resolve(b);
assertTrue(resolved.isPresent());
assertEquals(container.getValue(), resolved.map(Container::getValue).orElse("empty"));
assertFalse(MCRDecorator.resolve(container).isPresent());
}
private static class TestDecorator extends Container implements MCRDecorator<Container> {
private Container container;
TestDecorator(Container container, String value) {
super(value);
this.container = container;
}
@Override
public Container get() {
return this.container;
}
}
private static class Container {
private String value;
Container(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
| 2,877 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPoolTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/util/concurrent/MCRPoolTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.junit.Assert;
import org.junit.Test;
public class MCRPoolTest {
@Test
public void acquire() throws InterruptedException {
int size = Math.max(Runtime.getRuntime().availableProcessors() / 4, 2);
int runs = size * 10;
MCRPool<ResourceHelper> resourcePool = new MCRPool<>(size, ResourceHelper::new);
final int beforeCounter = ResourceHelper.counter.get();
Assert.assertNotNull(resourcePool.acquire());
Assert.assertEquals(beforeCounter + 1, ResourceHelper.counter.get());
ResourceHelper.counter.set(0);
IntStream.range(0, runs)
.parallel()
.mapToObj(i -> CompletableFuture.supplyAsync(() -> {
try {
return resourcePool.acquire();
} catch (InterruptedException e) {
throw new CompletionException(e);
}
}))
.map(f -> f.thenApply(r -> {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new CompletionException(e);
}
return r;
}))
.map(f -> f.thenAccept(resourcePool::release))
.forEach(CompletableFuture::join);
Assert.assertTrue(ResourceHelper.counter.get() <= size);
}
private static class ResourceHelper {
static AtomicInteger counter = new AtomicInteger();
ResourceHelper() {
counter.incrementAndGet();
}
}
}
| 2,488 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableSupplierTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/util/concurrent/processing/MCRProcessableSupplierTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent.processing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.processing.MCRAbstractProgressable;
import org.mycore.common.processing.MCRProcessableStatus;
import org.mycore.common.processing.MCRProgressable;
import org.mycore.common.processing.MCRProgressableListener;
public class MCRProcessableSupplierTest extends MCRTestCase {
private static Logger LOGGER = LogManager.getLogger();
private static int PROGRESS_LISTENER_COUNTER = 0;
private static int STATUS_LISTENER_COUNTER = 0;
@Test
public void submit() throws Exception {
ExecutorService es = Executors.newSingleThreadExecutor();
MCRProcessableExecutor pes = MCRProcessableFactory.newPool(es);
MCRProcessableSupplier<?> supplier = pes.submit(new TestRunnable(), 0);
// STATUS LISTENER
STATUS_LISTENER_COUNTER = 0;
supplier.addStatusListener((source, oldStatus, newStatus) -> STATUS_LISTENER_COUNTER++);
// PROGRESS LISTENER
PROGRESS_LISTENER_COUNTER = 0;
supplier.addProgressListener(new MCRProgressableListener() {
@Override
public void onProgressTextChange(MCRProgressable source, String oldProgressText, String newProgressText) {
PROGRESS_LISTENER_COUNTER++;
}
@Override
public void onProgressChange(MCRProgressable source, Integer oldProgress, Integer newProgress) {
PROGRESS_LISTENER_COUNTER++;
}
});
// await the task is executed
supplier.getFuture().get();
// TESTS
assertEquals("the processable should be finished successful", MCRProcessableStatus.successful,
supplier.getStatus());
assertEquals("the progressable should be at 100", Integer.valueOf(100), supplier.getProgress());
assertEquals("end", supplier.getProgressText());
assertEquals("there shouldn't be any error", null, supplier.getError());
assertNotEquals("there should be a start time", null, supplier.getStartTime());
assertNotEquals("there should be an end time", null, supplier.getEndTime());
assertNotEquals(null, supplier.took());
assertNotEquals("the status listener wasn't called", 0, STATUS_LISTENER_COUNTER);
assertNotEquals("the progressable listener wasn't called", 0, PROGRESS_LISTENER_COUNTER);
es.shutdown();
es.awaitTermination(10, TimeUnit.SECONDS);
}
private static class TestRunnable extends MCRAbstractProgressable implements Runnable {
@Override
public void run() {
setProgress(0);
setProgressText("start");
try {
Thread.sleep(100);
setProgress(100);
setProgressText("end");
} catch (InterruptedException e) {
LOGGER.warn("test thread interrupted", e);
}
}
}
}
| 4,016 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableFactoryTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/test/java/org/mycore/util/concurrent/processing/MCRProcessableFactoryTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent.processing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.common.processing.MCRProcessableCollection;
import org.mycore.common.processing.MCRProcessableDefaultCollection;
import org.mycore.common.processing.MCRProcessableRegistry;
import org.mycore.common.processing.MCRProcessableStatus;
import org.mycore.common.processing.impl.MCRCentralProcessableRegistry;
public class MCRProcessableFactoryTest extends MCRTestCase {
private static Logger LOGGER = LogManager.getLogger();
@Test
public void newPool() throws Exception {
MCRProcessableRegistry registry = new MCRCentralProcessableRegistry();
MCRProcessableCollection collection = new MCRProcessableDefaultCollection("test");
registry.register(collection);
int nThreads = 3;
ExecutorService es = Executors.newFixedThreadPool(nThreads);
MCRProcessableExecutor pes = MCRProcessableFactory.newPool(es, collection);
assertEquals("No runnables should be queued right now.", 0, collection.stream().count());
assertEquals("Only the 'test' collection should be registered.", 1, registry.stream().count());
Semaphore semaphore = new Semaphore(nThreads);
semaphore.acquire(nThreads); //lock threads until ready
MCRProcessableSupplier<?> sup1 = pes.submit(sleepyThread(semaphore));
MCRProcessableSupplier<?> sup2 = pes.submit(sleepyThread(semaphore));
MCRProcessableSupplier<?> sup3 = pes.submit(sleepyThread(semaphore));
MCRProcessableStatus s1 = sup1.getStatus();
MCRProcessableStatus s2 = sup2.getStatus();
MCRProcessableStatus s3 = sup3.getStatus();
String msgPrefix = "Job should be created or in processing: ";
assertTrue(msgPrefix + s1, MCRProcessableStatus.processing == s1 || MCRProcessableStatus.created == s1);
assertTrue(msgPrefix + s2, MCRProcessableStatus.processing == s2 || MCRProcessableStatus.created == s2);
assertTrue(msgPrefix + s3, MCRProcessableStatus.processing == s3 || MCRProcessableStatus.created == s3);
assertEquals(3, collection.stream().count());
semaphore.release(nThreads); //go
CompletableFuture.allOf(sup1.getFuture(), sup2.getFuture(), sup3.getFuture()).get();
assertEquals(MCRProcessableStatus.successful, sup1.getStatus());
assertEquals(MCRProcessableStatus.successful, sup2.getStatus());
assertEquals(MCRProcessableStatus.successful, sup3.getStatus());
es.shutdown();
es.awaitTermination(10, TimeUnit.SECONDS);
}
private Runnable sleepyThread(Semaphore semaphore) {
return () -> {
try {
semaphore.acquire();
} catch (InterruptedException e) {
LOGGER.warn("test thread interrupted", e);
} finally {
semaphore.release();
}
};
}
}
| 4,061 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDDate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRObjectIDDate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.Date;
import io.swagger.v3.oas.annotations.media.Schema;
public interface MCRObjectIDDate {
@Schema(description = "MCRObjectID as String in form {project}_{type}_{int32}", example = "mir_mods_00004711")
String getId();
Date getLastModified();
}
| 1,044 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultXMLMetadataManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultXMLMetadataManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationBase;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.ifs2.MCRMetadataStore;
import org.mycore.datamodel.ifs2.MCRMetadataVersion;
import org.mycore.datamodel.ifs2.MCRObjectIDFileSystemDate;
import org.mycore.datamodel.ifs2.MCRStore;
import org.mycore.datamodel.ifs2.MCRStoreCenter;
import org.mycore.datamodel.ifs2.MCRStoreManager;
import org.mycore.datamodel.ifs2.MCRStoredMetadata;
import org.mycore.datamodel.ifs2.MCRVersionedMetadata;
import org.mycore.datamodel.ifs2.MCRVersioningMetadataStore;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.history.MCRMetadataHistoryManager;
/**
* Manages persistence of MCRObject and MCRDerivate xml metadata.
* Provides methods to create, retrieve, update and delete object metadata
* using IFS2 MCRMetadataStore instances.
*
* For configuration, at least the following properties must be set:
*
* MCR.Metadata.Store.BaseDir=/path/to/metadata/dir
* MCR.Metadata.Store.SVNBase=file:///path/to/local/svndir/
*
* Both directories will be created if they do not exist yet.
* For each project and type, a subdirectory will be created,
* for example %MCR.Metadata.Store.BaseDir%/DocPortal/document/.
*
* The default IFS2 store is MCRVersioningMetadataStore, which
* versions metadata using SVN in local repositories below SVNBase.
* If you do not want versioning and would like to have better
* performance, change the following property to
*
* MCR.Metadata.Store.DefaultClass=org.mycore.datamodel.ifs2.MCRMetadataStore
*
* It is also possible to change individual properties per project and object type
* and overwrite the defaults, for example
*
* MCR.IFS2.Store.Class=org.mycore.datamodel.ifs2.MCRVersioningMetadataStore
* MCR.IFS2.Store.SVNRepositoryURL=file:///use/other/location/for/document/versions/
* MCR.IFS2.Store.SlotLayout=2-2-2-2
*
* See documentation of MCRStore and MCRMetadataStore for details.
*
* @author Frank Lützenkirchen
* @author Jens Kupferschmidt
* @author Thomas Scheffler (yagee)
*/
public class MCRDefaultXMLMetadataManager implements MCRXMLMetadataManagerAdapter {
private static final Logger LOGGER = LogManager.getLogger();
private static final String DEFAULT_SVN_DIRECTORY_NAME = "versions-metadata";
/** The singleton */
private static MCRDefaultXMLMetadataManager SINGLETON;
private HashSet<String> createdStores;
/**
* The default IFS2 Metadata store class to use, set by MCR.Metadata.Store.DefaultClass
*/
@SuppressWarnings("rawtypes")
private Class defaultClass;
/**
* The default subdirectory slot layout for IFS2 metadata store, is 4-2-2 for 8-digit IDs,
* that means DocPortal_document_0000001 will be stored in the file
* DocPortal/document/0000/00/DocPortal_document_00000001.xml
*/
private String defaultLayout;
/**
* The base directory for all IFS2 metadata stores used, set by MCR.Metadata.Store.BaseDir
*/
private Path basePath;
/**
* The local base directory for IFS2 versioned metadata using SVN, set URI by MCR.Metadata.Store.SVNBase
*/
private Path svnPath;
/**
* The local file:// uri of all SVN versioned metadata, set URI by MCR.Metadata.Store.SVNBase
*/
private URI svnBase;
protected MCRDefaultXMLMetadataManager() {
this.createdStores = new HashSet<>();
reload();
}
/** Returns the singleton */
public static synchronized MCRDefaultXMLMetadataManager instance() {
if (SINGLETON == null) {
SINGLETON = new MCRDefaultXMLMetadataManager();
}
return SINGLETON;
}
public synchronized void reload() {
String pattern = MCRConfiguration2.getString("MCR.Metadata.ObjectID.NumberPattern").orElse("0000000000");
defaultLayout = pattern.length() - 4 + "-2-2";
String base = MCRConfiguration2.getStringOrThrow("MCR.Metadata.Store.BaseDir");
basePath = Paths.get(base);
checkPath(basePath, "base");
defaultClass = MCRConfiguration2.<MCRVersioningMetadataStore>getClass("MCR.Metadata.Store.DefaultClass")
.orElse(MCRVersioningMetadataStore.class);
if (MCRVersioningMetadataStore.class.isAssignableFrom(defaultClass)) {
Optional<String> svnBaseOpt = MCRConfiguration2.getString("MCR.Metadata.Store.SVNBase");
if (svnBaseOpt.isEmpty()) {
svnPath = Paths.get(MCRConfiguration2.getStringOrThrow("MCR.datadir"))
.resolve(DEFAULT_SVN_DIRECTORY_NAME);
checkPath(svnPath, "svn");
svnBase = svnPath.toUri();
} else {
try {
String svnBaseValue = svnBaseOpt.get();
if (!svnBaseValue.endsWith("/")) {
svnBaseValue += '/';
}
svnBase = new URI(svnBaseValue);
LOGGER.info("SVN Base: {}", svnBase);
if (svnBase.getScheme() == null) {
String workingDirectory = (new File(".")).getAbsolutePath();
URI root = new File(MCRConfiguration2.getString("MCR.datadir").orElse(workingDirectory))
.toURI();
URI resolved = root.resolve(svnBase);
LOGGER.warn("Resolved {} to {}", svnBase, resolved);
svnBase = resolved;
}
} catch (URISyntaxException ex) {
String msg = "Syntax error in MCR.Metadata.Store.SVNBase property: " + svnBase;
throw new MCRConfigurationException(msg, ex);
}
if (svnBase.getScheme().equals("file")) {
svnPath = Paths.get(svnBase);
checkPath(svnPath, "svn");
}
}
}
closeCreatedStores();
}
private synchronized void closeCreatedStores() {
for (String storeId : createdStores) {
MCRStoreCenter.instance().removeStore(storeId);
}
createdStores.clear();
}
/**
* Checks the directory configured exists and is readable and writable, or creates it
* if it does not exist yet.
*
* @param path the path to check
* @param type metadata store type
*/
private void checkPath(Path path, String type) {
if (!Files.exists(path)) {
try {
if (!Files.exists(Files.createDirectories(path))) {
throw new MCRConfigurationException(
"The metadata store " + type + " directory " + path.toAbsolutePath() + " does not exist.");
}
} catch (Exception ex) {
String msg = "Exception while creating metadata store " + type + " directory " + path.toAbsolutePath();
throw new MCRConfigurationException(msg, ex);
}
} else {
if (!Files.isDirectory(path)) {
throw new MCRConfigurationException(
"Metadata store " + type + " " + path.toAbsolutePath() + " is a file, not a directory");
}
if (!Files.isReadable(path)) {
throw new MCRConfigurationException(
"Metadata store " + type + " directory " + path.toAbsolutePath() + " is not readable");
}
if (!Files.isWritable(path)) {
throw new MCRConfigurationException(
"Metadata store " + type + " directory " + path.toAbsolutePath() + " is not writeable");
}
}
}
/**
* Returns IFS2 MCRMetadataStore for the given MCRObjectID base, which is {project}_{type}
*
* @param base the MCRObjectID base, e.g. DocPortal_document
*/
private MCRMetadataStore getStore(String base) {
String[] split = base.split("_");
return getStore(split[0], split[1], false);
}
/**
* Returns IFS2 MCRMetadataStore for the given MCRObjectID base, which is {project}_{type}
*
* @param base the MCRObjectID base, e.g. DocPortal_document
* @param readOnly If readOnly, the store will not be created if it does not exist yet. Instead an exception
* is thrown.
* @return the metadata store
*/
private MCRMetadataStore getStore(String base, boolean readOnly) {
String[] split = base.split("_");
return getStore(split[0], split[1], readOnly);
}
/**
* Returns IFS2 MCRMetadataStore used to store metadata of the given MCRObjectID
*
* @param mcrid the mycore object identifier
* @param readOnly If readOnly, the store will not be created if it does not exist yet. Instead an exception
* is thrown.
* @return the metadata store
*/
private MCRMetadataStore getStore(MCRObjectID mcrid, boolean readOnly) {
return getStore(mcrid.getProjectId(), mcrid.getTypeId(), readOnly);
}
/**
* Returns IFS2 MCRMetadataStore for the given project and object type
*
* @param project the project, e.g. DocPortal
* @param type the object type, e.g. document
* @param readOnly if readOnly, this method will throw an exception if the store does not exist's yet
* @return the metadata store
*/
private MCRMetadataStore getStore(String project, String type, boolean readOnly) {
String projectType = getStoryKey(project, type);
String prefix = "MCR.IFS2.Store." + projectType + ".";
String forceXML = MCRConfiguration2.getString(prefix + "ForceXML").orElse(null);
if (forceXML == null) {
synchronized (this) {
forceXML = MCRConfiguration2.getString(prefix + "ForceXML").orElse(null);
if (forceXML == null) {
try {
setupStore(project, type, prefix, readOnly);
} catch (ReflectiveOperationException e) {
throw new MCRPersistenceException(
new MessageFormat("Could not instantiate store for project {0} and object type {1}.",
Locale.ROOT).format(new Object[] { project, type }),
e);
}
}
}
}
MCRMetadataStore store = MCRStoreManager.getStore(projectType);
if (store == null) {
throw new MCRPersistenceException(
new MessageFormat("Metadata store for project {0} and object type {1} is unconfigured.", Locale.ROOT)
.format(new Object[] { project, type }));
}
return store;
}
public void verifyStore(String base) {
MCRMetadataStore store = getStore(base);
if (store instanceof MCRVersioningMetadataStore versioningMetadataStore) {
LOGGER.info("Verifying SVN history of {}.", base);
versioningMetadataStore.verify();
} else {
LOGGER.warn("Cannot verify unversioned store {}!", base);
}
}
@SuppressWarnings("unchecked")
private void setupStore(String project, String objectType, String configPrefix, boolean readOnly)
throws ReflectiveOperationException {
String baseID = getStoryKey(project, objectType);
Class<? extends MCRStore> clazz = MCRConfiguration2.<MCRStore>getClass(configPrefix + "Class")
.orElseGet(() -> {
MCRConfiguration2.set(configPrefix + "Class", defaultClass.getName());
return defaultClass;
});
if (MCRVersioningMetadataStore.class.isAssignableFrom(clazz)) {
String property = configPrefix + "SVNRepositoryURL";
String svnURL = MCRConfiguration2.getString(property).orElse(null);
if (svnURL == null) {
String relativeURI = new MessageFormat("{0}/{1}/", Locale.ROOT)
.format(new Object[] { project, objectType });
URI repURI = svnBase.resolve(relativeURI);
LOGGER.info("Resolved {} to {} for {}", relativeURI, repURI.toASCIIString(), property);
MCRConfiguration2.set(property, repURI.toASCIIString());
checkAndCreateDirectory(svnPath.resolve(project), project, objectType, configPrefix, readOnly);
}
}
Path typePath = basePath.resolve(project).resolve(objectType);
checkAndCreateDirectory(typePath, project, objectType, configPrefix, readOnly);
String slotLayout = MCRConfiguration2.getString(configPrefix + "SlotLayout").orElse(null);
if (slotLayout == null) {
MCRConfiguration2.set(configPrefix + "SlotLayout", defaultLayout);
}
MCRConfiguration2.set(configPrefix + "BaseDir", typePath.toAbsolutePath().toString());
MCRConfiguration2.set(configPrefix + "ForceXML", String.valueOf(true));
String value = Objects.equals(objectType, "derivate") ? "mycorederivate" : "mycoreobject";
MCRConfiguration2.set(configPrefix + "ForceDocType", value);
createdStores.add(baseID);
MCRStoreManager.createStore(baseID, clazz);
}
private void checkAndCreateDirectory(Path path, String project, String objectType, String configPrefix,
boolean readOnly) {
if (Files.exists(path)) {
return;
}
if (readOnly) {
throw new MCRPersistenceException(String.format(Locale.ENGLISH,
"Path does not exists ''%s'' to set up store for project ''%s'' and objectType ''%s'' "
+ "and config prefix ''%s''. We are not willing to create it for an read only operation.",
path.toAbsolutePath(), project, objectType, configPrefix));
}
try {
if (!Files.exists(Files.createDirectories(path))) {
throw new FileNotFoundException(path.toAbsolutePath() + " does not exists.");
}
} catch (Exception e) {
throw new MCRPersistenceException(String.format(Locale.ENGLISH,
"Couldn'e create directory ''%s'' to set up store for project ''%s'' and objectType ''%s'' "
+ "and config prefix ''%s''",
path.toAbsolutePath(), project, objectType, configPrefix));
}
}
private String getStoryKey(String project, String objectType) {
return project + "_" + objectType;
}
public void create(MCRObjectID mcrid, MCRContent xml, Date lastModified)
throws MCRPersistenceException {
try {
MCRStoredMetadata sm = getStore(mcrid, false).create(xml, mcrid.getNumberAsInteger());
sm.setLastModified(lastModified);
MCRConfigurationBase.systemModified();
} catch (Exception exc) {
throw new MCRPersistenceException("Error while storing object: " + mcrid, exc);
}
}
public void delete(MCRObjectID mcrid) throws MCRPersistenceException {
try {
getStore(mcrid, true).delete(mcrid.getNumberAsInteger());
MCRConfigurationBase.systemModified();
} catch (Exception exc) {
throw new MCRPersistenceException("Error while deleting object: " + mcrid, exc);
}
}
public void update(MCRObjectID mcrid, MCRContent xml, Date lastModified)
throws MCRPersistenceException {
if (!exists(mcrid)) {
throw new MCRPersistenceException("Object to update does not exist: " + mcrid);
}
try {
MCRStoredMetadata sm = getStore(mcrid, false).retrieve(mcrid.getNumberAsInteger());
sm.update(xml);
sm.setLastModified(lastModified);
MCRConfigurationBase.systemModified();
} catch (Exception exc) {
throw new MCRPersistenceException("Unable to update object " + mcrid, exc);
}
}
public MCRContent retrieveContent(MCRObjectID mcrid) throws IOException {
MCRContent metadata;
MCRStoredMetadata storedMetadata = retrieveStoredMetadata(mcrid);
if (storedMetadata == null || storedMetadata.isDeleted()) {
return null;
}
metadata = storedMetadata.getMetadata();
return metadata;
}
public MCRContent retrieveContent(MCRObjectID mcrid, String revision) throws IOException {
LOGGER.info("Getting object {} in revision {}", mcrid, revision);
MCRMetadataVersion version = getMetadataVersion(mcrid, Long.parseLong(revision));
if (version != null) {
MCRContent content = version.retrieve();
try {
Document doc = content.asXML();
doc.getRootElement().setAttribute("rev", version.getRevision());
return new MCRJDOMContent(doc);
} catch (JDOMException e) {
throw new MCRPersistenceException("Could not parse XML from default store", e);
}
}
return null;
}
/**
* Returns the {@link MCRMetadataVersion} of the given id and revision.
*
* @param mcrId
* the id of the object to be retrieved
* @param rev
* the revision to be returned, specify -1 if you want to
* retrieve the latest revision (includes deleted objects also)
* @return a {@link MCRMetadataVersion} representing the {@link MCRObject} of the
* given revision or <code>null</code> if there is no such object
* with the given revision
* @throws IOException version metadata couldn't be retrieved due an i/o error
*/
private MCRMetadataVersion getMetadataVersion(MCRObjectID mcrId, long rev) throws IOException {
MCRVersionedMetadata versionedMetaData = getVersionedMetaData(mcrId);
if (versionedMetaData == null) {
return null;
}
return versionedMetaData.getRevision(rev);
}
public List<MCRMetadataVersion> listRevisions(MCRObjectID id) throws IOException {
MCRVersionedMetadata vm = getVersionedMetaData(id);
if (vm == null) {
return null;
}
return vm.listVersions();
}
private MCRVersionedMetadata getVersionedMetaData(MCRObjectID id) throws IOException {
if (id == null) {
return null;
}
MCRMetadataStore metadataStore = getStore(id, true);
if (!(metadataStore instanceof MCRVersioningMetadataStore verStore)) {
return null;
}
return verStore.retrieve(id.getNumberAsInteger());
}
/**
* Retrieves stored metadata xml as IFS2 metadata object.
*
* @param mcrid the MCRObjectID
*/
private MCRStoredMetadata retrieveStoredMetadata(MCRObjectID mcrid) throws IOException {
return getStore(mcrid, true).retrieve(mcrid.getNumberAsInteger());
}
public int getHighestStoredID(String project, String type) {
MCRMetadataStore store;
try {
store = getStore(project, type, true);
} catch (MCRPersistenceException persistenceException) {
// store does not exists -> return 0
return 0;
}
int highestStoredID = store.getHighestStoredID();
//fixes MCR-1534 (IDs once deleted should never be used again)
return Math.max(highestStoredID, MCRMetadataHistoryManager.getHighestStoredID(project, type)
.map(MCRObjectID::getNumberAsInteger)
.orElse(0));
}
public boolean exists(MCRObjectID mcrid) throws MCRPersistenceException {
try {
if (mcrid == null) {
return false;
}
MCRMetadataStore store;
try {
store = getStore(mcrid, true);
} catch (MCRPersistenceException persistenceException) {
// the store couldn't be retrieved, the object does not exists
return false;
}
return store.exists(mcrid.getNumberAsInteger());
} catch (Exception exc) {
throw new MCRPersistenceException("Unable to check if object exists " + mcrid, exc);
}
}
public List<String> listIDsForBase(String base) {
MCRMetadataStore store;
try {
store = getStore(base, true);
} catch (MCRPersistenceException e) {
LOGGER.warn("Store for '{}' does not exist.", base);
return Collections.emptyList();
}
List<String> list = new ArrayList<>();
Iterator<Integer> it = store.listIDs(MCRStore.ASCENDING);
String[] idParts = MCRObjectID.getIDParts(base);
while (it.hasNext()) {
list.add(MCRObjectID.formatID(idParts[0], idParts[1], it.next()));
}
return list;
}
public List<String> listIDsOfType(String type) {
try (Stream<Path> streamBasePath = list(basePath)) {
return streamBasePath.flatMap(projectPath -> {
final String project = projectPath.getFileName().toString();
return list(projectPath).flatMap(typePath -> {
if (type.equals(typePath.getFileName().toString())) {
final String base = getStoryKey(project, type);
return listIDsForBase(base).stream();
}
return Stream.empty();
});
}).collect(Collectors.toList());
}
}
public List<String> listIDs() {
try (Stream<Path> streamBasePath = list(basePath)) {
return streamBasePath.flatMap(projectPath -> {
final String project = projectPath.getFileName().toString();
return list(projectPath).flatMap(typePath -> {
final String type = typePath.getFileName().toString();
final String base = getStoryKey(project, type);
return listIDsForBase(base).stream();
});
}).collect(Collectors.toList());
}
}
public Collection<String> getObjectTypes() {
try (Stream<Path> streamBasePath = list(basePath)) {
return streamBasePath.flatMap(this::list)
.map(Path::getFileName)
.map(Path::toString)
.filter(MCRObjectID::isValidType)
.distinct()
.collect(Collectors.toSet());
}
}
public Collection<String> getObjectBaseIds() {
try (Stream<Path> streamBasePath = list(basePath)) {
return streamBasePath.flatMap(this::list)
.filter(p -> MCRObjectID.isValidType(p.getFileName().toString()))
.map(p -> p.getParent().getFileName() + "_" + p.getFileName())
.collect(Collectors.toSet());
}
}
/**
* Returns the entries of the given path. Throws a MCRException if an I/O-Exceptions occur.
*
* @return stream of project directories
*/
private Stream<Path> list(Path path) {
try {
return Files.list(path);
} catch (IOException ioException) {
throw new MCRPersistenceException(
"unable to list files of IFS2 metadata directory " + path.toAbsolutePath(), ioException);
}
}
public List<MCRObjectIDDate> retrieveObjectDates(List<String> ids) throws IOException {
List<MCRObjectIDDate> objidlist = new ArrayList<>(ids.size());
for (String id : ids) {
MCRStoredMetadata sm = this.retrieveStoredMetadata(MCRObjectID.getInstance(id));
objidlist.add(new MCRObjectIDFileSystemDate(sm, id));
}
return objidlist;
}
public long getLastModified(MCRObjectID id) throws IOException {
MCRMetadataStore store = getStore(id, true);
MCRStoredMetadata metadata = store.retrieve(id.getNumberAsInteger());
if (metadata != null) {
return metadata.getLastModified().getTime();
}
return -1;
}
public MCRCache.ModifiedHandle getLastModifiedHandle(final MCRObjectID id, final long expire, TimeUnit unit) {
return new StoreModifiedHandle(this, id, expire, unit);
}
private static final class StoreModifiedHandle implements MCRCache.ModifiedHandle {
private final MCRDefaultXMLMetadataManager mm;
private final long expire;
private final MCRObjectID id;
private StoreModifiedHandle(MCRDefaultXMLMetadataManager mm, MCRObjectID id, long time, TimeUnit unit) {
this.mm = mm;
this.expire = unit.toMillis(time);
this.id = id;
}
@Override
public long getCheckPeriod() {
return expire;
}
@Override
public long getLastModified() throws IOException {
return mm.getLastModified(id);
}
}
}
| 26,800 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMarkManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRMarkManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.mycore.common.events.MCREventHandler;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* Experimental class to improve performance on delete and import operations.
* You can mark object's as "will be deleted" or "will be imported". You can
* use this information on {@link MCREventHandler}'s to exclude those
* marked objects from operations which makes no sense.
*
* <h2>
* Current delete behavior:
* </h2>
* <ol>
* <li>An user delete's a parent object with 500 children.</li>
* <li>MyCoRe tries to delete the parent, but first, it has to delete all children.</li>
* <li>MyCoRe runs through each child and deletes it.</li>
* <li><b>BUT</b> after the deletion of <b>ONE</b> child, the parent object will be updated.</li>
* <li>This results in updating the parent 500 times, before its actually deleted.</li>
* </ol>
*
* <p>
* What this class tries to solve:<br>
* We mark the parent as "will be deleted". When a child is deleted, and the EventHandler tries
* to removed the child from its parent, the parent will not be updated because its "marked as
* deleted".
* </p>
*
* <h2>
* Current import behavior:
* </h2>
*
* <ol>
* <li>An import is started with a bunch of hierarchic objects.</li>
* <li>MyCoRe imports all the objects and does a "create" update.</li>
* <li><b>BUT</b> for each object created the parent is updated again (because a child was added)!</li>
* <li>This results in unnecessary updates.</li>
* </ol>
*
* <p>
* What this class tries to solve:<br>
* We mark all objects as "will be imported". On import, we ignore all solr index call for
* those objects. After the import, we delete all marks and do an solr import for all
* objects at once.
* </p>
*
* TODO: check side effects
*
* @author Matthias Eichner
*/
public class MCRMarkManager {
private static volatile MCRMarkManager INSTANCE = null;
public enum Operation {
DELETE, IMPORT
}
private Map<MCRObjectID, Operation> marks;
private MCRMarkManager() {
this.marks = new ConcurrentHashMap<>();
}
/**
* Returns the instance to the singleton {@link MCRMarkManager}.
*
* @return instance of {@link MCRMarkManager}
*/
public static MCRMarkManager instance() {
if (INSTANCE == null) {
// make it thread safe
synchronized (MCRMarkManager.class) {
if (INSTANCE == null) {
INSTANCE = new MCRMarkManager();
}
}
}
return INSTANCE;
}
/**
* Marks a single object with the given operation.
*
* @param mcrId the mycore object identifier
* @param operation the operation
* @return the previous Operation associated with the mycore identifier or null
*/
public Operation mark(MCRObjectID mcrId, Operation operation) {
return this.marks.put(mcrId, operation);
}
/**
* Removes the current mark for the given mycore identifier.
*
* @param mcrId the object where the mark should be removed
*/
public void remove(MCRObjectID mcrId) {
this.marks.remove(mcrId);
}
/**
* Checks if the object is marked.
*
* @param mcrId the mcr identifier
* @return true if its marked
*/
public boolean isMarked(MCRObjectID mcrId) {
return this.marks.containsKey(mcrId);
}
/**
* Checks if the given base object is marked. If base is an instance of MCRDerivate, this method checks also if the
* linked object is marked.
*
* @param base the mycore object
* @return true if its marked
*/
public boolean isMarked(MCRBase base) {
if (base instanceof MCRDerivate derivate) {
return isMarked(derivate.getId()) || isMarked(derivate.getOwnerID());
}
return isMarked(base.getId());
}
/**
* Checks if the object is marked for deletion.
*
* @param mcrId the mcr identifier
* @return true if its marked for deletion
*/
public boolean isMarkedForDeletion(MCRObjectID mcrId) {
return Operation.DELETE.equals(this.marks.get(mcrId));
}
/**
* Checks if the derivate or the corresponding mycore object is
* marked for deletion.
*
* @return true if one of them is marked for deletion
*/
public boolean isMarkedForDeletion(MCRDerivate derivate) {
return isMarkedForDeletion(derivate.getId()) || isMarkedForDeletion(derivate.getOwnerID());
}
/**
* Checks if the object is marked for import.
*
* @param mcrId the mcr identifier
* @return true if its marked for import
*/
public boolean isMarkedForImport(MCRObjectID mcrId) {
return Operation.IMPORT.equals(this.marks.get(mcrId));
}
}
| 5,747 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataURL.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDataURL.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Represents the data URL scheme (<a href="https://tools.ietf.org/html/rfc2397">RFC2397</a>).
*
* @author René Adler (eagle)
*
*/
public class MCRDataURL implements Serializable {
private static final long serialVersionUID = 1L;
private static final String SCHEME = "data:";
private static final String DEFAULT_MIMETYPE = "text/plain";
private static final Pattern PATTERN_MIMETYPE = Pattern.compile("^([a-z0-9\\-\\+]+)\\/([a-z0-9\\-\\+]+)$");
private static final String CHARSET_PARAM = "charset";
private static final String TOKEN_SEPARATOR = ";";
private static final String DATA_SEPARATOR = ",";
private static final String PARAM_SEPARATOR = "=";
private final String mimeType;
private final Map<String, String> parameters;
private final Charset charset;
private final MCRDataURLEncoding encoding;
private final byte[] data;
/**
* Build a "data" URL for given {@link Document}, encoding, mime-type and charset.
* Should encoding be <code>null</code>, it is detect from mime-type.
*
* @param document the document
* @param encoding the {@link MCRDataURLEncoding}
* @param mimeType the mime-type
* @param charset the charset
* @return a string with "data" URL
*/
public static String build(final Document document, final String encoding, final String mimeType,
final String charset) throws TransformerException, MalformedURLException {
return build(document.getChildNodes(), encoding, mimeType, charset);
}
/**
* Build a "data" URL for given {@link NodeList}, encoding, mime-type and charset.
* Should encoding be <code>null</code>, it is detect from mime-type.
*
* @param nodeList the node list
* @param encoding the {@link MCRDataURLEncoding}
* @param mimeType the mime-type
* @param charset the charset
* @return a string with "data" URL
*/
public static String build(final NodeList nodeList, final String encoding, final String mimeType,
final String charset) throws TransformerException, MalformedURLException {
Node node = Optional.ofNullable(nodeList.item(0)).filter(n -> n.getNodeName().equals("#document"))
.orElseGet(() -> Optional.of(nodeList).filter(nl -> nl.getLength() == 1).map(nl -> nl.item(0))
.orElseThrow(() -> new IllegalArgumentException("Nodelist must have an single root element.")));
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
MCRDataURLEncoding enc = encoding != null ? MCRDataURLEncoding.fromValue(encoding) : null;
String method = "xml";
final Matcher mtm = PATTERN_MIMETYPE.matcher(mimeType);
if (mtm.matches()) {
if (enc == null) {
if ("text".equals(mtm.group(1))) {
enc = MCRDataURLEncoding.URL;
} else {
enc = MCRDataURLEncoding.BASE64;
}
}
if ("plain".equals(mtm.group(2))) {
method = "text";
} else if ("html".equals(mtm.group(2))) {
method = "html";
} else if ("xml|xhtml+xml".contains(mtm.group(2))) {
method = "xml";
} else {
method = null;
}
}
if (method != null) {
transformer.setOutputProperty(OutputKeys.METHOD, method);
}
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, mimeType);
transformer.setOutputProperty(OutputKeys.ENCODING, charset);
DOMSource source = new DOMSource(node);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bao);
transformer.transform(source, result);
final MCRDataURL dataURL = new MCRDataURL(bao.toByteArray(), enc, mimeType, charset);
return dataURL.toString();
}
/**
* Build a "data" URL for given {@link String}, encoding, mime-type and charset.
* Should encoding be <code>null</code>, it is detect from mime-type.
*
* @param str the value
* @param encoding the {@link MCRDataURLEncoding}
* @param mimeType the mime-type
* @param charset the charset
* @return a string with "data" URL
*/
public static String build(final String str, final String encoding, final String mimeType, final String charset)
throws MalformedURLException {
MCRDataURLEncoding enc = encoding != null ? MCRDataURLEncoding.fromValue(encoding) : null;
final Matcher mtm = PATTERN_MIMETYPE.matcher(mimeType);
if (mtm.matches()) {
if (enc == null) {
if ("text".equals(mtm.group(1))) {
enc = MCRDataURLEncoding.URL;
} else {
enc = MCRDataURLEncoding.BASE64;
}
}
}
final MCRDataURL dataURL = new MCRDataURL(str.getBytes(Charset.forName(charset)), enc, mimeType, charset);
return dataURL.toString();
}
/**
* Build a "data" URL for given {@link Document}, mime-type and <code>UTF-8</code> as charset.
*
* @param document the document
* @param mimeType the mime-type
* @return a string with "data" URL
*/
public static String build(final Document document, final String mimeType)
throws TransformerException, MalformedURLException {
return build(document, null, mimeType, "UTF-8");
}
/**
* Build a "data" URL for given {@link NodeList}, mime-type and <code>UTF-8</code> as charset.
*
* @param nodeList the node list
* @param mimeType the mime-type
* @return a string with "data" URL
*/
public static String build(final NodeList nodeList, final String mimeType)
throws TransformerException, MalformedURLException {
return build(nodeList, null, mimeType, "UTF-8");
}
/**
* Build a "data" URL for given {@link String}, mime-type and <code>UTF-8</code> as charset.
*
* @param str the string
* @param mimeType the mime-type
* @return a string with "data" URL
*/
public static String build(final String str, final String mimeType)
throws MalformedURLException {
return build(str, null, mimeType, "UTF-8");
}
/**
* Build a "data" URL for given {@link Document} with mime-type based encoding,
* <code>text/xml</code> as mime-type and <code>UTF-8</code> as charset.
*
* @param document the document
* @return a string with "data" URL
*/
public static String build(final Document document) throws TransformerException, MalformedURLException {
return build(document, null, "text/xml", "UTF-8");
}
/**
* Build a "data" URL for given {@link NodeList} with mime-type based encoding,
* <code>text/xml</code> as mime-type and <code>UTF-8</code> as charset.
*
* @param nodeList the node list
* @return a string with "data" URL
*/
public static String build(final NodeList nodeList) throws TransformerException, MalformedURLException {
return build(nodeList, null, "text/xml", "UTF-8");
}
/**
* Build a "data" URL for given {@link String} with mime-type based encoding,
* <code>text/xml</code> as mime-type and <code>UTF-8</code> as charset.
*
* @param str the node list
* @return a string with "data" URL
*/
public static String build(final String str) throws MalformedURLException {
return build(str, null, "text/palin", "UTF-8");
}
/**
* Parse a {@link String} to {@link MCRDataURL}.
*
* @param dataURL the data url string
* @return a {@link MCRDataURL} object
*/
public static MCRDataURL parse(final String dataURL) throws MalformedURLException {
final String url = dataURL.trim();
if (url.startsWith(SCHEME)) {
String[] parts = url.substring(SCHEME.length()).split(DATA_SEPARATOR, 2);
if (parts.length == 2) {
String[] tokens = parts[0].split(TOKEN_SEPARATOR);
List<String> token = Arrays.stream(tokens).filter(s -> !s.contains(PARAM_SEPARATOR))
.collect(Collectors.toList());
Map<String, String> params = Arrays.stream(tokens).filter(s -> s.contains(PARAM_SEPARATOR))
.map(s -> s.split(PARAM_SEPARATOR, 2)).collect(Collectors.toMap(sl -> sl[0], sl -> {
try {
return decode(sl[1], StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("Error encoding the parameter value \"" + sl[1]
+ "\". Error: " + e.getMessage());
}
}));
final String mimeType = !token.isEmpty() ? token.get(0) : null;
if (mimeType != null && !mimeType.isEmpty() && !PATTERN_MIMETYPE.matcher(mimeType).matches()) {
throw new MalformedURLException("Unknown mime type.");
}
final MCRDataURLEncoding encoding;
try {
encoding = !token.isEmpty() && token.size() > 1 ? MCRDataURLEncoding.fromValue(token.get(1))
: MCRDataURLEncoding.URL;
} catch (IllegalArgumentException e) {
throw new MalformedURLException("Unknown encoding.");
}
Charset charset = params.containsKey(CHARSET_PARAM) ? Charset.forName(params.get(CHARSET_PARAM))
: StandardCharsets.US_ASCII;
byte[] data;
try {
data = encoding == MCRDataURLEncoding.BASE64 ? Base64.getDecoder().decode(parts[1])
: decode(parts[1], charset).getBytes(StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw new MalformedURLException("Error decoding the data. " + e.getMessage());
}
return new MCRDataURL(data, encoding, mimeType, params);
} else {
throw new MalformedURLException("Error parse data url: " + url);
}
} else {
throw new MalformedURLException("Wrong protocol");
}
}
/**
* Constructs a new {@link MCRDataURL}.
*
* @param data the data
* @param encoding the encoding of data url
* @param mimeType the mimeType of data url
* @param parameters a list of paramters of data url
*/
public MCRDataURL(final byte[] data, final MCRDataURLEncoding encoding, final String mimeType,
final Map<String, String> parameters) throws MalformedURLException {
this.data = data;
this.encoding = encoding != null ? encoding : MCRDataURLEncoding.URL;
this.mimeType = mimeType != null && !mimeType.isEmpty() ? mimeType : DEFAULT_MIMETYPE;
if (!PATTERN_MIMETYPE.matcher(this.mimeType).matches()) {
throw new MalformedURLException("Unknown mime type.");
}
if (parameters != null) {
this.parameters = Collections.unmodifiableMap(new LinkedHashMap<>(parameters.entrySet()
.stream()
.filter(
e -> !CHARSET_PARAM.equals(e.getKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue))));
this.charset = parameters.containsKey(CHARSET_PARAM) && parameters.get(CHARSET_PARAM) != null
&& !parameters.get(CHARSET_PARAM).isEmpty() ? Charset.forName(parameters.get(CHARSET_PARAM))
: StandardCharsets.US_ASCII;
} else {
this.parameters = Collections.emptyMap();
this.charset = StandardCharsets.US_ASCII;
}
}
/**
* Constructs a new {@link MCRDataURL}.
*
* @param data the data
* @param encoding the encoding of data url
* @param mimeType the mimeType of data url
* @param charset the charset of data url
*/
public MCRDataURL(final byte[] data, final MCRDataURLEncoding encoding, final String mimeType,
final Charset charset) throws MalformedURLException {
this.data = data;
this.encoding = encoding != null ? encoding : MCRDataURLEncoding.URL;
this.mimeType = mimeType != null && !mimeType.isEmpty() ? mimeType : DEFAULT_MIMETYPE;
if (!PATTERN_MIMETYPE.matcher(this.mimeType).matches()) {
throw new MalformedURLException("Unknown mime type.");
}
this.parameters = Collections.emptyMap();
this.charset = charset != null ? charset : StandardCharsets.US_ASCII;
}
/**
* Constructs a new {@link MCRDataURL}.
*
* @param data the data
* @param encoding the encoding of data url
* @param mimeType the mimeType of data url
* @param charset the charset of data url
*/
public MCRDataURL(final byte[] data, final MCRDataURLEncoding encoding, final String mimeType, final String charset)
throws MalformedURLException {
this(data, encoding, mimeType, Charset.forName(charset));
}
/**
* Constructs a new {@link MCRDataURL}.
*
* @param data the data
* @param encoding the encoding of data url
* @param mimeType the mimeType of data url
*/
public MCRDataURL(final byte[] data, final MCRDataURLEncoding encoding, final String mimeType)
throws MalformedURLException {
this(data, encoding, mimeType, StandardCharsets.US_ASCII);
}
/**
* Constructs a new {@link MCRDataURL}.
*
* @param data the data of data url
* @param encoding the encoding of data url
*/
public MCRDataURL(final byte[] data, final MCRDataURLEncoding encoding) throws MalformedURLException {
this(data, encoding, DEFAULT_MIMETYPE, StandardCharsets.US_ASCII);
}
/**
* Constructs a new {@link MCRDataURL}.
*
* @param data the data of data url
*/
public MCRDataURL(final byte[] data) throws MalformedURLException {
this(data, MCRDataURLEncoding.URL, DEFAULT_MIMETYPE, StandardCharsets.US_ASCII);
}
/**
* @return the mimeType
*/
public String getMimeType() {
return mimeType;
}
/**
* @return the parameters
*/
public Map<String, String> getParameters() {
return parameters;
}
/**
* @return the charset
*/
public Charset getCharset() {
return charset;
}
/**
* @return the encoding
*/
public MCRDataURLEncoding getEncoding() {
return encoding;
}
/**
* @return the data
*/
public byte[] getData() {
return data;
}
/**
* Returns a {@link String} of a {@link MCRDataURL} object .
*
* @return the data url as string
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(SCHEME);
if (!DEFAULT_MIMETYPE.equals(mimeType) || charset != StandardCharsets.US_ASCII) {
sb.append(mimeType);
}
if (charset != StandardCharsets.US_ASCII) {
sb.append(TOKEN_SEPARATOR + CHARSET_PARAM + PARAM_SEPARATOR).append(charset.name());
}
parameters.forEach((key, value) -> {
sb.append(TOKEN_SEPARATOR)
.append(key)
.append(PARAM_SEPARATOR)
.append(encode(value, StandardCharsets.UTF_8));
});
if (encoding == MCRDataURLEncoding.BASE64) {
sb.append(TOKEN_SEPARATOR).append(encoding.value());
sb.append(DATA_SEPARATOR).append(Base64.getEncoder().withoutPadding().encodeToString(data));
} else {
sb.append(DATA_SEPARATOR).append(encode(new String(data, charset), charset));
}
return sb.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((charset == null) ? 0 : charset.hashCode());
result = prime * result + ((data == null) ? 0 : Arrays.hashCode(data));
result = prime * result + ((encoding == null) ? 0 : encoding.hashCode());
result = prime * result + ((mimeType == null) ? 0 : mimeType.hashCode());
result = prime * result + ((parameters == null) ? 0 : parameters.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MCRDataURL other)) {
return false;
}
if (charset == null) {
if (other.charset != null) {
return false;
}
} else if (!charset.equals(other.charset)) {
return false;
}
if (data == null) {
if (other.data != null) {
return false;
}
} else if (!MessageDigest.isEqual(data, other.data)) {
return false;
}
if (encoding != other.encoding) {
return false;
}
if (mimeType == null) {
if (other.mimeType != null) {
return false;
}
} else if (!mimeType.equals(other.mimeType)) {
return false;
}
if (parameters == null) {
return other.parameters == null;
} else {
return parameters.equals(other.parameters);
}
}
private static String encode(final String str, final Charset charset) {
return URLEncoder.encode(str, charset).replace("+", "%20");
}
private static String decode(final String str, final Charset charset) {
return URLDecoder.decode(str.replace("%20", "+"), charset);
}
}
| 19,982 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractMetadataVersion.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRAbstractMetadataVersion.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.IOException;
import java.util.Date;
import org.jdom2.JDOMException;
import org.mycore.common.MCRUsageException;
import org.mycore.common.content.MCRContent;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlTransient;
/**
* Provides information about a stored version of metadata and allows to
* retrieve that version from SVN
*
* @author Frank Lützenkirchen
*/
@XmlRootElement(name = "revision")
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class MCRAbstractMetadataVersion<T> {
/**
* The metadata document this version belongs to
*/
@XmlTransient
protected T vm;
/**
* The revision number of this version
*/
@XmlAttribute(name = "r")
protected String revision;
/**
* The user that created this version
*/
@XmlAttribute
protected String user;
/**
* The date this version was created
*/
@XmlAttribute
protected Date date;
/**
* Was this version result of a create, update or delete?
*/
@XmlAttribute()
protected MCRMetadataVersionType type;
/**
* A version that was created in store
*/
public static final char CREATED = 'A';
/**
* A version that was updated in store
*/
public static final char UPDATED = 'M';
/**
* A version that was deleted in store
*/
public static final char DELETED = 'D';
//required for JAXB serialization
@SuppressWarnings("unused")
private MCRAbstractMetadataVersion() {
}
/**
* Creates a new metadata version info object
*
* @param vm
* the metadata document this version belongs to
* @param revision
* the revision of this object, serialised as a string
* @param user
* the user that created this revision
* @param date
* the date on which this revision was created
* @param type
* the type of commit
*/
public MCRAbstractMetadataVersion(T vm, String revision, String user, Date date, char type) {
this.vm = vm;
this.revision = revision;
this.user = user;
this.date = date;
this.type = MCRMetadataVersionType.fromValue(type);
}
/**
* Returns the metadata object this version belongs to
*
* @return the metadata object this version belongs to
*/
public T getMetadataObject() {
return vm;
}
/**
* Returns the type of operation this version comes from
*
* @see #CREATED
* @see #UPDATED
* @see #DELETED
*/
public char getType() {
return type.getCharValue();
}
/**
* Returns the SVN revision number of this version
*
* @return the SVN revision number of this version
*/
public String getRevision() {
return revision;
}
/**
* Returns the user that created this version
*
* @return the user that created this version
*/
public String getUser() {
return user;
}
/**
* Returns the date and time this version was created
*
* @return the date and time this version was created
*/
public Date getDate() {
return date;
}
/**
* Retrieves this version of the metadata
*
* @return the metadata document as it was in this version
* @throws MCRUsageException
* if this is a deleted version, which can not be retrieved
*/
abstract public MCRContent retrieve() throws IOException;
/**
* Replaces the current version of the metadata object with this version,
* which means that a new version is created that is identical to this old
* version. The stored metadata document is updated to this old version of
* the metadata.
*/
abstract public void restore() throws IOException, JDOMException;
}
| 4,860 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLMetadataEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRXMLMetadataEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.content.MCRBaseContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectService;
/**
* This class manages all operations of the XMLTables for operations of an
* object or derivate.
*
* @author Jens Kupferschmidt
*/
public class MCRXMLMetadataEventHandler extends MCREventHandlerBase {
static MCRXMLMetadataManager metaDataManager = MCRXMLMetadataManager.instance();
/**
* This method add the data to SQL table of XML data via MCRXMLMetadataManager.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected final void handleObjectCreated(MCREvent evt, MCRObject obj) {
handleStoreEvent(evt, obj);
}
/**
* This method update the data to SQL table of XML data via
* MCRXMLMetadataManager.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected final void handleObjectUpdated(MCREvent evt, MCRObject obj) {
handleStoreEvent(evt, obj);
}
/**
* This method delete the XML data from SQL table data via
* MCRXMLMetadataManager.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected final void handleObjectDeleted(MCREvent evt, MCRObject obj) {
handleStoreEvent(evt, obj);
}
@Override
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
handleStoreEvent(evt, obj);
}
/**
* This method add the data to SQL table of XML data via MCRXMLMetadataManager.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
@Override
protected final void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
handleStoreEvent(evt, der);
}
/**
* This method update the data to SQL table of XML data via
* MCRXMLMetadataManager.
*
* @param evt
* the event that occured
* @param der
* the MCRObject that caused the event
*/
@Override
protected final void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
handleStoreEvent(evt, der);
}
/**
* This method delete the XML data from SQL table data via
* MCRXMLMetadataManager.
*
* @param evt
* the event that occured
* @param der
* the MCRObject that caused the event
*/
@Override
protected final void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
handleStoreEvent(evt, der);
}
private void handleStoreEvent(MCREvent evt, MCRBase obj) {
MCREvent.EventType eventType = evt.getEventType();
MCRObjectID id = obj.getId();
try {
switch (eventType) {
case REPAIR, UPDATE, CREATE -> {
MCRBaseContent content = new MCRBaseContent(obj);
Date modified = obj.getService().getDate(MCRObjectService.DATE_TYPE_MODIFYDATE);
switch (eventType) {
case REPAIR:
MCRContent retrieveContent = metaDataManager.retrieveContent(id);
if (isUptodate(retrieveContent, content)) {
return;
}
case UPDATE:
metaDataManager.update(id, content, modified);
break;
case CREATE:
metaDataManager.create(id, content, modified);
break;
default:
break;
}
evt.put("content", content);
}
case DELETE -> metaDataManager.delete(id);
default -> throw new IllegalArgumentException("Invalid event type " + eventType + " for object " + id);
}
} catch (IOException e) {
throw new MCRPersistenceException("Error while handling '" + eventType + "' event of '" + id + "'", e);
}
}
private boolean isUptodate(MCRContent retrieveContent, MCRBaseContent content) throws IOException {
return retrieveContent.lastModified() > content.lastModified()
|| Arrays.equals(retrieveContent.asByteArray(), content.asByteArray());
}
}
| 5,861 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCreatorCache.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRCreatorCache.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.Collections;
import java.util.Comparator;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
*
* @author René Adler (eagle)
*
*/
public class MCRCreatorCache {
private static final Logger LOGGER = LogManager.getLogger(MCRCreatorCache.class);
private static final long CACHE_SIZE = 5000;
private static LoadingCache<MCRObjectID, String> CACHE = CacheBuilder.newBuilder()
.maximumSize(CACHE_SIZE).build(new CacheLoader<>() {
@Override
public String load(final MCRObjectID objectId) {
return Optional.ofNullable(MCRMetadataManager.retrieveMCRObject(objectId).getService()).map(os -> {
if (os.isFlagTypeSet("createdby")) {
final String creator = os.getFlags("createdby").get(0);
LOGGER.info("Found creator {} of {}", creator, objectId);
return creator;
}
LOGGER.info("Try to get creator information of {} from svn history.", objectId);
return null;
}).orElseGet(() -> {
try {
return Optional.ofNullable(MCRXMLMetadataManager.instance().listRevisions(objectId))
.map(versions -> versions.stream()
.sorted(
Collections
.reverseOrder(Comparator.comparing(MCRAbstractMetadataVersion::getRevision)))
.filter(v -> v.getType() == MCRAbstractMetadataVersion.CREATED).findFirst()
.map(version -> {
LOGGER.info(
"Found creator {} in revision {} of {}",
version.getUser(), version.getRevision(),
objectId);
return version.getUser();
}).orElseGet(() -> {
LOGGER.info("Could not get creator information of {}.", objectId);
return null;
}))
.orElseGet(() -> {
LOGGER.info("Could not get creator information.");
return null;
});
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
});
/**
* Returns the creator by given {@link MCRObjectID}.
*
* @param objectId the {@link MCRObjectID}
* @return the creator of the object
* @throws ExecutionException is thrown if any other exception occurs
*/
public static String getCreator(final MCRObjectID objectId) throws ExecutionException {
return CACHE.get(objectId);
}
/**
* Returns the creator by given {@link MCRObjectID}.
*
* @param objectId the {@link MCRObjectID}
* @return the creator of the object
* @throws ExecutionException is thrown if any other exception occurs
*/
public static String getCreator(final String objectId) throws ExecutionException {
return CACHE.get(MCRObjectID.getInstance(objectId));
}
/**
* Discard the cached creator for given {@link MCRObjectID}.
*
* @param objectId the {@link MCRObjectID}
*/
public static void invalidate(final MCRObjectID objectId) {
CACHE.invalidate(objectId);
}
/**
* Discard the cached creator for given {@link MCRObjectID}.
*
* @param objectId the {@link MCRObjectID}
*/
public static void invalidate(final String objectId) {
CACHE.invalidate(MCRObjectID.getInstance(objectId));
}
}
| 5,028 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLinkTableInterface.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRLinkTableInterface.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.Collection;
import java.util.Map;
/**
* This interface is designed to choose the persistence for the link tables.
*
* @author Jens Kupferschmidt
*/
public interface MCRLinkTableInterface {
/**
* The method create a new item in the datastore.
*
* @param from
* a string with the link ID MCRFROM
* @param to
* a string with the link ID MCRTO
* @param type
* a string with the link ID MCRTYPE
* @param attr
* a string with the link ID MCRATTR
*/
void create(String from, String to, String type, String attr);
/**
* The method remove a item for the from ID from the datastore.
*
* @param from
* a string with the link ID MCRFROM
* @param to
* an array of strings with the link ID MCRTO
* @param type
* an array of strings with the link ID MCRTYPE
*/
void delete(String from, String to, String type);
/**
* The method count the number of references with '%from%' and 'to' and
* optional 'type' and optional 'restriction%' values of the table.
*
* @param fromtype
* a substing in the from ID as String, it can be null
* @param to
* the object ID as String, which is referenced
* @param type
* the refernce type, it can be null
* @param restriction
* a first part of the to ID as String, it can be null
* @return the number of references
*/
int countTo(String fromtype, String to, String type, String restriction);
/**
* The method returns a Map of all counted distinct references
*
* @return
*
* the result-map of (key,value)-pairs can be visualized as <br>
* select count(mcrfrom) as value, mcrto as key from
* mcrlinkclass|mcrlinkhref where mcrto like mcrtoPrefix + '%' group by
* mcrto;
*
*/
Map<String, Number> getCountedMapOfMCRTO(String mcrtoPrefix);
/**
* Returns a List of all link sources of <code>to</code> and a special
* <code>type</code>
*
* @param to
* Destination-ID
* @param type
* Link reference type, this can be null. Current types are
* classid, child, parent, reference and derivate.
* @return List of Strings (Source-IDs)
*/
Collection<String> getSourcesOf(String to, String type);
/**
* Returns a List of all link destination of <code>from</code> and a
* special <code>type</code>
*
* @param from
* Source-ID
* @param type
* Link reference type, this can be null. Current types are
* classid, child, parent, reference and derivate.
* @return List of Strings (Destination-IDs)
*/
Collection<String> getDestinationsOf(String from, String type);
}
| 3,715 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataURLEncoding.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDataURLEncoding.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
/**
* @author René Adler (eagle)
*
*/
public enum MCRDataURLEncoding {
/**
* Base64 encoding
*/
BASE64("base64"),
/**
* URL encoding
*/
URL("");
private final String value;
MCRDataURLEncoding(final String value) {
this.value = value;
}
/**
* Returns the data url encoding.
*
* @return the set data url encoding
*/
public String value() {
return value;
}
/**
* Returns the data url encoding from given value.
*
* @param value the data url encoding
* @return the the data url encoding for value
*/
public static MCRDataURLEncoding fromValue(final String value) {
for (MCRDataURLEncoding encodings : MCRDataURLEncoding.values()) {
if (encodings.value.equals(value)) {
return encodings;
}
}
throw new IllegalArgumentException(value);
}
}
| 1,707 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLMetadataManagerAdapter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRXMLMetadataManagerAdapter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.ifs2.MCRMetadataVersion;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* Provides an abstract class for persistence managers of MCRObject and MCRDerivate xml
* metadata to extend, with methods to perform CRUD operations on object metadata.
*
* The default xml metadata manager is {@link MCRDefaultXMLMetadataManager}. If you wish to use
* another manager implementation instead, change the following property accordingly:
*
* MCR.Metadata.Manager.Class=org.mycore.datamodel.common.MCRDefaultXMLMetadataManager
*
* Xml metadata managers have a default class they will instantiate for every store.
* If you wish to use a different default class, change the following property
* accordingly. For example, when using the MCRDefaultXMLMetadataManager:
*
* MCR.Metadata.Store.DefaultClass=org.mycore.datamodel.ifs2.MCRVersioningMetadataStore
*
* The following directory will be used by xml metadata managers to keep up-to-date
* store contents in. This directory will be created if it does not exist yet.
*
* MCR.Metadata.Store.BaseDir=/path/to/metadata/dir
*
* For each project and type, subdirectories will be created below this path,
* for example %MCR.Metadata.Store.BaseDir%/DocPortal/document/.
*
* If an SVN-based store is configured, then the following property will be used to
* store and manage local SVN repositories:
*
* MCR.Metadata.Store.SVNBase=file:///path/to/local/svndir/
*
* It is also possible to change individual properties per project and object type
* and overwrite the defaults, for example
*
* MCR.IFS2.Store.Class=org.mycore.datamodel.ifs2.MCRVersioningMetadataStore
* MCR.IFS2.Store.SVNRepositoryURL=file:///use/other/location/for/document/versions/
* MCR.IFS2.Store.SlotLayout=2-2-2-2
*
* See documentation of MCRStore, MCRMetadataStore and the MCRXMLMetadataManager
* extensions (e.g. MCRDefaultXMLMetadataManager) for details.
*
* @author Christoph Neidahl (OPNA2608)
*/
public interface MCRXMLMetadataManagerAdapter {
/**
* Reads configuration properties, checks and creates base directories and builds the singleton.
*/
void reload();
/**
* Try to validate a store.
*
* @param base The base ID of a to-be-validated store
*/
void verifyStore(String base);
/**
* Stores metadata of a new MCRObject in the persistent store.
*
* @param mcrid the MCRObjectID
* @param xml the xml metadata of the MCRObject
* @param lastModified the date of last modification to set
* @throws MCRPersistenceException the object couldn't be created due persistence problems
*/
void create(MCRObjectID mcrid, MCRContent xml, Date lastModified)
throws MCRPersistenceException;
/**
* Delete metadata in store.
*
* @param mcrid the MCRObjectID
* @throws MCRPersistenceException if an error occurs during the deletion
*/
void delete(MCRObjectID mcrid) throws MCRPersistenceException;
/**
* Updates metadata of existing MCRObject in the persistent store.
*
* @param mcrid the MCRObjectID
* @param xml the xml metadata of the MCRObject
* @param lastModified the date of last modification to set
*/
void update(MCRObjectID mcrid, MCRContent xml, Date lastModified)
throws MCRPersistenceException;
/**
* Retrieves the (latest) content of a metadata object.
*
* @param mcrid
* the id of the object to be retrieved
* @return a {@link MCRContent} representing the {@link MCRObject} or
* <code>null</code> if there is no such object
*/
MCRContent retrieveContent(MCRObjectID mcrid) throws IOException;
/**
* Retrieves the content of a specific revision of a metadata object.
*
* @param mcrid
* the id of the object to be retrieved
* @param revision
* the revision to be returned, specify -1 if you want to
* retrieve the latest revision (includes deleted objects also)
* @return a {@link MCRContent} representing the {@link MCRObject} of the
* given revision or <code>null</code> if there is no such object
* with the given revision
*/
MCRContent retrieveContent(MCRObjectID mcrid, String revision) throws IOException;
/**
* Lists all versions of this metadata object available in the
* subversion repository.
*
* @param id
* the id of the object to be retrieved
* @return {@link List} with all {@link MCRMetadataVersion} of
* the given object or null if the id is null or the metadata
* store doesn't support versioning
*/
List<? extends MCRAbstractMetadataVersion<?>> listRevisions(MCRObjectID id) throws IOException;
/**
* This method returns the highest stored ID number for a given MCRObjectID
* base, or 0 if no object is stored for this type and project.
*
* @param project
* the project ID part of the MCRObjectID base
* @param type
* the type ID part of the MCRObjectID base
* @exception MCRPersistenceException
* if a persistence problem is occurred
* @return the highest stored ID number as a String
*/
int getHighestStoredID(String project, String type);
/**
* Checks if an object with the given MCRObjectID exists in the store.
*
* @param mcrid
* the MCRObjectID to check
* @return true if the ID exists, or false if it doesn't
* @throws MCRPersistenceException if an error occurred in the store
*/
boolean exists(MCRObjectID mcrid) throws MCRPersistenceException;
/**
* Lists all MCRObjectIDs stored for the given base, which is {project}_{type}
*
* @param base
* the MCRObjectID base, e.g. DocPortal_document
* @return List of Strings with all MyCoRe identifiers found in the metadata stores for the given base
*/
List<String> listIDsForBase(String base);
/**
* Lists all MCRObjectIDs stored for the given object type, for all projects
*
* @param type
* the MCRObject type, e.g. document
* @return List of Strings with all MyCoRe identifiers found in the metadata store for the given type
*/
List<String> listIDsOfType(String type);
/**
* Lists all MCRObjectIDs of all types and projects stored in any metadata store
*
* @return List of Strings with all MyCoRe identifiers found in the metadata store
*/
List<String> listIDs();
/**
* Returns all stored object types of MCRObjects/MCRDerivates.
*
* @return Collection of Strings with all object types
* @see MCRObjectID#getTypeId()
*/
Collection<String> getObjectTypes();
/**
* Returns all used base ids of MCRObjects/MCRDerivates.
*
* @return Collection of Strings with all object base identifier
* @see MCRObjectID#getBase()
*/
Collection<String> getObjectBaseIds();
/**
* Returns an enhanced list of object ids and their last modified date
*
* @param ids MCRObject ids
*/
List<MCRObjectIDDate> retrieveObjectDates(List<String> ids) throws IOException;
/**
* Returns the time when the xml data of a MCRObject was last modified.
*
* @param id
* the MCRObjectID of an object
* @return the last modification data of the object
* @throws IOException thrown while retrieving the object from the store
*/
long getLastModified(MCRObjectID id) throws IOException;
MCRCache.ModifiedHandle getLastModifiedHandle(MCRObjectID id, long expire, TimeUnit unit);
}
| 8,847 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRActiveLinkException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRActiveLinkException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.mycore.common.MCRCatchException;
/**
* This exception holds information about a link condition that did not allow a
* certain action to be performed.
*
* As this exception does not extend RuntimeException it has to be caught for
* data integrity reasons.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRActiveLinkException extends MCRCatchException {
private static final long serialVersionUID = 1L;
Map<String, Collection<String>> linkTable = new ConcurrentHashMap<>();
/**
*
* @return a Hashtable with destinations (key) and List of sources (value)
*/
public Map<String, Collection<String>> getActiveLinks() {
return linkTable;
}
/**
* collects information on active links that do not permit a certain action
* on the repository.
*
* @param source
* the source of a link
* @param dest
* the destination of a link
*/
public void addLink(String source, String dest) {
if (!linkTable.containsKey(dest)) {
linkTable.put(dest, new ConcurrentLinkedQueue<>());
}
linkTable.get(dest).add(source);
}
/**
* @see MCRCatchException#MCRCatchException(String)
*/
public MCRActiveLinkException(String message) {
super(message);
}
/**
* @see MCRCatchException#MCRCatchException(String, Throwable)
*/
public MCRActiveLinkException(String message, Throwable cause) {
super(message, cause);
}
}
| 2,445 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLinkTableManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRLinkTableManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetaClassification;
import org.mycore.datamodel.metadata.MCRMetaDerivateLink;
import org.mycore.datamodel.metadata.MCRMetaElement;
import org.mycore.datamodel.metadata.MCRMetaLinkID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectMetadata;
import org.mycore.datamodel.metadata.MCRObjectStructure;
/**
* This class manage all accesses to the link table database. This database
* holds all informations about links between MCRObjects/MCRClassifications.
*
* @author Jens Kupferschmidt
*/
public class MCRLinkTableManager {
/** The list of entry types */
public static final String ENTRY_TYPE_CHILD = "child";
public static final String ENTRY_TYPE_DERIVATE = "derivate";
public static final String ENTRY_TYPE_DERIVATE_LINK = "derivate_link";
public static final String ENTRY_TYPE_PARENT = "parent";
public static final String ENTRY_TYPE_REFERENCE = "reference";
/** The link table manager singleton */
protected static MCRLinkTableManager singleton;
// logger
static Logger LOGGER = LogManager.getLogger();
private MCRLinkTableInterface linkTableInstance = null;
/**
* Returns the link table manager singleton.
*
* @return Returns a MCRLinkTableManager instance.
*/
public static synchronized MCRLinkTableManager instance() {
if (singleton == null) {
singleton = new MCRLinkTableManager();
}
return singleton;
}
/**
* The constructor of this class.
*/
protected MCRLinkTableManager() {
// Load the persistence class
linkTableInstance = MCRConfiguration2
.getOrThrow("MCR.Persistence.LinkTable.Store.Class", MCRConfiguration2::instantiateClass);
}
/**
* The method add a reference link pair.
*
* @param from
* the source of the reference as MCRObjectID
* @param to
* the target of the reference as MCRObjectID
* @param type
* the type of the reference as String
* @param attr
* the optional attribute of the reference as String
*/
public void addReferenceLink(MCRObjectID from, MCRObjectID to, String type, String attr) {
addReferenceLink(from.toString(), to.toString(), type, attr);
}
/**
* The method add a reference link pair.
*
* @param from
* the source of the reference as String
* @param to
* the target of the reference as String
* @param type
* the type of the reference as String
* @param attr
* the optional attribute of the reference as String
*/
public void addReferenceLink(String from, String to, String type, String attr) {
from = MCRUtils.filterTrimmedNotEmpty(from).orElse(null);
if (from == null) {
LOGGER.warn("The from value of a reference link is false, the link was not added to the link table");
return;
}
to = MCRUtils.filterTrimmedNotEmpty(to).orElse(null);
if (to == null) {
LOGGER.warn("The to value of a reference link is false, the link was not added to the link table");
return;
}
type = MCRUtils.filterTrimmedNotEmpty(type).orElse(null);
if (type == null) {
LOGGER.warn("The type value of a reference link is false, the link was not added to the link table");
return;
}
attr = MCRUtils.filterTrimmedNotEmpty(attr).orElse("");
LOGGER.debug("Link in table {} add for {}<-->{} with {} and {}", type, from, to, type, attr);
try {
linkTableInstance.create(from, to, type, attr);
} catch (Exception e) {
LOGGER.warn("An error occured while adding a dataset from the reference link table, adding not succesful.",
e);
}
}
/**
* The method delete a reference link.
*
* @param from
* the source of the reference as MCRObjectID
*/
public void deleteReferenceLink(MCRObjectID from) {
deleteReferenceLink(from.toString());
}
/**
* The method delete a reference link.
*
* @param from
* the source of the reference as String
*/
public void deleteReferenceLink(String from) {
from = MCRUtils.filterTrimmedNotEmpty(from).orElse(null);
if (from == null) {
LOGGER
.warn("The from value of a reference link is false, the link was " + "not deleted from the link table");
return;
}
try {
linkTableInstance.delete(from, null, null);
} catch (Exception e) {
LOGGER.warn("An error occured while deleting a dataset from the" + from
+ " reference link table, deleting could be not succesful.", e);
}
}
/**
* The method delete a reference link pair for the given type to the store.
*
* @param from
* the source of the reference as String
* @param to
* the target of the reference as String
* @param type
* the type of the reference as String
*/
public void deleteReferenceLink(String from, String to, String type) {
from = MCRUtils.filterTrimmedNotEmpty(from).orElse(null);
if (from == null) {
LOGGER
.warn("The from value of a reference link is false, the link was " + "not deleted from the link table");
return;
}
try {
linkTableInstance.delete(from, to, type);
} catch (Exception e) {
LOGGER.warn("An error occured while deleting a dataset from the"
+ " reference link table, deleting is not succesful.", e);
}
}
/**
* The method count the reference links for a given target MCRobjectID.
*
* @param to
* the object ID as MCRObjectID, they was referenced
* @return the number of references
*/
public int countReferenceLinkTo(MCRObjectID to) {
return countReferenceLinkTo(to.toString());
}
/**
* The method count the reference links for a given target object ID.
*
* @param to
* the object ID as String, they was referenced
* @return the number of references
*/
public int countReferenceLinkTo(String to) {
to = MCRUtils.filterTrimmedNotEmpty(to).orElse(null);
if (to == null) {
LOGGER.warn("The to value of a reference link is false, the link was " + "not added to the link table");
return 0;
}
try {
return linkTableInstance.countTo(null, to, null, null);
} catch (Exception e) {
LOGGER.warn("An error occured while searching for references of " + to + ".", e);
}
return 0;
}
/**
* counts the reference links for a given to object ID.
*
* @param types
* Array of document type slected by the mcrfrom content
* @param restriction
* a first part of the to ID as String, it can be null
* @return the number of references
*/
public int countReferenceLinkTo(String to, String[] types, String restriction) {
Optional<String> myTo = MCRUtils.filterTrimmedNotEmpty(to);
if (!myTo.isPresent()) {
LOGGER.warn("The to value of a reference link is false, the link was " + "not added to the link table");
return 0;
}
try {
if (types != null && types.length > 0) {
return Stream.of(types).mapToInt(type -> linkTableInstance.countTo(null, myTo.get(), type, restriction))
.sum();
}
return linkTableInstance.countTo(null, myTo.get(), null, restriction);
} catch (Exception e) {
LOGGER.warn("An error occured while searching for references of " + to + ".", e);
return 0;
}
}
/**
* The method count the number of references to a category of a
* classification without sub ID's and returns it as a Map
*
* @param classid
* the classification ID as MCRObjectID
*
* @return a Map with key=categID and value=counted number of references
*/
public Map<String, Number> countReferenceCategory(String classid) {
return linkTableInstance.getCountedMapOfMCRTO(classid);
}
/**
* The method count the number of references to a category of a
* classification.
*
* @param classid
* the classification ID as String
* @param categid
* the category ID as String
* @return the number of references
*/
public int countReferenceCategory(String classid, String categid) {
return countReferenceLinkTo(classid + "##" + categid, null, null);
}
/**
* Returns a List of all link sources of <code>to</code>
*
* @param to
* The MCRObjectID to referenced.
* @return List of Strings (Source-IDs)
*/
public Collection<String> getSourceOf(MCRObjectID to) {
return getSourceOf(to.toString());
}
/**
* Returns a List of all link sources of <code>to</code>
*
* @param to
* The ID to referenced.
* @return List of Strings (Source-IDs)
*/
public Collection<String> getSourceOf(String to) {
if (to == null || to.length() == 0) {
LOGGER.warn("The to value of a reference link is false, the link was not found in the link table");
return Collections.emptyList();
}
try {
return linkTableInstance.getSourcesOf(to, null);
} catch (Exception e) {
LOGGER.warn("An error occured while searching for references to " + to + ".", e);
return Collections.emptyList();
}
}
/**
* Returns a List of all link sources of <code>to</code> and a special
* <code>type</code>
*
* @param to
* Destination-ID
* @param type
* link reference type
* @return List of Strings (Source-IDs)
*/
public Collection<String> getSourceOf(MCRObjectID to, String type) {
return getSourceOf(to.toString(), type);
}
/**
* Returns a List of all link sources of <code>to</code> and a special
* <code>type</code>
*
* @param to
* Destination-ID
* @param type
* link reference type
* @return List of Strings (Source-IDs)
*/
public Collection<String> getSourceOf(String to, String type) {
if (to == null || to.length() == 0) {
LOGGER.warn("The to value of a reference link is false, the link was not found in the link table");
return Collections.emptyList();
}
if (type == null || type.length() == 0) {
LOGGER.warn("The type value of a reference link is false, the link was not found in the link table");
return Collections.emptyList();
}
try {
return linkTableInstance.getSourcesOf(to, type);
} catch (Exception e) {
LOGGER.warn("An error occured while searching for references to " + to + " with " + type + ".", e);
return Collections.emptyList();
}
}
/**
* The method return a list of all source ID's of the refernce target to
* with the given type.
*
* @param to
* the refernce target to
* @param type
* type of the refernce
* @return a list of ID's
*/
public Collection<String> getSourceOf(String[] to, String type) {
if (to == null || to.length == 0) {
LOGGER.warn("The to value of a reference link is false, the link was not found in the link table");
return Collections.emptyList();
}
Collection<String> ll = new ArrayList<>();
try {
for (String singleTo : to) {
ll.addAll(linkTableInstance.getSourcesOf(singleTo, type));
}
return ll;
} catch (Exception e) {
LOGGER.warn("An error occured while searching for references to " + Arrays.toString(to) + ".", e);
return ll;
}
}
/**
* Returns a List of all link destinations of <code>from</code> and a
* special <code>type</code>
*
* @param from
* Destination-ID
* @param type
* link reference type
* @return List of Strings (Source-IDs)
*/
public Collection<String> getDestinationOf(MCRObjectID from, String type) {
return getDestinationOf(from.toString(), type);
}
/**
* Returns a List of all link destination of <code>from</code> and a
* special <code>type</code>
*
* @param from
* Source-ID
* @param type
* Link reference type, this can be null. Current types are
* classid, child, parent, reference and derivate.
* @return List of Strings (Destination-IDs)
*/
public Collection<String> getDestinationOf(String from, String type) {
if (from == null || from.length() == 0) {
LOGGER.warn("The from value of a reference link is false, the link was not found in the link table");
return Collections.emptyList();
}
if (type == null || type.length() == 0) {
LOGGER.warn("The type value of a reference link is false, the link was not found in the link table");
return Collections.emptyList();
}
try {
return linkTableInstance.getDestinationsOf(from, type);
} catch (Exception e) {
LOGGER.warn("An error occured while searching for references from " + from + ".", e);
return Collections.emptyList();
}
}
/**
* Creates all references for the given object. You should call {@link #delete(MCRObjectID)} before using this
* method otherwise doublets could occur.
*
* @param obj the object to create the references
*/
public void create(MCRObject obj) {
MCRObjectID mcrId = obj.getId();
// set new entries
MCRObjectMetadata meta = obj.getMetadata();
//use Set for category collection to remove duplicates if there are any
Collection<MCRCategoryID> categories = new HashSet<>();
meta.stream().flatMap(MCRMetaElement::stream).forEach(inf -> {
if (inf instanceof MCRMetaClassification classification) {
String classId = classification.getClassId();
String categId = classification.getCategId();
categories.add(new MCRCategoryID(classId, categId));
} else if (inf instanceof MCRMetaLinkID linkID) {
addReferenceLink(mcrId.toString(), linkID.getXLinkHref(),
MCRLinkTableManager.ENTRY_TYPE_REFERENCE, "");
} else if (inf instanceof MCRMetaDerivateLink derLink) {
addReferenceLink(mcrId.toString(), derLink.getXLinkHref(),
MCRLinkTableManager.ENTRY_TYPE_DERIVATE_LINK, "");
}
});
MCRCategoryID state = obj.getService().getState();
if (state != null) {
categories.add(state);
}
categories.addAll(obj.getService().getClassifications());
if (categories.size() > 0) {
MCRCategLinkReference objectReference = new MCRCategLinkReference(mcrId);
MCRCategLinkServiceFactory.getInstance().setLinks(objectReference, categories);
}
// add derivate reference
MCRObjectStructure structure = obj.getStructure();
for (int i = 0; i < structure.getDerivates().size(); i++) {
MCRMetaLinkID lid = structure.getDerivates().get(i);
addReferenceLink(obj.getId(), lid.getXLinkHrefID(), MCRLinkTableManager.ENTRY_TYPE_DERIVATE, "");
}
// add parent reference
if (structure.getParentID() != null) {
addReferenceLink(mcrId, structure.getParentID(), MCRLinkTableManager.ENTRY_TYPE_PARENT, "");
}
}
/**
* Removes all references of this object.
*
* @param id the object where all references should be removed
*/
public void delete(MCRObjectID id) {
deleteReferenceLink(id);
MCRCategLinkReference reference = new MCRCategLinkReference(id);
MCRCategLinkServiceFactory.getInstance().deleteLink(reference);
}
/**
* Updates all references of this object. Old ones will be removed and new links will be created.
*
* @param id the mycore object identifer
*/
public void update(MCRObjectID id) {
delete(id);
if ("derivate".equals(id.getTypeId())) {
create(MCRMetadataManager.retrieveMCRDerivate(id));
} else {
create(MCRMetadataManager.retrieveMCRObject(id));
}
}
public void create(MCRDerivate der) {
Collection<MCRCategoryID> categoryList = new HashSet<>(der.getDerivate().getClassifications()
.stream()
.map(this::metaClassToCategoryID)
.collect(Collectors.toList()));
MCRCategoryID state = der.getService().getState();
if (state != null) {
categoryList.add(state);
}
MCRCategLinkReference objectReference = new MCRCategLinkReference(der.getId());
MCRCategLinkServiceFactory.getInstance().setLinks(objectReference, categoryList);
}
private MCRCategoryID metaClassToCategoryID(MCRMetaClassification metaClazz) {
return new MCRCategoryID(metaClazz.getClassId(), metaClazz.getCategId());
}
}
| 19,452 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataVersionType.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRMetadataVersionType.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.stream.Stream;
public enum MCRMetadataVersionType {
CREATED('A'),
MODIFIED('M'),
DELETED('D');
private final char charValue;
MCRMetadataVersionType(char a) {
this.charValue = a;
}
public static MCRMetadataVersionType fromValue(char a) {
return Stream.of(values()).filter(t -> t.charValue == a)
.findAny()
.orElseThrow(IllegalArgumentException::new);
}
final char getCharValue() {
return charValue;
}
}
| 1,285 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectMerger.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRObjectMerger.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.xml.MCRXMLParserFactory;
import org.mycore.datamodel.metadata.MCRMetaElement;
import org.mycore.datamodel.metadata.MCRMetaInterface;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectMetadata;
/**
* Helper class to merge mycore objects. Only metadata merging is
* currently supported.
*
* @author Matthias Eichner
*/
public class MCRObjectMerger {
protected MCRObject target;
/**
* Creates a new instance of the object merger. The target will be cloned for
* further processing. You will receive a copy when calling {@link #get()}.
*
* @param target the target mycore object
*/
public MCRObjectMerger(MCRObject target) {
this.target = new MCRObject(target.createXML());
}
/**
* Merges the metadata of the given source into the target object. Be aware that
* performance isn't that good when validation is activated, due checking against
* the schema each time a change is made.
*
* @param source the source which is merged into the target
* @param validate If true, every change is tracked and validated against the
* xml schema of the mycore object. When a change is invalid it will be
* canceled and the merging continues.
* When set to false the mycore object will be merged without validation.
* This can result in an invalid object.
*
* @return true if something was merged
*/
public boolean mergeMetadata(MCRObject source, boolean validate) {
MCRObjectMetadata targetMetadata = this.target.getMetadata();
boolean merged = false;
for (MCRMetaElement metaElementSource : source.getMetadata()) {
MCRMetaElement metaElementTarget = targetMetadata.getMetadataElement(metaElementSource.getTag());
if (metaElementTarget == null) {
targetMetadata.setMetadataElement(metaElementSource.clone());
if (validate && !validate(this.target)) {
targetMetadata.removeMetadataElement(metaElementSource.getTag());
} else {
merged = true;
}
} else {
for (MCRMetaInterface metaInterfaceSource : metaElementSource) {
boolean equal = false;
for (MCRMetaInterface metaInterfaceTarget : metaElementTarget) {
if (metaInterfaceSource.equals(metaInterfaceTarget)) {
equal = true;
break;
}
}
if (!equal) {
metaElementTarget.addMetaObject(metaInterfaceSource.clone());
if (validate && !validate(this.target)) {
metaElementTarget.removeMetaObject(metaInterfaceSource);
} else {
merged = true;
}
}
}
}
}
return merged;
}
/**
* Validates the given mcr object against its own schema.
*
* @param mcrobj the object to validate
* @return true if the object is valid, otherwise false
*/
protected boolean validate(MCRObject mcrobj) {
try {
MCRXMLParserFactory.getParser(true, true).parseXML(new MCRJDOMContent(mcrobj.createXML()));
return true;
} catch (Exception exc) {
return false;
}
}
/**
* Returns a copy of the merged target object.
*
*/
public MCRObject get() {
return this.target;
}
}
| 4,529 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRISO8601Date.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRISO8601Date.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.StringTokenizer;
import java.util.TimeZone;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
/**
* holds info about a specific point in time. This class is used for handling ISO 8601 like date and dateTime formatted
* strings.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRISO8601Date {
public static final String PROPERTY_STRICT_PARSING = "MCR.Metadata.SimpleDateFormat.StrictParsing";
private static final Logger LOGGER = LogManager.getLogger(MCRISO8601Date.class);
private DateTimeFormatter dateTimeFormatter = MCRISO8601FormatChooser.getFormatter(null, null);
private TemporalAccessor dt;
private MCRISO8601Format isoFormat;
/**
* creates an empty instance. use {@link #setDate(String)} to parse a date/time by this instance.
*/
public MCRISO8601Date() {
}
/**
* same as {@link #MCRISO8601Date()} and {@link #setDate(String)}.
*
* @param isoString
* a date or dateTime string as defined on <a href="http://www.w3.org/TR/NOTE-datetime">W3C Page</a>
*/
public MCRISO8601Date(final String isoString) {
this();
setDate(isoString);
}
private static Locale getLocale(final String locale) {
return Locale.forLanguageTag(locale);
}
public static MCRISO8601Date now() {
MCRISO8601Date instance = new MCRISO8601Date();
instance.setInstant(Instant.now());
return instance;
}
/**
* formats the date to a String.
*
* @param format
* as in {@link MCRISO8601Format}
* @param locale
* used by format process
* @return null if date is not set yet
*/
public String format(final String format, final Locale locale) {
return format(format, locale, null);
}
/**
* formats the date to a String.
*
* @param format
* as in {@link MCRISO8601Format}
* @param locale
* used by format process
* @param timeZone
* valid timeZone id, e.g. "Europe/Berlin", or null
* @return null if date is not set yet
*/
public String format(final String format, final Locale locale, String timeZone) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format,
Optional.ofNullable(locale)
.orElseGet(Locale::getDefault));
ZoneId zone = null;
if (timeZone != null) {
try {
zone = ZoneId.of(timeZone);
} catch (DateTimeException e) {
LOGGER.warn(e.getMessage());
}
}
if (zone == null) {
zone = ZoneId.systemDefault();
}
df = df.withZone(zone);
if (LOGGER.isDebugEnabled()) {
Object[] parameter = { dt, zone, dt != null ? df.format(dt) : null };
String msg = new MessageFormat("DateTime ''{0}'', using time zone ''{1}'', formatted: {2}", Locale.ROOT)
.format(parameter);
LOGGER.debug(msg);
}
String formatted = null;
try {
formatted = dt == null ? null : !format.contains("G") ? df.format(dt) : df.format(dt).replace("-", "");
} catch (Exception e) {
LOGGER.error("Could not format date", e);
}
return formatted;
}
/**
* returns the Date representing this element.
*
* @return a new Date instance of the time set in this element
*/
public final Date getDate() {
return dt == null ? null : Date.from(Instant.from(dt));
}
/**
* @return the dt
*/
public TemporalAccessor getDt() {
return dt;
}
/**
* @return the isoFormat
*/
public MCRISO8601Format getIsoFormat() {
return isoFormat;
}
/**
* returns a ISO 8601 conform String using the current set format.
*
* @return date in ISO 8601 format, or null if date is unset.
*/
public final String getISOString() {
return dt == null ? null : dateTimeFormatter.format(dt);
}
/**
* sets the date for this meta data object.
*
* @param dt
* Date object representing date String in Element
*/
public void setDate(final Date dt) {
if (dt == null) {
this.dt = null;
} else {
this.dt = dt.toInstant();
}
}
/**
* sets the date for this meta data object
*
* @param isoString
* Date in any form that is a valid W3C dateTime
*/
public final void setDate(final String isoString) {
TemporalAccessor dt = null;
try {
dt = getDateTime(MCRISO8601FormatChooser.cropSecondFractions(isoString));
} catch (final RuntimeException e) {
final boolean strictParsingEnabled = true;
if (!strictParsingEnabled) {
/*
* Last line of defence against the worst dates of the universe ;o)
*/
LOGGER.warn("Strict date parsing is disabled. This may result in incorrect dates.");
dt = guessDateTime(isoString);
} else {
LOGGER.debug("Error while parsing date, set date to NULL.", e);
dt = null;
}
}
setInstant(dt);
}
/**
* sets the input and output format. please use only the formats defined on the
* <a href="http://www.w3.org/TR/NOTE-datetime">W3C Page</a>, which are also exported as static fields by this
* class.
*/
public void setFormat(final MCRISO8601Format isoFormat) {
this.isoFormat = isoFormat;
dateTimeFormatter = MCRISO8601FormatChooser.getFormatter(null, this.isoFormat);
}
/**
* sets the input and output format. please use only the formats defined on the
* <a href="http://www.w3.org/TR/NOTE-datetime">W3C Page</a>, which are also exported as static fields by this
* class.
*
* @param format
* a format string that is valid conforming to xsd:duration schema type.
*/
public void setFormat(String format) {
setFormat(MCRISO8601Format.getFormat(format));
}
private TemporalAccessor getDateTime(final String timeString) {
dateTimeFormatter = MCRISO8601FormatChooser.getFormatter(timeString, isoFormat);
return dateTimeFormatter.parseBest(timeString, ZonedDateTime::from, LocalDateTime::from, LocalDate::from,
YearMonth::from,
Year::from);
}
private TemporalAccessor guessDateTime(final String date) {
final String locales = MCRConfiguration2.getString("MCR.Metadata.SimpleDateFormat.Locales").orElse("de_DE");
final StringTokenizer tok = new StringTokenizer(locales, ",");
while (tok.hasMoreTokens()) {
final Locale locale = getLocale(tok.nextToken());
final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.setLenient(true);
TemporalAccessor result = null;
try {
final Date pDate = df.parse(date);
result = pDate.toInstant();
return result;
} catch (final ParseException e) {
LOGGER.warn("Date guess failed for locale: {}", locale);
//we need no big exception in the logs, if we can't guess what it is, a warning should be enough
}
}
LOGGER.error("Error trying to guess date for string: {}", date);
return null;
}
private void setInstant(final TemporalAccessor dt) {
this.dt = dt;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MCRISO8601Date other = (MCRISO8601Date) obj;
return Objects.equals(this.dt, other.dt);
}
}
| 9,408 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLMetadataManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRXMLMetadataManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationBase;
import org.mycore.common.content.MCRByteContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* Provides an adapter to communicate with the configured {@link MCRXMLMetadataManagerAdapter} implementation.
*
* @author Christoph Neidahl (OPNA2608)
*/
public class MCRXMLMetadataManager {
/**
* Our own singleton.
*/
private static MCRXMLMetadataManager SINGLETON;
/**
* The implementation's singleton.
*/
private static MCRXMLMetadataManagerAdapter IMPLEMENTATION;
/**
* Reads the MCR.Metadata.Manager.Class to instantiate and return the configured xml metadata manager.
* If MCR.Metadata.Manager.Class is not set, an instance of {@link MCRDefaultXMLMetadataManager} is returned.
*
* @return an instance of the configured xml metadata manager if any is set, or MCRDefaultXMLMetadataManager
*/
public static synchronized MCRXMLMetadataManager instance() {
if (SINGLETON == null) {
SINGLETON = new MCRXMLMetadataManager();
}
if (IMPLEMENTATION == null) {
IMPLEMENTATION = MCRConfiguration2
.getSingleInstanceOf("MCR.Metadata.Manager", MCRDefaultXMLMetadataManager.class).get();
}
return SINGLETON;
}
/*
* Delegations to IMPLEMENTATION
*/
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#reload()
*/
public void reload() {
IMPLEMENTATION.reload();
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#verifyStore(String)
*/
public void verifyStore(String base) {
IMPLEMENTATION.verifyStore(base);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#create(MCRObjectID, MCRContent, Date)
*/
public void create(MCRObjectID mcrid, MCRContent xml, Date lastModified)
throws MCRPersistenceException {
IMPLEMENTATION.create(mcrid, xml, lastModified);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#delete(MCRObjectID)
*/
public void delete(MCRObjectID mcrid) throws MCRPersistenceException {
IMPLEMENTATION.delete(mcrid);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#update(MCRObjectID, MCRContent, Date)
*/
public void update(MCRObjectID mcrid, MCRContent xml, Date lastModified)
throws MCRPersistenceException {
IMPLEMENTATION.update(mcrid, xml, lastModified);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#retrieveContent(MCRObjectID)
*/
public MCRContent retrieveContent(MCRObjectID mcrid) throws IOException {
return IMPLEMENTATION.retrieveContent(mcrid);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#retrieveContent(MCRObjectID, String)
*/
public MCRContent retrieveContent(MCRObjectID mcrid, String revision) throws IOException {
return IMPLEMENTATION.retrieveContent(mcrid, revision);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#listRevisions(MCRObjectID)
*/
public List<? extends MCRAbstractMetadataVersion<?>> listRevisions(MCRObjectID id) throws IOException {
return IMPLEMENTATION.listRevisions(id);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#getHighestStoredID(String, String)
*/
public int getHighestStoredID(String project, String type) {
return IMPLEMENTATION.getHighestStoredID(project, type);
}
public int getHighestStoredID(String base) {
return IMPLEMENTATION.getHighestStoredID(
base.substring(0, base.indexOf("_")),
base.substring(base.indexOf("_") + 1));
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#exists(MCRObjectID)
*/
public boolean exists(MCRObjectID mcrid) throws MCRPersistenceException {
return IMPLEMENTATION.exists(mcrid);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#listIDsForBase(String)
*/
public List<String> listIDsForBase(String base) {
return IMPLEMENTATION.listIDsForBase(base);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#listIDsOfType(String)
*/
public List<String> listIDsOfType(String type) {
return IMPLEMENTATION.listIDsOfType(type);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#listIDs()
*/
public List<String> listIDs() {
return IMPLEMENTATION.listIDs();
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#getObjectTypes()
*/
public Collection<String> getObjectTypes() {
return IMPLEMENTATION.getObjectTypes();
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#getObjectBaseIds()
*/
public Collection<String> getObjectBaseIds() {
return IMPLEMENTATION.getObjectBaseIds();
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#retrieveObjectDates(List)
*/
public List<MCRObjectIDDate> retrieveObjectDates(List<String> ids) throws IOException {
return IMPLEMENTATION.retrieveObjectDates(ids);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#getLastModified(MCRObjectID)
*/
public long getLastModified(MCRObjectID id) throws IOException {
return IMPLEMENTATION.getLastModified(id);
}
/**
* Delegation, see linked method for relevant documentation.
*
* @see MCRXMLMetadataManagerAdapter#getLastModifiedHandle(MCRObjectID, long, TimeUnit)
*/
public MCRCache.ModifiedHandle getLastModifiedHandle(MCRObjectID id, long expire, TimeUnit unit) {
return IMPLEMENTATION.getLastModifiedHandle(id, expire, unit);
}
/*
* Redirections/wrappers to delegations
*/
/**
* Stores metadata of a new MCRObject in the persistent store.
*
* @param mcrid the MCRObjectID
* @param xml the xml metadata of the MCRObject
* @param lastModified the date of last modification to set
* @throws MCRPersistenceException the object couldn't be created due persistence problems
*/
public void create(MCRObjectID mcrid, Document xml, Date lastModified)
throws MCRPersistenceException {
create(mcrid, new MCRJDOMContent(xml), lastModified);
}
/**
* Stores metadata of a new MCRObject in the persistent store.
*
* @param mcrid the MCRObjectID
* @param xml the xml metadata of the MCRObject
* @param lastModified the date of last modification to set
* @throws MCRPersistenceException the object couldn't be created due persistence problems
*/
public void create(MCRObjectID mcrid, byte[] xml, Date lastModified) throws MCRPersistenceException {
create(mcrid, new MCRByteContent(xml, lastModified.getTime()), lastModified);
}
public void delete(String mcrid) throws MCRPersistenceException {
delete(MCRObjectID.getInstance(mcrid));
}
/**
* Updates metadata of existing MCRObject in the persistent store.
*
* @param mcrid the MCRObjectID
* @param xml the xml metadata of the MCRObject
* @param lastModified the date of last modification to set
* @throws MCRPersistenceException the object couldn't be updated due persistence problems
*/
public void update(MCRObjectID mcrid, Document xml, Date lastModified)
throws MCRPersistenceException {
update(mcrid, new MCRJDOMContent(xml), lastModified);
}
/**
* Creates or updates metadata of a MCRObject in the persistent store.
*
* @param mcrid the MCRObjectID
* @param xml the xml metadata of the MCRObject
* @param lastModified the date of last modification to set
* @throws MCRPersistenceException the object couldn't be created or updated due persistence problems
*/
public void createOrUpdate(MCRObjectID mcrid, Document xml, Date lastModified)
throws MCRPersistenceException {
if (exists(mcrid)) {
update(mcrid, xml, lastModified);
} else {
create(mcrid, xml, lastModified);
}
}
/**
* Updates metadata of existing MCRObject in the persistent store.
*
* @param mcrid the MCRObjectID
* @param xml the xml metadata of the MCRObject
* @param lastModified the date of last modification to set
* @throws MCRPersistenceException the object couldn't be updated due persistence problems
*/
public void update(MCRObjectID mcrid, byte[] xml, Date lastModified) throws MCRPersistenceException {
update(mcrid, new MCRByteContent(xml, lastModified.getTime()), lastModified);
}
/**
* Retrieves stored metadata xml as JDOM document
*
* @param mcrid the MCRObjectID
* @return null if metadata is not present
*/
public Document retrieveXML(MCRObjectID mcrid) throws IOException, JDOMException {
MCRContent metadata = retrieveContent(mcrid);
return metadata == null ? null : metadata.asXML();
}
/**
* Retrieves stored metadata xml as byte[] BLOB.
*
* @param mcrid the MCRObjectID
* @return null if metadata is not present
*/
public byte[] retrieveBLOB(MCRObjectID mcrid) throws IOException {
MCRContent metadata = retrieveContent(mcrid);
return metadata == null ? null : metadata.asByteArray();
}
/**
* Lists all objects with their last modification dates.
*
* @return List of {@link MCRObjectIDDate}
*/
public List<MCRObjectIDDate> listObjectDates() throws IOException {
return retrieveObjectDates(this.listIDs());
}
/**
* Lists all objects of the specified <code>type</code> and their last modified date.
*
* @param type type of object
*/
public List<MCRObjectIDDate> listObjectDates(String type) throws IOException {
return retrieveObjectDates(this.listIDsOfType(type));
}
/**
* Returns the time the store's content was last modified
*
* @return Last modification date of the MyCoRe system
*/
public long getLastModified() {
return MCRConfigurationBase.getSystemLastModified();
}
}
| 12,408 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLClassificationManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRXMLClassificationManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.IOException;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.classifications2.MCRCategoryID;
/**
* Interface for Classification Storage Manager
* @author Tobias Lenhardt [Hammer1279]
*/
public interface MCRXMLClassificationManager {
/**
* Load a Classification from the Store
* @param mcrid ID of the Category
* @return MCRContent
*/
default MCRContent retrieveContent(MCRCategoryID mcrid) throws IOException {
return retrieveContent(mcrid, null);
}
/**
* Load a Classification from the Store
* @param mcrid ID of the Category
* @param revision Revision of the Category
* @return MCRContent
*/
MCRContent retrieveContent(MCRCategoryID mcrid, String revision) throws IOException;
}
| 1,567 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRISO8601Format.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRISO8601Format.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.stream.Stream;
public enum MCRISO8601Format {
YEAR("UUUU"),
YEAR_MONTH("UUUU-MM"),
COMPLETE("UUUU-MM-DD"),
COMPLETE_HH_MM(
"UUUU-MM-DDThh:mmTZD"),
COMPLETE_HH_MM_SS("UUUU-MM-DDThh:mm:ssTZD"),
COMPLETE_HH_MM_SS_SSS(
"UUUU-MM-DDThh:mm:ss.sTZD"),
YEAR_ERA("YYYY"),
YEAR_MONTH_ERA("YYYY-MM"),
COMPLETE_ERA(
"YYYY-MM-DD"),
COMPLETE_HH_MM_ERA(
"YYYY-MM-DDThh:mmTZD"),
COMPLETE_HH_MM_SS_ERA("YYYY-MM-DDThh:mm:ssTZD"),
COMPLETE_HH_MM_SS_SSS_ERA(
"YYYY-MM-DDThh:mm:ss.sTZD");
private final String format;
MCRISO8601Format(String format) {
this.format = format;
}
@Override
public String toString() {
return format;
}
public static MCRISO8601Format getFormat(String format) {
return Stream.of(values())
.filter(f -> f.format.equals(format))
.findAny()
.orElse(null);
}
}
| 1,729 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRServiceFlagEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRServiceFlagEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRException;
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.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetaLinkID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectService;
/**
* This event handler sets the service flags "createdby" and "modifiedby" for users who created / modified a
* MyCoReObject and also added a state service flag using classification defined in
* "MCR.Metadata.Service.State.Classification.ID" (default "state") and category defined in
* "MCR.Metadata.Service.State.Category.Default" (default "submitted").
* If the state changes in an update event of an MCRObject the state gets propagated to all of it's derivates.
*
* @author Robert Stephan
* @author Thomas Scheffler (yagee)
*/
public class MCRServiceFlagEventHandler extends MCREventHandlerBase {
@Override
protected final void handleObjectCreated(MCREvent evt, MCRObject obj) {
if (!obj.isImportMode()) {
handleCreated(obj.getService());
setDefaultState(obj.getService());
}
}
@Override
protected final void handleObjectUpdated(MCREvent evt, MCRObject obj) {
if (!obj.isImportMode()) {
handleUpdated(obj.getService());
if (isStateChanged((MCRObject) evt.get(MCREvent.OBJECT_OLD_KEY), obj)) {
updateDerivateState(obj);
}
}
}
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
if (!der.isImportMode()) {
handleCreated(der.getService());
}
}
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
if (!der.isImportMode()) {
handleUpdated(der.getService());
}
}
protected static void handleCreated(MCRObjectService objService) {
objService.removeFlags(MCRObjectService.FLAG_TYPE_CREATEDBY);
objService.addFlag(MCRObjectService.FLAG_TYPE_CREATEDBY, MCRSessionMgr.getCurrentSession()
.getUserInformation().getUserID());
handleUpdated(objService);
}
protected static void setDefaultState(MCRObjectService objService) {
if (objService.getState() == null) {
MCRCategoryID defaultState = new MCRCategoryID(
MCRConfiguration2.getStringOrThrow("MCR.Metadata.Service.State.Classification.ID"),
MCRConfiguration2.getStringOrThrow("MCR.Metadata.Service.State.Category.Default"));
objService.setState(defaultState);
}
}
protected static void handleUpdated(MCRObjectService objectService) {
objectService.removeFlags(MCRObjectService.FLAG_TYPE_MODIFIEDBY);
objectService.addFlag(MCRObjectService.FLAG_TYPE_MODIFIEDBY,
MCRSessionMgr.getCurrentSession().getUserInformation().getUserID());
}
protected static boolean isStateChanged(MCRObject oldVersion, MCRObject obj) {
MCRCategoryID newState = obj.getService().getState();
return newState != null && oldVersion != null && !newState.equals(oldVersion.getService().getState());
}
protected static void updateDerivateState(MCRObject obj) {
MCRCategoryID state = obj.getService().getState();
obj
.getStructure()
.getDerivates()
.stream()
.map(MCRMetaLinkID::getXLinkHrefID)
.forEach(id -> updateDerivateState(id, state));
}
protected static void updateDerivateState(MCRObjectID derID, MCRCategoryID state) {
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derID);
MCRCategoryID oldState = derivate.getService().getState();
if (!state.equals(oldState)) {
derivate.getService().setState(state);
try {
MCRMetadataManager.update(derivate);
} catch (MCRAccessException e) {
throw new MCRException("Error while updating derivate state!", e);
}
}
}
}
| 5,174 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileBaseCacheObjectIDGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRFileBaseCacheObjectIDGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* This class generates object ids based on a file based cache. The cache is used to store the last generated id for a
* given base id. The cache file is located in the data directory of MyCoRe and is named "id_cache" and contains one
* file for each base id. The file contains the last generated id as a string.
*/
public class MCRFileBaseCacheObjectIDGenerator implements MCRObjectIDGenerator {
private static final Logger LOGGER = LogManager.getLogger();
static ConcurrentHashMap<String, ReentrantReadWriteLock> locks = new ConcurrentHashMap<>();
private static Path getCacheFilePath(String baseId) {
Path idCachePath = getCacheDirPath();
Path cacheFile = MCRUtils.safeResolve(idCachePath, baseId);
if (Files.exists(cacheFile)) {
return cacheFile;
}
synchronized (MCRFileBaseCacheObjectIDGenerator.class) {
if (!Files.exists(cacheFile)) {
try {
return Files.createFile(cacheFile);
} catch (IOException e) {
throw new MCRException("Could not create " + cacheFile.toAbsolutePath(), e);
}
}
}
return cacheFile;
}
private static Path getCacheDirPath() {
Path dataDir = getDataDirPath();
Path idCachePath = dataDir.resolve("id_cache");
if (Files.exists(idCachePath)) {
return idCachePath;
}
synchronized (MCRFileBaseCacheObjectIDGenerator.class) {
if (!Files.exists(idCachePath)) {
try {
Files.createDirectory(idCachePath);
} catch (IOException e) {
throw new MCRException("Could not create " + idCachePath.toAbsolutePath() + " directory", e);
}
}
}
return idCachePath;
}
static Path getDataDirPath() {
Path path = Paths.get(MCRConfiguration2.getStringOrThrow("MCR.datadir"));
if (Files.exists(path) && !Files.isDirectory(path)) {
throw new MCRException("Data directory does not exist or is not a directory: " + path);
}
return path;
}
private static void writeNewID(MCRObjectID nextID, ByteBuffer buffer, FileChannel channel, Path cacheFile)
throws IOException {
buffer.clear();
channel.position(0);
byte[] idAsBytes = nextID.toString().getBytes(StandardCharsets.UTF_8);
buffer.put(idAsBytes);
buffer.flip();
int written = channel.write(buffer);
if (written != idAsBytes.length) {
throw new MCRException("Could not write new ID to " + cacheFile.toAbsolutePath());
}
}
/**
* Set the next free id for the given baseId. Should only be used for migration purposes and the caller has to make
* sure that the cache file is not used by another process.
* @param baseId the base id
* @param next the next free id to be returned by getNextFreeId
*/
public void setNextFreeId(String baseId, int next) {
Path cacheFile = getCacheFilePath(baseId);
int idLengthInBytes = MCRObjectID.formatID(baseId, 1).getBytes(StandardCharsets.UTF_8).length;
try (
FileChannel channel = FileChannel.open(cacheFile, StandardOpenOption.WRITE,
StandardOpenOption.SYNC, StandardOpenOption.CREATE);){
ByteBuffer buffer = ByteBuffer.allocate(idLengthInBytes);
channel.position(0);
writeNewID(MCRObjectID.getInstance(MCRObjectID.formatID(baseId, next-1)), buffer, channel, cacheFile);
} catch (FileNotFoundException e) {
throw new MCRException("Could not create " + cacheFile.toAbsolutePath(), e);
} catch (IOException e) {
throw new MCRException("Could not open " + cacheFile.toAbsolutePath(), e);
}
}
@Override
public MCRObjectID getNextFreeId(String baseId, int maxInWorkflow) {
Path cacheFile = getCacheFilePath(baseId);
MCRObjectID nextID;
ReentrantReadWriteLock lock = locks.computeIfAbsent(baseId, k -> new ReentrantReadWriteLock());
ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
try {
writeLock.lock();
try (
FileChannel channel = FileChannel.open(cacheFile, StandardOpenOption.READ, StandardOpenOption.WRITE,
StandardOpenOption.SYNC);
FileLock fileLock = channel.lock()) {
int idLengthInBytes = MCRObjectID.formatID(baseId, 1).getBytes(StandardCharsets.UTF_8).length;
ByteBuffer buffer = ByteBuffer.allocate(idLengthInBytes);
buffer.clear();
channel.position(0);
int bytesRead = channel.read(buffer);
if (bytesRead <= 0) {
LOGGER.info("No ID found in " + cacheFile.toAbsolutePath());
// empty file -> new currentID is 1
nextID = MCRObjectID.getInstance(MCRObjectID.formatID(baseId, maxInWorkflow + 1));
writeNewID(nextID, buffer, channel, cacheFile);
} else if (bytesRead == idLengthInBytes) {
buffer.flip();
MCRObjectID objectID = readObjectIDFromBuffer(idLengthInBytes, buffer);
int lastID = objectID.getNumberAsInteger();
nextID = MCRObjectID.getInstance(MCRObjectID.formatID(baseId, lastID + maxInWorkflow + 1));
writeNewID(nextID, buffer, channel, cacheFile);
} else {
throw new MCRException("Content has different id length " + cacheFile.toAbsolutePath());
}
} catch (FileNotFoundException e) {
throw new MCRException("Could not create " + cacheFile.toAbsolutePath(), e);
} catch (IOException e) {
throw new MCRException("Could not open " + cacheFile.toAbsolutePath(), e);
}
} finally {
writeLock.unlock();
}
return nextID;
}
private static MCRObjectID readObjectIDFromBuffer(int idLengthBytes, ByteBuffer buffer) {
byte[] idBytes = new byte[idLengthBytes];
buffer.get(idBytes);
String lastIDString = new String(idBytes, StandardCharsets.UTF_8);
return MCRObjectID.getInstance(lastIDString);
}
@Override
public MCRObjectID getLastID(String baseId) {
Path cacheFilePath = getCacheFilePath(baseId);
ReentrantReadWriteLock lock = locks.computeIfAbsent(baseId, k -> new ReentrantReadWriteLock());
ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
try {
readLock.lock();
int idLengthInBytes = MCRObjectID.formatID(baseId, 1).getBytes(StandardCharsets.UTF_8).length;
try (FileChannel channel = FileChannel.open(cacheFilePath)) {
ByteBuffer buffer = ByteBuffer.allocate(idLengthInBytes);
buffer.clear();
channel.position(0);
int bytesRead = channel.read(buffer);
if (bytesRead == -1) {
// empty file -> no ID found
return null;
} else if (bytesRead == idLengthInBytes) {
buffer.flip();
return readObjectIDFromBuffer(idLengthInBytes, buffer);
} else {
throw new MCRException("Content has different id length " + cacheFilePath.toAbsolutePath());
}
} catch (IOException e) {
throw new MCRException("Could not open " + cacheFilePath.toAbsolutePath(), e);
}
} finally {
readLock.unlock();
}
}
@Override
public Collection<String> getBaseIDs() {
Path cacheDir = getCacheDirPath();
try (Stream<Path> list = Files.list(cacheDir);) {
List<String> baseIdList = list.filter(Files::isRegularFile)
.map(Path::getFileName).map(Path::toString)
.collect(Collectors.toList());
return baseIdList;
} catch (IOException e) {
throw new MCRException("Could not detect cache files!", e);
}
}
}
| 9,897 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLinkTableEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRLinkTableEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
/**
* This class manages all operations of the LinkTables for operations of an object.
*
* @author Jens Kupferschmidt
*/
public class MCRLinkTableEventHandler extends MCREventHandlerBase {
/**
* This method add the data to the link and classification table via MCRLinkTableManager.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected final void handleObjectCreated(MCREvent evt, MCRObject obj) {
MCRLinkTableManager.instance().create(obj);
}
/**
* This method update the data to the link and classification table via MCRLinkTableManager.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected final void handleObjectUpdated(MCREvent evt, MCRObject obj) {
handleObjectRepaired(evt, obj);
}
/**
* This method delete the data from the link and classification table via MCRLinkTableManager.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected final void handleObjectDeleted(MCREvent evt, MCRObject obj) {
MCRLinkTableManager.instance().delete(obj.getId());
}
/**
* This method repair the data from the link and classification table via MCRLinkTableManager.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected final void handleObjectRepaired(MCREvent evt, MCRObject obj) {
MCRLinkTableManager.instance().update(obj.getId());
}
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
MCRLinkTableManager.instance().create(der);
}
@Override
protected void handleDerivateRepaired(MCREvent evt, MCRDerivate der) {
MCRLinkTableManager.instance().update(der.getId());
}
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
handleDerivateRepaired(evt, der);
}
@Override
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
MCRLinkTableManager.instance().delete(der.getId());
}
}
| 3,360 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRISO8601FormatChooser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRISO8601FormatChooser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.YEAR;
import java.time.ZoneOffset;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* is a helper class for MCRMetaISO8601Date. Please be aware that this class is not supported. It may disappear some day
* or methods get removed.
*
* @author Thomas Scheffler (yagee)
* @since 1.3
*/
public final class MCRISO8601FormatChooser {
public static final DateTimeFormatter YEAR_FORMAT = ISODateTimeFormat.year();
public static final DateTimeFormatter YEAR_MONTH_FORMAT = ISODateTimeFormat.yearMonth();
public static final DateTimeFormatter COMPLETE_FORMAT = ISODateTimeFormat.date();
public static final DateTimeFormatter COMPLETE_HH_MM_FORMAT = ISODateTimeFormat.dateHourMinute();
public static final DateTimeFormatter COMPLETE_HH_MM_SS_FORMAT = ISODateTimeFormat.dateTimeNoMillis();
public static final DateTimeFormatter COMPLETE_HH_MM_SS_SSS_FORMAT = ISODateTimeFormat.dateTime();
private static final Pattern MILLI_CHECK_PATTERN = Pattern.compile("\\.\\d{4,}\\+");
private static final boolean USE_UTC = true;
/**
* returns a DateTimeFormatter for the given isoString or format. This method prefers the format parameter. So if
* it's not null or not zero length this method will interpret the format string. You can also get a formatter for e
* specific iso String. In either case if the underlying algorithm can not determine an exact matching formatter it
* will allway fall back to a default. So this method will never return null.
*
* @param isoString
* an ISO 8601 formatted time String, or null
* @param isoFormat
* a valid format String, or null
* @return returns a specific DateTimeFormatter
*/
public static DateTimeFormatter getFormatter(String isoString, MCRISO8601Format isoFormat) {
DateTimeFormatter df;
if (isoFormat != null) {
df = getFormatterForFormat(isoFormat);
} else if (isoString != null && isoString.length() != 0) {
df = getFormatterForDuration(isoString);
} else {
df = COMPLETE_HH_MM_SS_SSS_FORMAT;
}
if (USE_UTC) {
df = df.withZone(ZoneOffset.UTC);
}
return df;
}
private static DateTimeFormatter getFormatterForFormat(MCRISO8601Format isoFormat) {
return switch (isoFormat) {
case YEAR -> YEAR_FORMAT;
case YEAR_MONTH -> YEAR_MONTH_FORMAT;
case COMPLETE -> COMPLETE_FORMAT;
case COMPLETE_HH_MM -> COMPLETE_HH_MM_FORMAT;
case COMPLETE_HH_MM_SS -> COMPLETE_HH_MM_SS_FORMAT;
case COMPLETE_HH_MM_SS_SSS -> COMPLETE_HH_MM_SS_SSS_FORMAT;
case YEAR_ERA -> YEAR_FORMAT;
case YEAR_MONTH_ERA -> YEAR_MONTH_FORMAT;
case COMPLETE_ERA -> COMPLETE_FORMAT;
case COMPLETE_HH_MM_ERA -> COMPLETE_HH_MM_FORMAT;
case COMPLETE_HH_MM_SS_ERA -> COMPLETE_HH_MM_SS_FORMAT;
case COMPLETE_HH_MM_SS_SSS_ERA -> COMPLETE_HH_MM_SS_SSS_FORMAT;
default -> COMPLETE_HH_MM_SS_SSS_FORMAT;
};
}
private static DateTimeFormatter getFormatterForDuration(String isoString) {
boolean test = false;
switch (isoString.length()) {
case 1:
case 2:
case 3:
case 4:
case 5:
return YEAR_FORMAT;
case 6:
case 7:
case 8:
return YEAR_MONTH_FORMAT;
case 10:
case 11:
return COMPLETE_FORMAT;
case 17: // YYYY-MM-DDThh:mm'Z'
test = true;
case 22:
if (test || !isoString.endsWith("Z")) {
// YYYY-MM-DDThh:mm[+-]hh:mm
return COMPLETE_HH_MM_FORMAT;
}
// YYYY-MM-DDThh:mm:ss.s'Z'
return COMPLETE_HH_MM_SS_SSS_FORMAT;
case 20: // YYYY-MM-DDThh:mm:ss'Z'
case 25: // YYYY-MM-DDThh:mm:ss[+-]hh:mm
return COMPLETE_HH_MM_SS_FORMAT;
case 23: // YYYY-MM-DDThh:mm:ss.ss'Z'
case 24: // YYYY-MM-DDThh:mm:ss.sss'Z'
case 27: // YYYY-MM-DDThh:mm:ss.s[+-]hh:mm
case 28: // YYYY-MM-DDThh:mm:ss.ss[+-]hh:mm
case 29: // YYYY-MM-DDThh:mm:ss.ss[+-]hh:mm
return COMPLETE_HH_MM_SS_SSS_FORMAT;
default:
return COMPLETE_HH_MM_SS_SSS_FORMAT;
}
}
/**
* returns a String that has not more than 3 digits representing "fractions of a second". If isoString has no or not
* more than 3 digits this method simply returns isoString.
*
* @param isoString
* an ISO 8601 formatted time String
* @return an ISO 8601 formatted time String with at max 3 digits for fractions of a second
*/
public static String cropSecondFractions(String isoString) {
Matcher matcher = MILLI_CHECK_PATTERN.matcher(isoString);
boolean result = matcher.find();
if (result) {
return matcher.replaceFirst(isoString.substring(matcher.start(), matcher.start() + 4) + "+");
}
return isoString;
}
private static class ISODateTimeFormat {
public static DateTimeFormatter year() {
return DateTimeFormatter.ofPattern("uuuu", Locale.ROOT);
}
public static DateTimeFormatter yearMonth() {
return DateTimeFormatter.ofPattern("uuuu-MM", Locale.ROOT);
}
public static DateTimeFormatter date() {
return DateTimeFormatter.ISO_LOCAL_DATE;
}
public static DateTimeFormatter dateHourMinute() {
return new DateTimeFormatterBuilder().parseCaseInsensitive()
.appendValue(YEAR, 4)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral('T')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendOffset("+HH:MM", "Z")
.toFormatter(Locale.ROOT)
.withChronology(IsoChronology.INSTANCE)
.withResolverStyle(ResolverStyle.STRICT);
}
public static DateTimeFormatter dateTimeNoMillis() {
return new DateTimeFormatterBuilder().parseCaseInsensitive()
.appendValue(YEAR, 4)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral('T')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.appendOffset("+HH:MM", "Z")
.toFormatter(Locale.ROOT)
.withChronology(IsoChronology.INSTANCE)
.withResolverStyle(ResolverStyle.STRICT);
}
public static DateTimeFormatter dateTime() {
return new DateTimeFormatterBuilder().parseCaseInsensitive()
.appendValue(YEAR, 4)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral('T')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.appendFraction(ChronoField.NANO_OF_SECOND, 3, 3, true)
.appendOffset("+HH:MM", "Z")
.toFormatter(Locale.ROOT)
.withChronology(IsoChronology.INSTANCE)
.withResolverStyle(ResolverStyle.STRICT);
}
}
}
| 9,321 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRObjectIDGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.Collection;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* central generator for new MyCoRe Object IDs.
*
* @author Robert Stephan
*
*/
public interface MCRObjectIDGenerator {
/**
* Returns a MCRObjectID from a given base ID string. A base ID is
* <em>project_id</em>_<em>type_id</em>.
* The number is computed by this method.
*
* @param baseId
* <em>project_id</em>_<em>type_id</em>
*/
default MCRObjectID getNextFreeId(String baseId) {
return getNextFreeId(baseId, 0);
}
/**
* Returns a MCRObjectID from a given the components of a base ID string. A base ID is
* <em>project_id</em>_<em>type_id</em>. The number is computed by this method.
*
* @param projectId
* The first component of <em>project_id</em>_<em>type_id</em>
* @param type
* The second component of <em>project_id</em>_<em>type_id</em>
*/
default MCRObjectID getNextFreeId(String projectId, String type) {
return getNextFreeId(projectId + "_" + type);
}
/**
* Returns a MCRObjectID from a given base ID string. Same as
* {@link #getNextFreeId(String)} but the additional parameter acts as a
* lower limit for integer part of the ID.
*
* @param baseId
* <em>project_id</em>_<em>type_id</em>
* @param maxInWorkflow
* returned integer part of id will be at least
* <code>maxInWorkflow + 1</code>
*/
MCRObjectID getNextFreeId(String baseId, int maxInWorkflow);
/**
* Returns the last ID used or reserved for the given object base type.
*
* @return a valid MCRObjectID, or null when there is no ID for the given
* type
*/
MCRObjectID getLastID(String baseId);
/**
* Returns all the base IDs that have been used to generate object IDs.
* @return a collection of base IDs
*/
Collection<String> getBaseIDs();
}
| 2,775 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultObjectIDGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/common/MCRDefaultObjectIDGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.common;
import java.util.Collection;
import java.util.HashMap;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* default implementation for generator of MyCoRe Object IDs.
*
* @author Robert Stephan
*
*/
// code was moved from MCRObjectID into this class
public class MCRDefaultObjectIDGenerator implements MCRObjectIDGenerator {
// counter for the next IDs per project base ID
private HashMap<String, Integer> lastNumber = new HashMap<>();
/**
* First invocation may return MCR.Metadata.ObjectID.InitialNumberDistance if set,
* following invocations will return MCR.Metadata.ObjectID.NumberDistance.
* The default for both is 1.
*/
private int numberDistance = MCRConfiguration2.getInt("MCR.Metadata.ObjectID.InitialNumberDistance")
.orElse(MCRConfiguration2.getInt("MCR.Metadata.ObjectID.NumberDistance").orElse(1));
/**
* Returns a MCRObjectID from a given base ID string
* The additional parameter acts as a
* lower limit for integer part of the ID.
*
* Otherwise it is the next free number of an item in the database for the
* given project ID and type ID, with the following additional restriction:
* The ID returned can be divided by the configured numberDistance without remainder.
* The ID returned minus the last ID returned is at least the configured numberDistance.
*
* Example for number distance of 1 (default):
* last ID = 7, next ID = 8
* last ID = 8, next ID = 9
*
* Example for number distance of 2:
* last ID = 7, next ID = 10
* last ID = 8, next ID = 10
* last ID = 10, next ID = 20
*
*
* @param baseId
* <em>project_id</em>_<em>type_id</em>
* @param maxInWorkflow
* returned integer part of id will be at least
* <code>maxInWorkflow + 1</code>
*/
public synchronized MCRObjectID getNextFreeId(String baseId, int maxInWorkflow) {
int last = Math.max(getLastIDNumber(baseId), maxInWorkflow);
int next = last + numberDistance;
int rest = next % numberDistance;
if (rest != 0) {
next += numberDistance - rest;
}
lastNumber.put(baseId, next);
return MCRObjectID.getInstance(MCRObjectID.formatID(baseId, next));
}
/**
* Returns the last ID used or reserved for the given object base type.
*
* @return a valid MCRObjectID, or null when there is no ID for the given
* type
*/
public synchronized MCRObjectID getLastID(String baseId) {
int lastIDNumber = getLastIDNumber(baseId);
if (lastIDNumber == 0) {
return null;
}
return MCRObjectID.getInstance(MCRObjectID.formatID(baseId, lastIDNumber));
}
@Override
public Collection<String> getBaseIDs() {
return MCRXMLMetadataManager.instance().getObjectBaseIds();
}
/**
* Returns the last ID number used or reserved for the given object base
* type. This may return the value 0 when there is no ID last used or in the
* store.
*/
private int getLastIDNumber(String baseId) {
int lastIDKnown = lastNumber.getOrDefault(baseId, 0);
int highestStoredID = MCRXMLMetadataManager.instance().getHighestStoredID(baseId);
return Math.max(lastIDKnown, highestStoredID);
}
}
| 4,208 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMD5AttributeView.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRMD5AttributeView.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.io.IOException;
import java.nio.file.attribute.BasicFileAttributeView;
/**
* @author Thomas Scheffler (yagee)
*
*/
public interface MCRMD5AttributeView<T> extends BasicFileAttributeView {
/**
* Returns the name of the attribute view. Attribute views of this type have the name "md5".
*/
@Override
String name();
MCRFileAttributes<T> readAllAttributes() throws IOException;
}
| 1,184 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPathXML.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPathXML.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import static org.mycore.datamodel.niofs.MCRAbstractFileSystem.SEPARATOR;
import static org.mycore.datamodel.niofs.MCRAbstractFileSystem.SEPARATOR_STRING;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SecureDirectoryStream;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Collection;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.mycore.common.MCRConstants;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* @author Thomas Scheffler (yagee)
*/
public class MCRPathXML {
static Logger LOGGER = LogManager.getLogger(MCRPathXML.class);
private MCRPathXML() {
}
public static Document getDirectoryXML(MCRPath path) throws IOException {
BasicFileAttributes attr = path.getFileSystem().provider().readAttributes(path, BasicFileAttributes.class);
return getDirectoryXML(path, attr);
}
/**
* Sends the contents of an MCRDirectory as XML data to the client
*/
public static Document getDirectoryXML(MCRPath path, BasicFileAttributes attr) throws IOException {
LOGGER.debug("MCRDirectoryXML: start listing of directory {}", path);
Element root = new Element("mcr_directory");
Document doc = new Document(root);
addString(root, "uri", path.toUri().toString(), false);
addString(root, "ownerID", path.getOwner(), false);
MCRPath relativePath = path.getRoot().relativize(path);
boolean isRoot = relativePath.toString().isEmpty();
addString(root, "name", (isRoot ? "" : relativePath.getFileName().toString()), true);
addString(root, "path", toStringValue(relativePath), true);
if (!isRoot) {
addString(root, "parentPath", toStringValue(relativePath.getParent()), true);
}
addBasicAttributes(root, attr, path);
Element numChildren = new Element("numChildren");
Element here = new Element("here");
root.addContent(numChildren);
numChildren.addContent(here);
Element nodes = new Element("children");
root.addContent(nodes);
SortedMap<MCRPath, MCRFileAttributes<?>> directories = new TreeMap<>();
SortedMap<MCRPath, MCRFileAttributes<?>> files = new TreeMap<>();
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path)) {
LOGGER.debug(() -> "Opened DirectoryStream for " + path);
Function<Path, MCRFileAttributes<?>> attrResolver = p -> {
try {
return Files.readAttributes(p, MCRFileAttributes.class);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
if (dirStream instanceof SecureDirectoryStream) {
//fast path
LOGGER.debug(() -> "Using SecureDirectoryStream code path for " + path);
attrResolver = p -> {
try {
MCRMD5AttributeView attributeView = ((SecureDirectoryStream<Path>) dirStream)
.getFileAttributeView(p.getFileName(), MCRMD5AttributeView.class);
return attributeView.readAllAttributes();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
for (Path child : dirStream) {
MCRFileAttributes<?> childAttrs;
try {
childAttrs = attrResolver.apply(child);
} catch (UncheckedIOException e) {
throw e.getCause();
}
if (childAttrs.isDirectory()) {
directories.put(MCRPath.toMCRPath(child), childAttrs);
} else {
files.put(MCRPath.toMCRPath(child), childAttrs);
}
}
}
//store current directory statistics
addString(here, "directories", Integer.toString(directories.size()), false);
addString(here, "files", Integer.toString(files.size()), false);
for (Map.Entry<MCRPath, MCRFileAttributes<?>> dirEntry : directories.entrySet()) {
Element child = new Element("child");
child.setAttribute("type", "directory");
addString(child, "name", dirEntry.getKey().getFileName().toString(), true);
addString(child, "uri", dirEntry.getKey().toUri().toString(), false);
nodes.addContent(child);
addBasicAttributes(child, dirEntry.getValue(), dirEntry.getKey());
}
for (Map.Entry<MCRPath, MCRFileAttributes<?>> fileEntry : files.entrySet()) {
Element child = new Element("child");
child.setAttribute("type", "file");
addString(child, "name", fileEntry.getKey().getFileName().toString(), true);
addString(child, "uri", fileEntry.getKey().toUri().toString(), false);
nodes.addContent(child);
addAttributes(child, fileEntry.getValue(), fileEntry.getKey());
}
LOGGER.debug("MCRDirectoryXML: end listing of directory {}", path);
return doc;
}
/**
* Returns metadata of the file retrievable by 'path' in XML form. Same as
* {@link #getFileXML(MCRPath, BasicFileAttributes)}, but attributes are retrieved first.
*/
public static Document getFileXML(MCRPath path) throws IOException {
MCRFileAttributes<?> attrs = Files.readAttributes(path, MCRFileAttributes.class);
return getFileXML(path, attrs);
}
/**
* Returns metadata of the file retrievable by 'path' in XML form.
*
* @param path
* Path to File
* @param attrs
* file attributes of given file
*/
public static Document getFileXML(MCRPath path, BasicFileAttributes attrs) throws IOException {
Element root = new Element("file");
root.setAttribute("uri", path.toUri().toString());
root.setAttribute("ownerID", path.getOwner());
String fileName = path.getFileName().toString();
root.setAttribute("name", fileName);
String absolutePath = path.getOwnerRelativePath();
root.setAttribute("path", absolutePath);
root.setAttribute("extension", getFileExtension(fileName));
root.setAttribute("returnId",
MCRMetadataManager.getObjectId(MCRObjectID.getInstance(path.getOwner()), 10, TimeUnit.SECONDS).toString());
Collection<MCRCategoryID> linksFromReference = MCRCategLinkServiceFactory.getInstance().getLinksFromReference(
new MCRCategLinkReference(path));
for (MCRCategoryID category : linksFromReference) {
Element catEl = new Element("category");
catEl.setAttribute("id", category.toString());
root.addContent(catEl);
}
if (!attrs.isDirectory() && attrs instanceof MCRFileAttributes<?> fAttrs) {
addAttributes(root, fAttrs, path);
} else {
addBasicAttributes(root, attrs, path);
}
return new Document(root);
}
private static String getFileExtension(String fileName) {
if (fileName.endsWith(".")) {
return "";
}
int pos = fileName.lastIndexOf(".");
return pos == -1 ? "" : fileName.substring(pos + 1);
}
private static String toStringValue(MCRPath relativePath) {
if (relativePath == null) {
return SEPARATOR_STRING;
}
String pathString = relativePath.toString();
if (pathString.isEmpty()) {
return SEPARATOR_STRING;
}
if (pathString.equals(SEPARATOR_STRING)) {
return pathString;
}
return SEPARATOR + pathString + SEPARATOR;
}
private static void addBasicAttributes(Element root, BasicFileAttributes attr, MCRPath path) throws IOException {
addString(root, "size", String.valueOf(attr.size()), false);
addDate(root, "created", attr.creationTime());
addDate(root, "lastModified", attr.lastModifiedTime());
addDate(root, "lastAccessed", attr.lastAccessTime());
if (attr.isRegularFile()) {
addString(root, "contentType", MCRContentTypes.probeContentType(path), false);
}
}
private static void addAttributes(Element root, MCRFileAttributes<?> attr, MCRPath path) throws IOException {
addBasicAttributes(root, attr, path);
addString(root, "md5", attr.md5sum(), false);
}
private static void addDate(Element parent, String type, FileTime date) {
Element xDate = new Element("date");
parent.addContent(xDate);
xDate.setAttribute("type", type);
xDate.addContent(date.toString());
}
private static void addString(Element parent, String itemName, String content, boolean preserve) {
if (content == null) {
return;
}
Element child = new Element(itemName).addContent(content);
if (preserve) {
child.setAttribute("space", "preserve", MCRConstants.XML_NAMESPACE);
}
parent.addContent(child);
}
}
| 10,584 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Contains abstract classes and factories to build a {@link java.nio.file.FileSystem}
* on top of different implementations.
* @author Thomas Scheffler (yagee)
*
*/
package org.mycore.datamodel.niofs;
| 937 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGlobPathMatcher.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRGlobPathMatcher.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.nio.file.FileSystem;
import java.nio.file.PathMatcher;
import java.util.Optional;
import java.util.regex.Pattern;
import org.mycore.common.function.MCRFunctions;
/**
* @author Thomas Scheffler
*
*/
public class MCRGlobPathMatcher extends MCRPathMatcher {
/**
* A {@link PathMatcher} that accepts 'glob' syntax
* @param globPattern pattern in {@link FileSystem#getPathMatcher(String) 'glob' syntax}
*/
public MCRGlobPathMatcher(final String globPattern) {
super(globPattern);
}
@Override
protected Pattern getPattern(final String globPattern) {
return Optional.of(globPattern)
.map(MCRFunctions::convertGlobToRegex)
.map(Pattern::compile)
.get();
}
}
| 1,524 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRContentTypes.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRContentTypes.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.spi.FileTypeDetector;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRContentTypes {
private static final Logger LOGGER = LogManager.getLogger(MCRContentTypes.class);
private static List<FileTypeDetector> fileTypeDetectors;
static {
try {
fileTypeDetectors = getInstalledDetectors();
} catch (Exception exc) {
LOGGER.error("Unable to retrieve installed file type detectors", exc);
}
}
private MCRContentTypes() {
}
private static List<FileTypeDetector> getInstalledDetectors() {
ArrayList<FileTypeDetector> detectors = new ArrayList<>();
ServiceLoader<FileTypeDetector> serviceLoader = ServiceLoader.load(FileTypeDetector.class);
for (FileTypeDetector fileTypeDetector : serviceLoader) {
LOGGER.info("Adding content type detector: {}", fileTypeDetector.getClass());
detectors.add(fileTypeDetector);
}
return detectors;
}
/**
* Probes the content type of a file.
*
* Same as {@link Files#probeContentType(Path)} but uses context class loader.
* @param path
* the path to the file to probe
* @return The content type of the file, or null if the content type cannot be determined
* @throws IOException if an I/O error occurs
*/
public static String probeContentType(Path path) throws IOException {
LOGGER.debug("Probing content type: {}", path);
for (FileTypeDetector fileTypeDetector : fileTypeDetectors) {
LOGGER.debug("Using type detector: {}", fileTypeDetector.getClass());
String contentType = fileTypeDetector.probeContentType(path);
if (contentType != null) {
LOGGER.debug("Content type: {}", contentType);
return contentType;
}
}
return Files.probeContentType(path);
}
}
| 2,957 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractFileSystem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRAbstractFileSystem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.WatchService;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.spi.FileSystemProvider;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
public abstract class MCRAbstractFileSystem extends FileSystem {
public static final char SEPARATOR = '/';
public static final String SEPARATOR_STRING = String.valueOf(SEPARATOR);
private final LoadingCache<String, MCRPath> rootDirectoryCache = CacheBuilder.newBuilder().weakValues()
.build(new CacheLoader<>() {
@Override
public MCRPath load(final String owner) {
return getPath(owner, "/", instance());
}
});
private final MCRPath emptyPath;
public MCRAbstractFileSystem() {
super();
emptyPath = getPath(null, "", this);
}
/**
* Returns any subclass that implements and handles the given scheme.
* @param scheme a valid {@link URI} scheme
* @see FileSystemProvider#getScheme()
* @throws FileSystemNotFoundException if no filesystem handles this scheme
*/
public static MCRAbstractFileSystem getInstance(String scheme) {
URI uri;
try {
uri = MCRPaths.getURI(scheme, "helper", SEPARATOR_STRING);
} catch (URISyntaxException e) {
throw new MCRException(e);
}
for (FileSystemProvider provider : Iterables.concat(MCRPaths.webAppProvider,
FileSystemProvider.installedProviders())) {
if (provider.getScheme().equals(scheme)) {
return (MCRAbstractFileSystem) provider.getFileSystem(uri);
}
}
throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not found");
}
public static MCRPath getPath(final String owner, final String path, final MCRAbstractFileSystem fs) {
Objects.requireNonNull(fs, MCRAbstractFileSystem.class.getSimpleName() + " instance may not be null.");
return new MCRPath(owner, path) {
@Override
public MCRAbstractFileSystem getFileSystem() {
return fs;
}
};
}
/**
* Creates a new root under the given name.
*
* After calling this method the implementing FileSystem should
* be ready to accept data for this root.
*
* @param owner ,e.g. derivate ID
* @throws FileSystemException if creating the root directory fails
* @throws FileAlreadyExistsException more specific, if the directory already exists
*/
public abstract void createRoot(String owner) throws FileSystemException;
/**
* Checks if the file for given Path is still valid.
*
* This should check if the file is still completely readable and the MD5 sum still matches the recorded value.
* @param path Path to the file to check
* @return if the file is still in good condition
*/
public boolean verifies(MCRPath path) throws NoSuchFileException {
try {
return verifies(path, Files.readAttributes(path, MCRFileAttributes.class));
} catch (NoSuchFileException nsfe) {
throw nsfe;
} catch (IOException e) {
return false;
}
}
/**
* Checks if the file for given Path is still valid.
*
* This should check if the file is still completely readable and the MD5 sum still matches the recorded value.
* This method does the same as {@link #verifies(MCRPath)} but uses the given attributes to save a file access.
* @param path Path to the file to check
* @param attrs matching attributes to file
*/
public boolean verifies(MCRPath path, MCRFileAttributes<?> attrs) throws NoSuchFileException {
if (Files.notExists(Objects.requireNonNull(path, "Path may not be null."))) {
throw new NoSuchFileException(path.toString());
}
Objects.requireNonNull(attrs, "attrs may not be null");
String md5Sum;
try {
md5Sum = MCRUtils.getMD5Sum(Files.newInputStream(path));
} catch (IOException e) {
LogManager.getLogger(getClass()).error("Could not verify path: {}", path, e);
return false;
}
boolean returns = md5Sum.matches(attrs.md5sum());
if (!returns) {
LogManager.getLogger(getClass()).warn("MD5sum does not match: {}", path);
}
return returns;
}
/**
* Removes a root with the given name.
*
* Call this method if you want to remove a stalled directory that is not in use anymore.
*
* @param owner ,e.g. derivate ID
* @throws FileSystemException if removing the root directory fails
* @throws DirectoryNotEmptyException more specific, if the directory is not empty
* @throws NoSuchFileException more specific, if the directory does not exist
*/
public abstract void removeRoot(String owner) throws FileSystemException;
@Override
public void close() {
throw new UnsupportedOperationException();
}
public MCRPath emptyPath() {
return emptyPath;
}
@Override
public Path getPath(final String first, final String... more) {
String root = null;
final StringBuilder path = new StringBuilder();
if (!first.isEmpty() && first.charAt(first.length() - 1) == ':') {
//we have a root;
root = first;
path.append(SEPARATOR);
} else {
path.append(first);
}
boolean addSep = path.length() > 0;
for (final String element : more) {
if (!element.isEmpty()) {
if (addSep) {
path.append(SEPARATOR);
} else {
addSep = true;
}
path.append(element);
}
}
return getPath(root, path.toString(), this);
}
@Override
public PathMatcher getPathMatcher(final String syntaxAndPattern) {
final int pos = syntaxAndPattern.indexOf(':');
if (pos <= 0 || pos == syntaxAndPattern.length()) {
throw new IllegalArgumentException();
}
final String syntax = syntaxAndPattern.substring(0, pos);
final String pattern = syntaxAndPattern.substring(pos + 1);
return switch (syntax) {
case "glob" -> new MCRGlobPathMatcher(pattern);
case "regex" -> new MCRPathMatcher(pattern);
default -> throw new UnsupportedOperationException("If the pattern syntax '" + syntax + "' is not known.");
};
}
public MCRPath getRootDirectory(final String owner) {
return rootDirectoryCache.getUnchecked(owner);
}
@Override
public String getSeparator() {
return SEPARATOR_STRING;
}
@Override
public UserPrincipalLookupService getUserPrincipalLookupService() {
throw new UnsupportedOperationException();
}
@Override
public boolean isOpen() {
return true;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public WatchService newWatchService() {
throw new UnsupportedOperationException();
}
@Override
public Set<String> supportedFileAttributeViews() {
return Collections.unmodifiableSet(Sets.newHashSet("basic", "mcrifs"));
}
public MCRPath toThisFileSystem(final MCRPath other) {
if (Objects.requireNonNull(other).getFileSystem() == this) {
return other;
}
return getPath(other.root, other.path, this);
}
private MCRAbstractFileSystem instance() {
return this;
}
}
| 9,241 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileSystemPromoter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRFileSystemPromoter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.nio.file.FileSystem;
import java.nio.file.spi.FileSystemProvider;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.events.MCRStartupHandler.AutoExecutable;
import jakarta.servlet.ServletContext;
/**
* This {@link AutoExecutable} checks if the {@link FileSystem} implementations are available.
*
* There is a documented "feature" in OpenJDK 8 that only {@link FileSystemProvider}
* available to the system {@link ClassLoader} are available.
* We try to fix (a.k.a. hack) it right.
* @author Thomas Scheffler (yagee)
*
*/
public class MCRFileSystemPromoter implements AutoExecutable {
private static Logger LOGGER = LogManager.getLogger(MCRFileSystemPromoter.class);
public MCRFileSystemPromoter() {
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getName()
*/
@Override
public String getName() {
return getClass().getSimpleName();
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getPriority()
*/
@Override
public int getPriority() {
return Integer.MAX_VALUE;
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#startUp(jakarta.servlet.ServletContext)
*/
@Override
public void startUp(ServletContext servletContext) {
if (servletContext != null) {
HashSet<String> installedSchemes = FileSystemProvider.installedProviders()
.stream()
.map(FileSystemProvider::getScheme)
.collect(Collectors.toCollection(HashSet::new));
ServiceLoader<FileSystemProvider> sl = ServiceLoader.load(FileSystemProvider.class, getClass()
.getClassLoader());
promoteFileSystemProvider(StreamSupport.stream(sl.spliterator(), false)
.filter(p -> !installedSchemes.contains(p.getScheme()))
.collect(Collectors.toCollection(ArrayList::new)));
}
}
private void promoteFileSystemProvider(List<FileSystemProvider> detectedProviders) {
if (detectedProviders.isEmpty()) {
return;
}
for (FileSystemProvider provider : detectedProviders) {
LOGGER.info("Promoting filesystem {}: {}", provider.getScheme(), provider.getClass().getCanonicalName());
MCRPaths.addFileSystemProvider(provider);
}
}
}
| 3,428 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractFileStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRAbstractFileStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.nio.file.FileStore;
import java.nio.file.Path;
/**
* @author Thomas Scheffler
*
*/
public abstract class MCRAbstractFileStore extends FileStore {
/**
* Returns base directory of this filestore.
*/
public abstract Path getBaseDirectory();
/**
* Translates the given path into an absolute path of the physical filesystem.
*
* To retrieve a relative path use {@link Path#relativize(Path)} on {@link #getBaseDirectory()}.
* The returned path may not exist or may be null.
*/
public abstract Path getPhysicalPath(MCRPath path);
}
| 1,360 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPathMatcher.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPathMatcher.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.regex.Pattern;
/**
* @author Thomas Scheffler
*
*/
public class MCRPathMatcher implements PathMatcher {
private final Pattern pattern;
public MCRPathMatcher(final String regex) {
pattern = getPattern(regex);
}
@Override
public boolean matches(final Path path) {
return pattern.matcher(path.toString()).matches();
}
protected Pattern getPattern(final String pattern) {
return Pattern.compile(pattern);
}
}
| 1,312 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPath.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPath.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import static org.mycore.datamodel.niofs.MCRAbstractFileSystem.SEPARATOR;
import static org.mycore.datamodel.niofs.MCRAbstractFileSystem.SEPARATOR_STRING;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileStore;
import java.nio.file.InvalidPathException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.ProviderMismatchException;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.text.MessageFormat;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Objects;
import org.mycore.common.MCRException;
import com.google.common.primitives.Ints;
/**
* IFS implementation of the {@link Path} interface.
* Absolute path have this form: <code>{owner}':/'{path}</code>
* @author Thomas Scheffler (yagee)
*
*/
public abstract class MCRPath implements Path {
String root, path, stringValue;
private int[] offsets;
MCRPath(final String root, final String path) {
this.root = root;
this.path = normalizeAndCheck(Objects.requireNonNull(path, "path may not be null"));
if (root == null || root.isEmpty()) {
this.root = "";
stringValue = this.path;
} else {
if (!path.isEmpty() && path.charAt(0) != SEPARATOR) {
final String msg = new MessageFormat("If root is given, path has to start with ''{0}'': {1}",
Locale.ROOT).format(new Object[] { SEPARATOR_STRING, path });
throw new IllegalArgumentException(msg);
}
stringValue = this.root + ":" + (this.path.isEmpty() ? SEPARATOR_STRING : this.path);
}
initNameComponents();
}
public static MCRPath toMCRPath(final Path other) {
if (other == null) {
throw new NullPointerException();
}
if (!(other instanceof MCRPath)) {
throw new ProviderMismatchException("other is not an instance of MCRPath: " + other.getClass());
}
return (MCRPath) other;
}
public static MCRPath getPath(String owner, String path) {
Path resolved = MCRPaths.getPath(owner, path);
return toMCRPath(resolved);
}
/**
* Returns the root directory for a given derivate.
*
* @param owner the file owner (usually the id of a derivate)
* @return the root path
*/
public static MCRPath getRootPath(String owner) {
return getPath(owner, "/");
}
/**
* removes redundant slashes and checks for invalid characters
* @param uncleanPath path to check
* @return normalized path
* @throws InvalidPathException if <code>uncleanPath</code> contains invalid characters
*/
static String normalizeAndCheck(final String uncleanPath) {
String unicodeNormalizedUncleanPath = Normalizer.normalize(uncleanPath, Normalizer.Form.NFC);
char prevChar = 0;
final boolean afterSeparator = false;
for (int i = 0; i < unicodeNormalizedUncleanPath.length(); i++) {
final char c = unicodeNormalizedUncleanPath.charAt(i);
checkCharacter(unicodeNormalizedUncleanPath, c, afterSeparator);
if (c == SEPARATOR && prevChar == SEPARATOR) {
return normalize(unicodeNormalizedUncleanPath, unicodeNormalizedUncleanPath.length(), i - 1);
}
prevChar = c;
}
if (prevChar == SEPARATOR) {
//remove final slash
return normalize(unicodeNormalizedUncleanPath, unicodeNormalizedUncleanPath.length(),
unicodeNormalizedUncleanPath.length() - 1);
}
return unicodeNormalizedUncleanPath;
}
private static void checkCharacter(final String input, final char c, final boolean afterSeparator) {
if (c == '\u0000') {
throw new InvalidPathException(input, "Nul character is not allowed.");
}
if (afterSeparator && c == ':') {
throw new InvalidPathException(input, "':' is only allowed after owner id.");
}
}
private static String normalize(final String input, final int length, final int offset) {
if (length == 0) {
return input;
}
int newLength = length;
while (newLength > 0 && input.charAt(newLength - 1) == SEPARATOR) {
newLength--;
}
if (newLength == 0) {
return SEPARATOR_STRING;
}
final StringBuilder sb = new StringBuilder(input.length());
boolean afterSeparator = false;
if (offset > 0) {
final String prefix = input.substring(0, offset);
afterSeparator = prefix.contains(SEPARATOR_STRING);
sb.append(prefix);
}
char prevChar = 0;
for (int i = offset; i < newLength; i++) {
final char c = input.charAt(i);
checkCharacter(input, c, afterSeparator);
if (c == SEPARATOR && prevChar == SEPARATOR) {
continue;
}
sb.append(c);
if (!afterSeparator && c == SEPARATOR) {
afterSeparator = true;
}
prevChar = c;
}
return sb.toString();
}
/* (non-Javadoc)
* @see java.nio.file.Path#compareTo(java.nio.file.Path)
*/
@Override
public int compareTo(final Path other) {
final MCRPath that = (MCRPath) Objects.requireNonNull(other);
return toString().compareTo(that.toString());
}
/* (non-Javadoc)
* @see java.nio.file.Path#endsWith(java.nio.file.Path)
*/
@Override
public boolean endsWith(final Path other) {
if (!(Objects.requireNonNull(other, "other Path may not be null.") instanceof MCRPath)) {
return false;
}
final MCRPath that = (MCRPath) other;
if (this == that) {
return true;
}
final int thatOffsetCount = that.offsets.length;
final int thisOffsetCount = offsets.length;
final int thatPathLength = that.path.length();
final int thisPathLength = path.length();
if (thatPathLength > thisPathLength) {
return false;
}
//checks required by Path.endsWidth()
final boolean thatIsAbsolute = that.isAbsolute();
final boolean thisIsAbsolute = isAbsolute();
if (thatIsAbsolute) {
if (!thisIsAbsolute) {
return false;
}
//roots must be equal if both path contains one
if (!root.equals(that.root)) {
return false;
}
//path must be equal too
return Objects.deepEquals(offsets, that.offsets) && path.equals(that.path)
&& that.getFileSystem().equals(getFileSystem());
}
//that is not absolute
//check offsets
if (thatOffsetCount > thisOffsetCount) {
return false;
}
if (thisOffsetCount == thatOffsetCount && thisPathLength != thatPathLength) {
return false;
}
int thisPos = thisOffsetCount - thatOffsetCount;
for (int i = thisPos; i < thisOffsetCount; i++) {
if (that.offsets[i - thisPos] != offsets[i]) {
return false;
}
}
//check characters
thisPos = offsets[thisOffsetCount - thatOffsetCount];
int thatPos = that.offsets[0];
if (thatPathLength - thatPos != thisPathLength - thisPos) {
return false;
}
while (thisPos < thisPathLength) {
if (path.charAt(thisPos++) != that.path.charAt(thatPos++)) {
return false;
}
}
return that.getFileSystem().equals(getFileSystem());
}
/* (non-Javadoc)
* @see java.nio.file.Path#endsWith(java.lang.String)
*/
@Override
public boolean endsWith(final String other) {
return endsWith(getFileSystem().getPath(other));
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof MCRPath that)) {
return false;
}
if (!getFileSystem().equals(that.getFileSystem())) {
return false;
}
return stringValue.equals(that.stringValue);
}
/* (non-Javadoc)
* @see java.nio.file.Path#getFileName()
*/
@Override
public Path getFileName() {
final int nameCount = getNameCount();
if (nameCount == 0) {
return null;
}
final int lastOffset = offsets[nameCount - 1];
final String fileName = path.substring(lastOffset);
return MCRAbstractFileSystem.getPath(null, fileName, getFileSystem());
}
@Override
public abstract MCRAbstractFileSystem getFileSystem();
/* (non-Javadoc)
* @see java.nio.file.Path#getName(int)
*/
@Override
public Path getName(final int index) {
final int nameCount = getNameCount();
if (index < 0 || index >= nameCount) {
throw new IllegalArgumentException();
}
final String pathElement = getPathElement(index);
return MCRAbstractFileSystem.getPath(null, pathElement, getFileSystem());
}
/* (non-Javadoc)
* @see java.nio.file.Path#getNameCount()
*/
@Override
public int getNameCount() {
return offsets.length;
}
public String getOwner() {
return root;
}
public String getOwnerRelativePath() {
return (path.equals("")) ? "/" : path;
}
/**
* returns complete subpath.
* same as {@link #subpath(int, int)} with '0' and '{@link #getNameCount()}'.
*/
public MCRPath subpathComplete() {
return isAbsolute() ? subpath(0, offsets.length) : this;
}
/* (non-Javadoc)
* @see java.nio.file.Path#getParent()
*/
@Override
public MCRPath getParent() {
final int nameCount = getNameCount();
if (nameCount == 0) {
return null;
}
final int lastOffset = offsets[nameCount - 1] - 1;
if (lastOffset <= 0) {
if (root.isEmpty()) {
if (path.startsWith("/")) {
//we have root as parent
return MCRAbstractFileSystem.getPath(root, "/", getFileSystem());
}
// path is like "foo" -> no parent
return null;
}
return getRoot();
}
return MCRAbstractFileSystem.getPath(root, path.substring(0, lastOffset), getFileSystem());
}
/* (non-Javadoc)
* @see java.nio.file.Path#getRoot()
*/
@Override
public MCRPath getRoot() {
if (!isAbsolute()) {
return null;
}
if (getNameCount() == 0) {
return this;
}
return getFileSystem().getRootDirectory(root);
}
@Override
public int hashCode() {
return stringValue.hashCode();
}
/* (non-Javadoc)
* @see java.nio.file.Path#isAbsolute()
*/
@Override
public boolean isAbsolute() {
return root == null || !root.isEmpty();
}
/* (non-Javadoc)
* @see java.nio.file.Path#iterator()
*/
@Override
public Iterator<Path> iterator() {
return new Iterator<>() {
int i = 0;
@Override
public boolean hasNext() {
return i < getNameCount();
}
@Override
public Path next() {
if (hasNext()) {
final Path result = getName(i);
i++;
return result;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/* (non-Javadoc)
* @see java.nio.file.Path#normalize()
*/
@Override
public Path normalize() {
final int count = getNameCount();
int remaining = count;
final boolean[] ignoreSubPath = new boolean[count];
for (int i = 0; i < count; i++) {
if (ignoreSubPath[i]) {
continue;
}
final int subPathIndex = offsets[i];
int subPathLength;
if (i == offsets.length - 1) {
subPathLength = path.length() - subPathIndex;
} else {
subPathLength = offsets[i + 1] - subPathIndex - 1;
}
if (path.charAt(subPathIndex) == '.') {
if (subPathLength == 1) {
ignoreSubPath[i] = true;
remaining--;
} else if (subPathLength == 2 && path.charAt(subPathIndex + 1) == '.') {
ignoreSubPath[i] = true;
remaining--;
//go backward to the last unignored and mark it ignored
//can't normalize if all preceding elements already ignored
for (int r = i - 1; r > 0; r--) {
if (!ignoreSubPath[r]) {
ignoreSubPath[r] = true;
remaining--;
break;
}
}
}
}
}
if (count == remaining) {
return this;
}
if (remaining == 0) {
return isAbsolute() ? getRoot() : getFileSystem().emptyPath();
}
final StringBuilder sb = new StringBuilder(path.length());
if (isAbsolute()) {
sb.append(SEPARATOR);
}
for (int i = 0; i < count; i++) {
if (ignoreSubPath[i]) {
continue;
}
sb.append(getPathElement(i));
if (--remaining > 0) {
sb.append('/');
}
}
return MCRAbstractFileSystem.getPath(root, sb.toString(), getFileSystem());
}
/* (non-Javadoc)
* @see java.nio.file.Path#register(java.nio.file.WatchService, java.nio.file.WatchEvent.Kind[])
*/
@Override
public WatchKey register(final WatchService watcher, final Kind<?>... events) {
return register(watcher, events, new WatchEvent.Modifier[0]);
}
/* (non-Javadoc)
* @see java.nio.file.Path#register(java.nio.file.WatchService, java.nio.file.WatchEvent.Kind[], java.nio.file.WatchEvent.Modifier[])
*/
@Override
public WatchKey register(final WatchService watcher, final Kind<?>[] events, final Modifier... modifiers) {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see java.nio.file.Path#relativize(java.nio.file.Path)
*/
@Override
public MCRPath relativize(final Path other) {
if (equals(Objects.requireNonNull(other, "Cannot relativize against 'null'."))) {
return getFileSystem().emptyPath();
}
if (isAbsolute() != other.isAbsolute()) {
throw new IllegalArgumentException("'other' must be absolute if and only if this is absolute, too.");
}
final MCRPath that = toMCRPath(other);
if (!isAbsolute() && isEmpty()) {
return that;
}
URI thisURI;
URI thatURI;
try {
thisURI = new URI(null, null, path, null);
thatURI = new URI(null, null, that.path, null);
} catch (URISyntaxException e) {
throw new MCRException(e);
}
final URI relativizedURI = thisURI.relativize(thatURI);
if (thatURI.equals(relativizedURI)) {
return that;
}
return MCRAbstractFileSystem.getPath(null, relativizedURI.getPath(), getFileSystem());
}
private static boolean isEmpty(Path test) {
return test instanceof MCRPath && ((MCRPath) test).isEmpty()
|| (test.getNameCount() == 1 && test.getName(0).toString().isEmpty());
}
/* (non-Javadoc)
* @see java.nio.file.Path#resolve(java.nio.file.Path)
*/
@Override
public Path resolve(final Path other) {
if (other.isAbsolute()) {
return other;
}
if (isEmpty(other)) {
return this;
}
String otherStr = toMCRPathString(other);
final int baseLength = path.length();
final int childLength = other.toString().length();
if (isEmpty() || otherStr.charAt(0) == SEPARATOR) {
return root == null ? other : MCRAbstractFileSystem.getPath(root, otherStr, getFileSystem());
}
final StringBuilder result = new StringBuilder(baseLength + 1 + childLength);
if (baseLength != 1 || path.charAt(0) != SEPARATOR) {
result.append(path);
}
result.append(SEPARATOR);
result.append(otherStr);
return MCRAbstractFileSystem.getPath(root, result.toString(), getFileSystem());
}
private String toMCRPathString(final Path other) {
String otherStr = other.toString();
String otherSeperator = other.getFileSystem().getSeparator();
return otherSeperator.equals(SEPARATOR_STRING) ? otherStr : otherStr.replace(otherSeperator, SEPARATOR_STRING);
}
/* (non-Javadoc)
* @see java.nio.file.Path#resolve(java.lang.String)
*/
@Override
public Path resolve(final String other) {
return resolve(getFileSystem().getPath(other));
}
/* (non-Javadoc)
* @see java.nio.file.Path#resolveSibling(java.nio.file.Path)
*/
@Override
public Path resolveSibling(final Path other) {
Objects.requireNonNull(other);
final Path parent = getParent();
return parent == null ? other : parent.resolve(other);
}
/* (non-Javadoc)
* @see java.nio.file.Path#resolveSibling(java.lang.String)
*/
@Override
public Path resolveSibling(final String other) {
return resolveSibling(getFileSystem().getPath(other));
}
/* (non-Javadoc)
* @see java.nio.file.Path#startsWith(java.nio.file.Path)
*/
@Override
public boolean startsWith(final Path other) {
if (!(Objects.requireNonNull(other, "other Path may not be null.") instanceof MCRPath)) {
return false;
}
final MCRPath that = (MCRPath) other;
if (this == that) {
return true;
}
final int thatOffsetCount = that.offsets.length;
final int thisOffsetCount = offsets.length;
//checks required by Path.startsWidth()
if (thatOffsetCount > thisOffsetCount || that.path.length() > path.length()) {
return false;
}
if (thatOffsetCount == thisOffsetCount && that.path.length() != path.length()) {
return false;
}
if (!Objects.deepEquals(root, that.root)) {
return false;
}
if (!Objects.deepEquals(getFileSystem(), that.getFileSystem())) {
return false;
}
for (int i = 0; i < thatOffsetCount; i++) {
if (that.offsets[i] != offsets[i]) {
return false;
}
}
if (!path.startsWith(that.path)) {
return false;
}
final int thatPathLength = that.path.length();
// return false if this.path==/foo/bar and that.path==/path
return thatPathLength <= path.length() || path.charAt(thatPathLength) == SEPARATOR;
}
/* (non-Javadoc)
* @see java.nio.file.Path#startsWith(java.lang.String)
*/
@Override
public boolean startsWith(final String other) {
return startsWith(getFileSystem().getPath(other));
}
/* (non-Javadoc)
* @see java.nio.file.Path#subpath(int, int)
*/
@Override
public MCRPath subpath(final int beginIndex, final int endIndex) {
if (beginIndex < 0) {
throw new IllegalArgumentException("beginIndex may not be negative: " + beginIndex);
}
if (beginIndex >= offsets.length) {
throw new IllegalArgumentException("beginIndex may not be greater or qual to the number of path elements("
+ offsets.length + "): " + beginIndex);
}
if (endIndex > offsets.length) {
throw new IllegalArgumentException("endIndex may not be greater that the number of path elements("
+ offsets.length + "): " + endIndex);
}
if (beginIndex >= endIndex) {
throw new IllegalArgumentException("endIndex must be greater than beginIndex(" + beginIndex + "): "
+ endIndex);
}
final int begin = offsets[beginIndex];
final int end = endIndex == offsets.length ? path.length() : offsets[endIndex] - 1;
return MCRAbstractFileSystem.getPath(null, path.substring(begin, end), getFileSystem());
}
/* (non-Javadoc)
* @see java.nio.file.Path#toAbsolutePath()
*/
@Override
public Path toAbsolutePath() {
if (isAbsolute()) {
return this;
}
throw new IOError(new IOException("There is no default directory to resolve " + this + " against to."));
}
/* (non-Javadoc)
* @see java.nio.file.Path#toFile()
*/
@Override
public File toFile() {
throw new UnsupportedOperationException();
}
/* (non-Javadoc)
* @see java.nio.file.Path#toRealPath(java.nio.file.LinkOption[])
*/
@Override
public Path toRealPath(final LinkOption... options) throws IOException {
if (isAbsolute()) {
final MCRPath normalized = (MCRPath) normalize();
getFileSystem().provider().checkAccess(normalized); //eventually throws IOException
return normalized;
}
throw new IOException("Cannot get real path from relative path.");
}
@SuppressWarnings("resource")
public Path toPhysicalPath() throws IOException {
if (isAbsolute()) {
for (FileStore fs : getFileSystem().getFileStores()) {
if (fs instanceof MCRAbstractFileStore mcrfs) {
Path physicalPath = mcrfs.getPhysicalPath(this);
if (physicalPath != null) {
return physicalPath;
}
}
}
return null;
}
throw new IOException("Cannot get real path from relative path.");
}
@Override
public String toString() {
return stringValue;
}
/* (non-Javadoc)
* @see java.nio.file.Path#toUri()
*/
@Override
public URI toUri() {
try {
if (isAbsolute()) {
return MCRPaths.getURI(getFileSystem().provider().getScheme(), root, path);
}
return new URI(null, null, path, null);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private String getPathElement(final int index) {
final int begin = offsets[index];
final int end = index == offsets.length - 1 ? path.length() : offsets[index + 1] - 1;
return path.substring(begin, end);
}
private void initNameComponents() {
final ArrayList<Integer> list = new ArrayList<>();
if (isEmpty()) {
if (!isAbsolute()) {
// is empty path but not root component
// empty path considered to have one name element
list.add(0);
}
} else {
int start = 0;
while (start < path.length()) {
if (path.charAt(start) != SEPARATOR) {
break;
}
start++;
}
int off = start;
while (off < path.length()) {
if (path.charAt(off) != SEPARATOR) {
off++;
} else {
list.add(start);
start = ++off;
}
}
if (start != off) {
list.add(start);
}
}
offsets = Ints.toArray(list);
}
private boolean isEmpty() {
return path.isEmpty();
}
}
| 25,293 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileAttributes.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRFileAttributes.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRFileAttributes<T> implements BasicFileAttributes {
enum FileType {
file, directory, link, other;
public static FileType fromAttribute(BasicFileAttributes attrs) {
if (attrs.isRegularFile()) {
return file;
}
if (attrs.isDirectory()) {
return directory;
}
if (attrs.isSymbolicLink()) {
return link;
}
return other;
}
}
private static final FileTime EPOCHE_TIME = FileTime.fromMillis(0);
private static final Pattern MD5_HEX_PATTERN = Pattern.compile("[a-fA-F0-9]{32}");
FileTime lastModified, lastAccessTime, creationTime;
long size;
T filekey;
String md5sum;
FileType type;
private MCRFileAttributes(final FileType type, final long size, final T filekey, final String md5sum,
final FileTime creationTime, final FileTime lastModified, final FileTime lastAccessTime) {
super();
this.type = type;
if (size < 0) {
throw new IllegalArgumentException("'size' cannot be negative");
}
this.size = size;
this.filekey = filekey;
setMd5sum(type, md5sum);
this.creationTime = creationTime == null ? lastModified == null ? EPOCHE_TIME : lastModified : creationTime;
this.lastModified = lastModified == null ? creationTime == null ? EPOCHE_TIME : creationTime : lastModified;
this.lastAccessTime = lastAccessTime == null ? EPOCHE_TIME : lastAccessTime;
}
public static <T> MCRFileAttributes<T> directory(final T filekey, final long size, final FileTime lastModified) {
return new MCRFileAttributes<>(FileType.directory, size, filekey, null, null, lastModified, null);
}
public static <T> MCRFileAttributes<T> file(final T filekey, final long size, final String md5sum,
final FileTime lastModified) {
return file(filekey, size, md5sum, null, lastModified, null);
}
public static <T> MCRFileAttributes<T> file(final T filekey, final long size, final String md5sum,
final FileTime creationTime, final FileTime lastModified, final FileTime lastAccessTime) {
return new MCRFileAttributes<>(FileType.file, size, filekey, md5sum, creationTime, lastModified,
lastAccessTime);
}
public static <T> MCRFileAttributes<T> fromAttributes(BasicFileAttributes attrs, String md5) {
return new MCRFileAttributes<>(FileType.fromAttribute(attrs), attrs.size(), (T) attrs.fileKey(), md5,
attrs.creationTime(), attrs.lastModifiedTime(), attrs.lastAccessTime());
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#creationTime()
*/
@Override
public FileTime creationTime() {
return creationTime;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#fileKey()
*/
@Override
public T fileKey() {
return filekey;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#isDirectory()
*/
@Override
public boolean isDirectory() {
return type == FileType.directory;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#isOther()
*/
@Override
public boolean isOther() {
return type == FileType.other;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#isRegularFile()
*/
@Override
public boolean isRegularFile() {
return type == FileType.file;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#isSymbolicLink()
*/
@Override
public boolean isSymbolicLink() {
return type == FileType.link;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#lastAccessTime()
*/
@Override
public FileTime lastAccessTime() {
return lastAccessTime;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#lastModifiedTime()
*/
@Override
public FileTime lastModifiedTime() {
return lastModified;
}
public String md5sum() {
return md5sum;
}
/* (non-Javadoc)
* @see java.nio.file.attribute.BasicFileAttributes#size()
*/
@Override
public long size() {
return size;
}
private void setMd5sum(final FileType type, final String md5sum) {
if (type != FileType.file && md5sum == null) {
return;
}
Objects.requireNonNull(md5sum, "'md5sum' is required for files");
if (md5sum.length() != 32 || !MD5_HEX_PATTERN.matcher(md5sum).matches()) {
throw new IllegalArgumentException("Not a valid md5sum: " + md5sum);
}
this.md5sum = md5sum;
}
}
| 5,805 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUnsupportedContentTypeException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRUnsupportedContentTypeException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
/**
* Created by chi on 01.02.17.
* @author Huu Chi Vu
*/
public class MCRUnsupportedContentTypeException {
}
| 877 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPathUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPathUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.logging.log4j.LogManager;
/**
* @author Thomas Scheffler (yagee)
*
*/
public abstract class MCRPathUtils {
private MCRPathUtils() {
}
/**
* Returns requested {@link BasicFileAttributes} or null if file does not exist.
*
* Same as {@link Files#readAttributes(Path, Class, LinkOption...)} without throwing {@link IOException}.
*
* @param path
* the path to the file
* @param type
* the {@code Class} of the file attributes required
* to read
* @param options
* options indicating how symbolic links are handled
*
* @return the file attributes
*/
public static <A extends BasicFileAttributes> A getAttributes(Path path, Class<A> type, LinkOption... options) {
try {
return Files.readAttributes(path, type, options);
} catch (NoSuchFileException | FileNotFoundException e) {
//we expect that file may not exist
} catch (IOException e) {
//any other IOException is catched
LogManager.getLogger(MCRPathUtils.class).info("Error while retrieving attributes of file: {}", path, e);
}
return null;
}
public static Path getPath(FileSystem targetFS, String fileName) {
String[] nameComps = fileName.replace('\\', '/').split("/");
if (nameComps.length == 1) {
return targetFS.getPath(nameComps[0]);
} else {
return targetFS.getPath(nameComps[0], Arrays.copyOfRange(nameComps, 1, nameComps.length));
}
}
/**
* Returns the size of the path.
*
* If the path is a directory the size returned is the sum of all files found recursivly
* in this directory.
* @param p path of a file or directory
* @return the size of p in bytes
* @throws IOException underlaying IOException
*/
public static long getSize(Path p) throws IOException {
AtomicLong size = new AtomicLong();
Files.walkFileTree(p, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
size.addAndGet(attrs.size());
return super.visitFile(file, attrs);
}
});
return size.get();
}
}
| 3,562 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPaths.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/MCRPaths.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.spi.FileSystemProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.config.MCRConfiguration2;
/**
* @author Thomas Scheffler (yagee)
*
*/
final class MCRPaths {
static final String DEFAULT_SCHEME_PROPERTY = "MCR.NIO.DefaultScheme";
static List<FileSystemProvider> webAppProvider = new ArrayList<>(4);
private MCRPaths() {
}
static URI getURI(String owner, String path) throws URISyntaxException {
String scheme = getDefaultScheme();
return getURI(scheme, owner, path);
}
private static String getDefaultScheme() {
return MCRConfiguration2.getString(DEFAULT_SCHEME_PROPERTY).orElse("ifs2");
}
static URI getURI(String scheme, String owner, String path) throws URISyntaxException {
boolean needSeperator = Objects.requireNonNull(path, "No 'path' specified.").isEmpty()
|| path.charAt(0) != MCRAbstractFileSystem.SEPARATOR;
String aPath = needSeperator ? (MCRAbstractFileSystem.SEPARATOR_STRING + path) : path;
String finalPath = MCRAbstractFileSystem.SEPARATOR_STRING
+ Objects.requireNonNull(owner, "No 'owner' specified.") + ":" + aPath;
return new URI(Objects.requireNonNull(scheme, "No 'scheme' specified."), null, finalPath, null);
}
static Path getPath(String owner, String path) {
String scheme = getDefaultScheme();
return getPath(scheme, owner, path);
}
static Path getPath(String scheme, String owner, String path) {
URI uri;
try {
uri = getURI(scheme, owner, path);
LogManager.getLogger(MCRPaths.class).debug("Generated path URI:{}", uri);
} catch (URISyntaxException e) {
throw new InvalidPathException(path, "URI syntax error (" + e.getMessage() + ") for path");
}
try {
return Paths.get(uri);
} catch (FileSystemNotFoundException e) {
for (FileSystemProvider provider : webAppProvider) {
if (provider.getScheme().equals(uri.getScheme())) {
return provider.getPath(uri);
}
}
throw e;
}
}
static void addFileSystemProvider(FileSystemProvider provider) {
webAppProvider.add(provider);
}
}
| 3,364 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTreeCopier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRTreeCopier.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs.utils;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemLoopException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
/**
* Simple {@link FileVisitor} that recursive copies a directory
* @author Thomas Scheffler (yagee)
*
*/
public class MCRTreeCopier implements FileVisitor<Path> {
private static final Logger LOGGER = LogManager.getLogger(MCRTreeCopier.class);
private final Path source;
private final Path target;
private final boolean renameExisting;
private final boolean restartTransaction;
public MCRTreeCopier(Path source, Path target) throws NoSuchFileException {
this(source, target, false, false);
}
public MCRTreeCopier(Path source, Path target, boolean renameOnExisting) throws NoSuchFileException {
this(source, target, renameOnExisting, false);
}
public MCRTreeCopier(Path source, Path target, boolean renameOnExisting, boolean restartTransaction)
throws NoSuchFileException {
this.renameExisting = renameOnExisting;
if (Files.notExists(target)) {
throw new NoSuchFileException(target.toString(), null, "Target directory does not exist.");
}
this.source = source;
this.target = target;
this.restartTransaction = restartTransaction;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
Path newdir = target.resolve(toTargetFS(source.relativize(dir)));
try {
Files.copy(dir, newdir, StandardCopyOption.COPY_ATTRIBUTES);
} catch (FileAlreadyExistsException x) {
// (okay if directory already exists).
// ignore
} catch (IOException x) {
LOGGER.error("Unable to create: {}", newdir, x);
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
private void copyFile(Path source, Path target) {
try {
if (renameExisting && Files.exists(target)) {
int nameTry = 1;
String fileName = target.getFileName().toString();
int numberPosition = fileName.lastIndexOf(".") == -1 ? fileName.length() : fileName.lastIndexOf(".");
String prefixString = fileName.substring(0, numberPosition);
String suffixString = fileName.substring(numberPosition);
String newName = null;
Path parent = target.getParent();
do {
newName = prefixString + nameTry++ + suffixString;
target = parent.resolve(newName);
} while (Files.exists(target));
}
if (restartTransaction && MCRSessionMgr.hasCurrentSession()) {
MCRTransactionHelper.commitTransaction();
MCRTransactionHelper.beginTransaction();
}
Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException x) {
LOGGER.error("Unable to copy: {}", source, x);
}
}
private Path toTargetFS(Path source) {
if (target.getFileSystem().equals(source.getFileSystem())) {
return source;
}
String[] nameParts = new String[source.getNameCount() - 1];
for (int i = 0; i < nameParts.length; i++) {
nameParts[i] = source.getName(i + 1).toString();
}
return target.getFileSystem().getPath(source.getName(0).toString(), nameParts);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
// fix up modification time of directory when done
if (exc == null) {
Path newdir = target.resolve(toTargetFS(source.relativize(dir)));
try {
FileTime time = Files.getLastModifiedTime(dir);
Files.setLastModifiedTime(newdir, time);
} catch (IOException x) {
LOGGER.error("Unable to copy all attributes to: {}", newdir, x);
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
copyFile(file, target.resolve(toTargetFS(source.relativize(file))));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
if (exc instanceof FileSystemLoopException) {
LOGGER.error("cycle detected: {}", file);
} else {
LOGGER.error("Unable to copy: {}", file, exc);
}
return FileVisitResult.CONTINUE;
}
}
| 5,907 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
package-info.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/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/>.
*/
/**
* Various utils for java.nio.file API.
* @author Thomas Scheffler (yagee)
*/
package org.mycore.datamodel.niofs.utils;
| 853 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRecursiveDeleter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRRecursiveDeleter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs.utils;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
/**
* A {@link FileVisitor} to delete a directory recursivly
* <pre>
* Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance())
* </pre>
* @author Thomas Scheffler (yagee)
*
*/
public final class MCRRecursiveDeleter extends SimpleFileVisitor<Path> {
private static final MCRRecursiveDeleter INSTANCE = new MCRRecursiveDeleter();
private MCRRecursiveDeleter() {
}
public static MCRRecursiveDeleter instance() {
return INSTANCE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
throw exc;
}
if (dir.getNameCount() > 0) {
Files.delete(dir);
}
return super.postVisitDirectory(dir, exc);
}
}
| 1,988 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDerivateUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRDerivateUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs.utils;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.niofs.MCRPath;
public class MCRDerivateUtil {
private static final Logger LOGGER = LogManager.getLogger();
/**
* Renames multiple files in one Derivate with the given pattern. You can try out your pattern with the method
* {@link #testRenameFile(String, String, String) testRenameFile}.
*
* @param derivate the Derivate ID as String
* @param pattern the RegEx pattern to find the wanted files
* @param replacement the new name for the files
* @return a Hashmap with the old name and the new name
*/
public static Map<String, String> renameFiles(String derivate, String pattern, String replacement)
throws IOException {
MCRPath derivateRoot = MCRPath.getPath(derivate, "/");
Pattern patternObj = Pattern.compile(pattern);
Map<String, String> resultMap = new HashMap<>();
Files.walkFileTree(derivateRoot, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Matcher matcher = patternObj.matcher(file.getFileName().toString());
if (matcher.matches()) {
LOGGER.debug("The file {} matches the pattern {}", file, pattern);
String newFilename;
try {
newFilename = matcher.replaceAll(replacement);
} catch (IndexOutOfBoundsException e) {
LOGGER.error("The file {} can't be renamed to {}. To many groups!", file, replacement, e);
return FileVisitResult.CONTINUE;
} catch (IllegalArgumentException e) {
LOGGER.error("The new name '{}' contains illegal characters!", replacement, e);
return FileVisitResult.CONTINUE;
}
Files.move(file, file.resolveSibling(newFilename));
LOGGER.info("The file {} was renamed to {}", file, newFilename);
resultMap.put(file.getFileName().toString(), newFilename);
}
return FileVisitResult.CONTINUE;
}
});
return resultMap;
}
/**
* Tests the rename pattern on one file, so you can try the rename befor renaming all files. This method does not
* change any files.
*
* @param filename a filename to try the pattern on
* @param pattern the RegEx pattern to find the wanted files
* @param replacement the new name for the files
* @return the new filename
*/
public static String testRenameFile(String filename, String pattern, String replacement) {
String newFilename = "";
try {
Pattern patternObj = Pattern.compile(pattern);
Matcher matcher = patternObj.matcher(filename);
newFilename = matcher.replaceAll(replacement);
LOGGER.info("The file {} will be renamed to {}", filename, newFilename);
} catch (PatternSyntaxException e) {
LOGGER.error("The pattern '{}' contains errors!", pattern, e);
} catch (IndexOutOfBoundsException e) {
LOGGER.error("The file {} can't be renamed to {}. To many groups!", filename, replacement, e);
} catch (IllegalArgumentException e) {
LOGGER.error("The new name '{}' contains illegal characters!", replacement, e);
}
return newFilename;
}
}
| 4,747 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileCollectingFileVisitor.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/niofs/utils/MCRFileCollectingFileVisitor.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.niofs.utils;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
public class MCRFileCollectingFileVisitor<T> implements FileVisitor<T> {
private final ArrayList<T> paths;
public MCRFileCollectingFileVisitor() {
paths = new ArrayList<>();
}
public ArrayList<T> getPaths() {
return paths;
}
@Override
public FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs) {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(T file, BasicFileAttributes attrs) {
paths.add(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(T file, IOException exc) {
return FileVisitResult.TERMINATE;
}
@Override
public FileVisitResult postVisitDirectory(T dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
}
| 1,788 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFileNodeServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs/MCRFileNodeServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.ifs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.regex.Pattern;
import javax.xml.transform.TransformerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.MCRPathContent;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.datamodel.niofs.MCRPathXML;
import org.mycore.frontend.servlets.MCRContentServlet;
import org.xml.sax.SAXException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* This servlet delivers the contents of an {@link MCRPath} to the client
* browser. If the node is a ordinary file, the contents of that file will be
* sent to the browser. If the node is a directory, the contents of that
* directory will be forwareded to MCRLayoutService as XML data to display a
* detailed directory listing.
*
* @author Frank Lützenkirchen
* @author Jens Kupferschmidt
* @author Thomas Scheffler (yagee)
* @author A.Schaar
* @author Robert Stephan
*
*/
public class MCRFileNodeServlet extends MCRContentServlet {
private static final long serialVersionUID = 1L;
private static Logger LOGGER = LogManager.getLogger(MCRFileNodeServlet.class);
private static Pattern patternDerivateID = Pattern.compile(".+_derivate_[0-9]+");
/* (non-Javadoc)
* @see org.mycore.frontend.servlets.MCRContentServlet#getContent(jakarta.servlet.http.HttpServletRequest, jakarta.servlet.http.HttpServletResponse)
*/
@Override
public MCRContent getContent(HttpServletRequest request, HttpServletResponse response) throws IOException {
if (!isParametersValid(request, response)) {
return null;
}
String ownerID = getOwnerID(request);
if (ownerID != null && ownerID.length() > 0) {
//make sure, that numberpart of ownerID has correct length
ownerID = MCRObjectID.getInstance(ownerID).toString();
}
if (!MCRAccessManager.checkDerivateContentPermission(MCRObjectID.getInstance(ownerID),
MCRAccessManager.PERMISSION_READ)) {
LOGGER.info("AccessForbidden to {}", request.getPathInfo());
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
String path = getPath(request);
MCRPath mcrPath = MCRPath.getPath(ownerID, path);
BasicFileAttributes attr;
try {
attr = Files.readAttributes(mcrPath, BasicFileAttributes.class);
} catch (NoSuchFileException e) {
String msg = e.getMessage();
if (msg == null) {
msg = "File or directory not found: " + mcrPath;
}
response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
return null;
}
if (attr.isDirectory()) {
try {
return sendDirectory(request, response, mcrPath);
} catch (TransformerException | SAXException e) {
throw new IOException(e);
}
}
if (attr.isRegularFile()) {
return sendFile(request, response, mcrPath);
}
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not a file or directory: " + mcrPath);
return null;
}
private boolean isParametersValid(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestPath = request.getPathInfo();
LOGGER.debug("request path = {}", requestPath);
if (requestPath == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Error: HTTP request path is null");
return false;
}
return true;
}
/**
* retrieves the derivate ID of the owning derivate from request path.
* Attention: derivateID is not always at the first position in path
* @param request - the http request object
*/
public static String getOwnerID(HttpServletRequest request) {
String pI = request.getPathInfo();
return Arrays.stream(pI.split("/"))
.filter(fragment -> patternDerivateID.matcher(fragment).matches())
.findFirst()
.orElse("");
}
/**
* Retrieves the path of the file to display from request path.
* @param request - the http request object
*/
protected String getPath(HttpServletRequest request) {
String pI = request.getPathInfo();
String ownerID = getOwnerID(request);
int pos = pI.indexOf(ownerID) + ownerID.length() + 1;
if (pos - 1 >= pI.length()) {
return "/";
}
String path = pI.substring(pos);
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
if (path.length() == 0) {
return "/";
}
return path;
}
private MCRContent sendFile(HttpServletRequest request, HttpServletResponse response, MCRPath mcrPath) {
// TODO: Does MCRFileNodeServlet really has to handle IFS1 AudioVideoExtender support? (last rev: 30037))
return new MCRPathContent(mcrPath);
}
/**
* Sends the contents of an MCRDirectory as XML data to the client
*/
private MCRContent sendDirectory(HttpServletRequest request, HttpServletResponse response, MCRPath mcrPath)
throws IOException, TransformerException, SAXException {
Document directoryXML = MCRPathXML.getDirectoryXML(mcrPath);
MCRJDOMContent source = new MCRJDOMContent(directoryXML);
source.setLastModified(Files.getLastModifiedTime(mcrPath).toMillis());
String fileName = mcrPath.getNameCount() == 0 ? mcrPath.getOwner() : mcrPath.getFileName().toString();
source.setName(fileName);
return getLayoutService().getTransformedContent(request, response, source);
}
}
| 6,963 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRContentInputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/ifs/MCRContentInputStream.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.ifs;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.streams.MCRBlockingInputStream;
/**
* This input stream is used by the MyCoRe filesystem classes to read the
* content of a file and import it into the System. MCRContentInputStream
* provides the header of the file that is read (the first 64k) for content type
* detection purposes, counts the number of bytes read and builds an MD5
* checksum String while content goes through this input stream.
*
* @author Frank Lützenkirchen
*/
public class MCRContentInputStream extends FilterInputStream {
/** The number of bytes that will be read for content type detection */
protected static final int HEADER_SIZE = 65536;
/** The MD5 checksum of all bytes read through this stream */
protected byte[] md5 = null;
/** The message digest to build the MD5 checksum */
protected MessageDigest digest = null;
/** The total number of bytes read so far */
protected long length;
/** The header of the file read */
protected byte[] header;
/**
* Constructs a new MCRContentInputStream
*
* @param in
* the InputStream to read from
* @throws MCRConfigurationException
* if java classes supporting MD5 checksums are not found
*/
public MCRContentInputStream(InputStream in) throws MCRException {
super(null);
digest = buildMD5Digest();
DigestInputStream dis = new DigestInputStream(in, digest);
MCRBlockingInputStream bis = new MCRBlockingInputStream(dis, HEADER_SIZE);
byte[] buffer = new byte[HEADER_SIZE];
try {
int num = bis.read(buffer, 0, buffer.length);
header = new byte[Math.max(0, num)];
if (num > 0) {
System.arraycopy(buffer, 0, header, 0, num);
}
} catch (IOException ex) {
String msg = "Error while reading content input stream header";
throw new MCRException(msg, ex);
}
this.in = bis;
}
public int consume() throws IOException {
byte[] buffer = new byte[4096];
int numRead, totalRead = 0;
do {
numRead = read(buffer);
if (numRead > 0) {
totalRead += numRead;
}
} while (numRead != -1);
return totalRead;
}
@Override
public int read() throws IOException {
int b;
// if current position is in header buffer, return value from there
if (header.length > 0 && length < header.length) {
b = header[(int) length];
length++;
} else {
b = super.read();
if (b != -1) {
length++;
}
}
return b;
}
@Override
public int read(byte[] buf, int off, int len) throws IOException {
// if current position is in header buffer, return bytes from there
if (header.length > 0 && length < header.length) {
int numAvail = header.length - (int) length;
len = Math.min(len, numAvail);
System.arraycopy(header, (int) length, buf, off, len);
} else {
len = super.read(buf, off, len);
}
if (len != -1) {
length += len;
}
return len;
}
/**
* Returns the first 64 k of the underlying input stream. This is used for
* content type detection during file import into MyCoRe.
*
* @return the first 64 k of the input stream
*/
public byte[] getHeader() {
return header;
}
/**
* Returns the number of bytes read so far
*
* @return the number of bytes read
*/
public long getLength() {
return length;
}
/**
* Returns the MD5 message digest that has been built during reading of the
* underlying input stream.
*
* @return the MD5 message digest checksum of all bytes that have been read
*/
public byte[] getMD5() {
if (md5 == null) {
md5 = digest.digest();
}
return md5;
}
/**
* Returns the MD5 checksum as a String
*
* @return the MD5 checksum as a String of hex digits
*/
public String getMD5String() {
return getMD5String(getMD5());
}
/**
* Given an MD5 message digest, returns the MD5 checksum as a String
*
* @return the MD5 checksum as a String of hex digits
*/
public static String getMD5String(byte[] digest) {
StringBuilder md5SumBuilder = new StringBuilder();
for (byte b : digest) {
md5SumBuilder.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
return md5SumBuilder.toString();
}
/**
* Builds a MessageDigest instance for MD5 checksum computation.
*
* @throws MCRConfigurationException
* if no java classes that support MD5 algorithm could be found
*/
private static MessageDigest buildMD5Digest() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException exc) {
String msg = "Could not find java classes that support MD5 checksum algorithm";
throw new MCRConfigurationException(msg, exc);
}
}
}
| 6,371 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaDateLangText.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaDateLangText.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.Objects;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.datamodel.common.MCRISO8601Date;
import org.mycore.datamodel.common.MCRISO8601Format;
import com.google.gson.JsonObject;
/**
* This class implements all method for handling with the MCRMetaDateLangText part
* of a metadata object. The MCRMetaDateLangText class present a single item, which
* has quadruples of a text and his corresponding language and optional a type and date.
*
*/
public class MCRMetaDateLangText extends MCRMetaLangText {
protected MCRISO8601Date isoDate;
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. All other elements was set to
* an empty string. The <em>form</em> Attribute is set to 'plain'.
*/
public MCRMetaDateLangText() {
super();
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>lang</em> is
* null, empty or false <b>en </b> was set. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was thrown. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The text element was set to the value of
* <em>text</em>, if it is null, an empty string was set
* to the text element.
* @param subtag the name of the subtag
* @param lang the default language
* @param type the optional type string
* @param inherted a value >= 0
* @param form the format string, if it is empty 'plain' is set.
* @param text the text string
*
* @exception MCRException if the subtag value is null or empty
*/
public MCRMetaDateLangText(String subtag, String lang, String type, int inherted, String form, String text)
throws MCRException {
super(subtag, lang, type, inherted, form, text);
}
/**
* sets the date for this meta data object
*
* @param isoDate
* the new date, may be null
*/
public void setDate(MCRISO8601Date isoDate) {
this.isoDate = isoDate;
}
/**
* Returns the date.
*
* @return the date, may be null
*/
public MCRISO8601Date getDate() {
return isoDate;
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
String tempDate = element.getAttributeValue("date");
if (tempDate != null) {
MCRISO8601Date tempIsoDate = new MCRISO8601Date();
String tempFormat = element.getAttributeValue("format");
if (tempFormat != null) {
tempIsoDate.setFormat(tempFormat);
}
tempIsoDate.setDate(tempDate);
isoDate = tempIsoDate;
}
}
/**
* This method create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaLangText definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaLangText part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
if (isoDate != null) {
elm.setAttribute("date", isoDate.getISOString());
MCRISO8601Format isoFormat = isoDate.getIsoFormat();
if (isoFormat != null && isoFormat != MCRISO8601Format.COMPLETE_HH_MM_SS_SSS) {
elm.setAttribute("format", isoDate.getIsoFormat().toString());
}
}
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaLangText#createJSON()} method
* with the following data.
*
* <pre>
* {
* text: "Hallo Welt",
* form: "plain",
* date: "2000-01-01",
* format: "YYYY-MM-DD"
* }
* </pre>
*
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
if (isoDate != null) {
obj.addProperty("date", isoDate.getISOString());
MCRISO8601Format isoFormat = isoDate.getIsoFormat();
if (isoFormat != null) {
obj.addProperty("format", isoDate.getIsoFormat().toString());
}
}
return obj;
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see Object#clone()
*/
@Override
public MCRMetaDateLangText clone() {
MCRMetaDateLangText clone = (MCRMetaDateLangText) super.clone();
clone.isoDate = this.isoDate; // this is ok because iso Date is immutable
return clone;
}
/**
* Check the equivalence between this instance and the given object.
*
* @param obj the MCRMetaDateLangText object
* @return true if its equal
*/
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaDateLangText other = (MCRMetaDateLangText) obj;
return Objects.equals(this.text, other.text) && Objects.equals(this.form, other.form)
&& Objects.equals(this.isoDate, other.isoDate);
}
}
| 6,395 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaEnrichedLinkID.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaEnrichedLinkID.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jdom2.Content;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* A Link to a {@link MCRDerivate}. In addition to {@link MCRMetaLink} this class contains information about the
* linked {@link MCRBase} like mainDoc, titles and classifications in {@link MCRDerivate}.
* See also {@link MCREditableMetaEnrichedLinkID}
*/
@JsonClassDescription("Links to derivates")
public class MCRMetaEnrichedLinkID extends MCRMetaLinkID {
protected static final String ORDER_ELEMENT_NAME = "order";
protected static final String MAIN_DOC_ELEMENT_NAME = "maindoc";
protected static final String CLASSIFICATION_ELEMENT_NAME = "classification";
protected static final String CLASSID_ATTRIBUTE_NAME = "classid";
protected static final String CATEGID_ATTRIBUTE_NAME = "categid";
protected static final String TITLE_ELEMENT_NAME = "title";
protected static final String LANG_ATTRIBUTE_NAME = "lang";
private static final List<String> ORDER = List.of(ORDER_ELEMENT_NAME, MAIN_DOC_ELEMENT_NAME, TITLE_ELEMENT_NAME,
CLASSIFICATION_ELEMENT_NAME);
private List<Content> contentList;
public MCRMetaEnrichedLinkID() {
setContentList(new ArrayList<>());
}
/**
* deprecated in 2023.06, use {@link MCRMetaEnrichedLinkIDFactory} instead
*/
@Deprecated
public static MCRMetaEnrichedLinkID fromDom(Element element) {
return MCRMetaEnrichedLinkIDFactory.getInstance().fromDom(element);
}
private static int getElementPosition(Element e) {
final int index = ORDER.indexOf(e.getName());
return index < 0 ? ORDER.size() : index;
}
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
contentList = element.getContent().stream().map(Content::clone).collect(Collectors.toList());
}
@Override
public Element createXML() throws MCRException {
final Element xml = super.createXML();
contentList.stream().map(Content::clone).forEach(xml::addContent);
xml.sortChildren(
Comparator.comparingInt(MCRMetaEnrichedLinkID::getElementPosition)
.thenComparing(contentList::indexOf));
return xml;
}
@JsonIgnore
public List<Content> getContentList() {
return contentList;
}
public void setContentList(List<Content> contentList) {
this.contentList = Objects.requireNonNull(contentList);
}
public int getOrder() {
return elementsWithNameFromContentList(ORDER_ELEMENT_NAME)
.findFirst()
.map(Element::getTextNormalize)
.map(Integer::valueOf)
.orElse(1);
}
public String getMainDoc() {
return elementsWithNameFromContentList(MAIN_DOC_ELEMENT_NAME)
.findFirst()
.map(Element::getTextTrim)
.orElse(null);
}
public List<MCRCategoryID> getClassifications() {
return elementsWithNameFromContentList(CLASSIFICATION_ELEMENT_NAME)
.map(el -> new MCRCategoryID(el.getAttributeValue(CLASSID_ATTRIBUTE_NAME),
el.getAttributeValue(CATEGID_ATTRIBUTE_NAME)))
.collect(Collectors.toList());
}
public List<MCRMetaLangText> getTitle() {
return elementsWithNameFromContentList(TITLE_ELEMENT_NAME)
.map(el -> {
MCRMetaLangText mlt = new MCRMetaLangText();
mlt.setFromDOM(el);
return mlt;
})
.collect(Collectors.toList());
}
protected Stream<Element> elementsWithNameFromContentList(String name) {
return getContentList().stream()
.filter(Element.class::isInstance)
.map(Element.class::cast)
.filter(el -> el.getName().equals(name));
}
@Override
public JsonObject createJSON() {
final JsonObject json = super.createJSON();
json.addProperty(ORDER_ELEMENT_NAME, getOrder());
json.addProperty(MAIN_DOC_ELEMENT_NAME, getMainDoc());
final List<MCRMetaLangText> title = getTitle();
JsonArray titles = new JsonArray(title.size());
title.stream().forEach(t -> titles.add(t.createJSON()));
json.add("titles", titles);
final List<MCRCategoryID> categories = getClassifications();
JsonArray classifications = new JsonArray(categories.size());
categories.stream().map(MCRCategoryID::toString).forEach(classifications::add);
json.add("classifications", classifications);
return json;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
MCRMetaEnrichedLinkID that = (MCRMetaEnrichedLinkID) o;
final List<Content> myContentList = getContentList();
final List<Content> theirContentList = that.getContentList();
final int listSize = myContentList.size();
if (listSize != theirContentList.size()) {
return false;
}
for (int i = 0; i < listSize; i++) {
Content myContent = myContentList.get(i);
Content theirContent = theirContentList.get(i);
if (!myContent.equals(theirContent) || (myContent instanceof Element && theirContent instanceof Element
&& !MCRXMLHelper.deepEqual((Element) myContent, (Element) theirContent))) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getContentList());
}
}
| 6,814 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.common.MCRISO8601Date;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* This class implements all methods for handling MCRObject service data.
* The service data stores technical information that is no metadata.
* The service data holds six types of data (dates, rules flags, messages,
* classifications and states). The flags and messages are text strings
* and are optional.
* <p>
*
* The dates are represent by a date and a type. Two types are in service data
* at every time and can't remove:
* <ul>
* <li>createdate - for the creating date of the object, this was set only one
* time</li>
* <li>modifydate - for the accepting date of the object, this was set at every
* changes</li>
* </ul>
* Other date types are optional, but as example in Dublin Core:
* <ul>
* <li>submitdate - for the submiting date of the object</li>
* <li>acceptdate - for the accepting date of the object</li>
* <li>validfromdate - for the date of the object, at this the object is valid
* to use</li>
* <li>validtodate - for the date of the object, at this the object is no more
* valid to use</li>
* </ul>
*
* The state is optional and represented by a MyCoRe classification object.
*
* @author Jens Kupferschmidt
* @author Matthias Eichner
* @author Robert Stephan
*/
public class MCRObjectService {
private static final Logger LOGGER = LogManager.getLogger(MCRObjectService.class);
/**
* constant for create date
*/
public static final String DATE_TYPE_CREATEDATE = "createdate";
/**
* constant for modify date
*/
public static final String DATE_TYPE_MODIFYDATE = "modifydate";
/**
* constant for create user
*/
public static final String FLAG_TYPE_CREATEDBY = "createdby";
/**
* constant for modify user
*/
public static final String FLAG_TYPE_MODIFIEDBY = "modifiedby";
private final ArrayList<MCRMetaISO8601Date> dates = new ArrayList<>();
private final ArrayList<MCRMetaAccessRule> rules = new ArrayList<>();
private final ArrayList<MCRMetaLangText> flags = new ArrayList<>();
private final ArrayList<MCRMetaDateLangText> messages = new ArrayList<>();
private final ArrayList<MCRMetaClassification> classifications = new ArrayList<>();
private MCRCategoryID state;
/**
* This is the constructor of the MCRObjectService class. All data are set
* to null.
*/
public MCRObjectService() {
Date now = new Date();
MCRMetaISO8601Date createDate = new MCRMetaISO8601Date("servdate", DATE_TYPE_CREATEDATE, 0);
createDate.setDate(now);
dates.add(createDate);
MCRMetaISO8601Date modifyDate = new MCRMetaISO8601Date("servdate", DATE_TYPE_MODIFYDATE, 0);
modifyDate.setDate(now);
dates.add(modifyDate);
}
/**
* This method read the XML input stream part from a DOM part for the
* structure data of the document.
*
* @param service
* a list of relevant DOM elements for the metadata
*/
public final void setFromDOM(Element service) {
// date part
Element datesElement = service.getChild("servdates");
dates.clear();
if (datesElement != null) {
List<Element> dateElements = datesElement.getChildren();
for (Element dateElement : dateElements) {
String dateElementName = dateElement.getName();
if (!Objects.equals(dateElementName, "servdate")) {
continue;
}
MCRMetaISO8601Date date = new MCRMetaISO8601Date();
date.setFromDOM(dateElement);
setDate(date);
}
}
// rule part
Element rulesElement = service.getChild("servacls");
if (rulesElement != null) {
List<Element> ruleElements = rulesElement.getChildren();
for (Element ruleElement : ruleElements) {
if (!ruleElement.getName().equals("servacl")) {
continue;
}
MCRMetaAccessRule user = new MCRMetaAccessRule();
user.setFromDOM(ruleElement);
rules.add(user);
}
}
// flag part
Element flagsElement = service.getChild("servflags");
if (flagsElement != null) {
List<Element> flagElements = flagsElement.getChildren();
for (Element flagElement : flagElements) {
if (!flagElement.getName().equals("servflag")) {
continue;
}
MCRMetaLangText flag = new MCRMetaLangText();
flag.setFromDOM(flagElement);
flags.add(flag);
}
}
// classification part
Element classificationsElement = service.getChild("servclasses");
if (classificationsElement != null) {
List<Element> classificationElements = classificationsElement.getChildren();
for (Element classificationElement : classificationElements) {
if (!classificationElement.getName().equals("servclass")) {
continue;
}
MCRMetaClassification classification = new MCRMetaClassification();
classification.setFromDOM(classificationElement);
classifications.add(classification);
}
}
// nessage part
Element messagesElement = service.getChild("servmessages");
if (messagesElement != null) {
List<Element> messageElements = messagesElement.getChildren();
for (Element messageElement : messageElements) {
if (!messageElement.getName().equals("servmessage")) {
continue;
}
MCRMetaDateLangText message = new MCRMetaDateLangText();
message.setFromDOM(messageElement);
messages.add(message);
}
}
// States part
Element statesElement = service.getChild("servstates");
if (statesElement != null) {
List<Element> stateElements = statesElement.getChildren();
for (Element stateElement : stateElements) {
if (!stateElement.getName().equals("servstate")) {
continue;
}
MCRMetaClassification stateClass = new MCRMetaClassification();
stateClass.setFromDOM(stateElement);
state = new MCRCategoryID(stateClass.getClassId(), stateClass.getCategId());
}
}
}
/**
* This method return the size of the date list.
*
* @return the size of the date list
*/
public final int getDateSize() {
return dates.size();
}
/**
* Returns the dates.
*
* @return list of dates
*/
protected ArrayList<MCRMetaISO8601Date> getDates() {
return dates;
}
/**
* This method returns the status classification
*
* @return the status as MCRMetaClassification,
* can return null
*
*/
public final MCRCategoryID getState() {
return state;
}
/**
* This method get a date for a given type. If the type was not found, an
* null was returned.
*
* @param type
* the type of the date
* @return the date as GregorianCalendar
*
* @see MCRObjectService#DATE_TYPE_CREATEDATE
* @see MCRObjectService#DATE_TYPE_MODIFYDATE
*/
public final Date getDate(String type) {
MCRMetaISO8601Date isoDate = getISO8601Date(type);
if (isoDate == null) {
return null;
}
return isoDate.getDate();
}
private MCRMetaISO8601Date getISO8601Date(String type) {
if (type == null || type.length() == 0) {
return null;
}
return IntStream.range(0, dates.size())
.mapToObj(dates::get)
.filter(d -> d.getType().equals(type))
.findAny()
.orElse(null);
}
/**
* This method set a date element in the dates list to a actual date value.
* If the given type exists, the date was update.
*
* @param type
* the type of the date
*/
public final void setDate(String type) {
setDate(type, new Date());
}
/**
* This method set a date element in the dates list to a given date value.
* If the given type exists, the date was update.
*
* @param type
* the type of the date
* @param date
* set time to this Calendar
* null means the actual date
*/
public final void setDate(String type, Date date) {
MCRMetaISO8601Date d = getISO8601Date(type); //search date in ArrayList
if (d == null) {
d = new MCRMetaISO8601Date("servdate", type, 0);
d.setDate(date);
dates.add(d);
} else {
d.setDate(date); // alter date found in ArrayList
}
}
/**
* This method set a date element in the dates list to a given date value.
* If the given type exists, the date was update.
*
* @param date
* set time to this Calendar
*/
private void setDate(MCRMetaISO8601Date date) {
MCRMetaISO8601Date d = getISO8601Date(date.getType()); //search date in ArrayList
if (d == null) {
dates.add(date);
} else {
d.setDate(date.getDate()); // alter date found in ArrayList
}
}
/**
* This method removes the date of the specified type from
* the date list.
*
* @param type
* a type as string
*/
public final void removeDate(String type) {
if (DATE_TYPE_CREATEDATE.equals(type) || DATE_TYPE_MODIFYDATE.equals(type)) {
LOGGER.error("Cannot delete built-in date: " + type);
} else {
MCRMetaISO8601Date d = getISO8601Date(type);
if (d != null) {
dates.remove(d);
}
}
}
/**
* This method sets the status classification
*/
public final void setState(MCRCategoryID state) {
if (state == null) {
this.state = state;
} else {
if (MCRCategoryDAOFactory.getInstance().exist(state)) {
this.state = state;
} else {
LOGGER.warn("Error at setting servstate classification.",
new MCRException("The category " + state + " does not exist."));
}
}
}
/**
* This method sets the status classification with the given string as categid
* and the default classid ('state')
*/
public final void setState(String state) {
if (state == null) {
this.state = null;
} else {
MCRCategoryID categState = new MCRCategoryID(
MCRConfiguration2.getString("MCR.Metadata.Service.State.Classification.ID").orElse("state"),
state);
setState(categState);
}
}
/**
* This method removes the current state
*/
public final void removeState() {
this.state = null;
}
/**
* This method add a flag to the flag list.
*
* @param value -
* the new flag as string
*/
public final void addFlag(String value) {
addFlag(null, value);
}
/**
* This method adds a flag to the flag list.
*
* @param type
* a type as string
* @param value
* the new flag value as string
*/
public final void addFlag(String type, String value) {
String lType = StringUtils.trim(type);
MCRUtils.filterTrimmedNotEmpty(value)
.map(flagValue -> new MCRMetaLangText("servflag", null, lType, 0, null, flagValue))
.ifPresent(flags::add);
}
/**
* This method get all flags from the flag list as a string.
*
* @return the flags string
*/
public final String getFlags() {
StringBuilder sb = new StringBuilder();
for (MCRMetaLangText flag : flags) {
sb.append(flag.getText()).append(' ');
}
return sb.toString();
}
/**
* Returns the flags as list.
*
* @return flags as list
*/
protected final List<MCRMetaLangText> getFlagsAsList() {
return flags;
}
/**
* This method returns all flag values of the specified type.
*
* @param type
* a type as string.
* @return a list of flag values
*/
protected final ArrayList<MCRMetaLangText> getFlagsAsMCRMetaLangText(String type) {
return flags.stream()
.filter(metaLangText -> StringUtils.equals(type, metaLangText.getType()))
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method returns all flag values of the specified type.
*
* @param type
* a type as string.
* @return a list of flag values
*/
public final ArrayList<String> getFlags(String type) {
return getFlagsAsMCRMetaLangText(type).stream()
.map(MCRMetaLangText::getText)
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method return the size of the flag list.
*
* @return the size of the flag list
*/
public final int getFlagSize() {
return flags.size();
}
/**
* This method get a single flag from the flag list as a string.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a flag string
*/
public final String getFlag(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= flags.size()) {
throw new IndexOutOfBoundsException("Index error in getFlag.");
}
return flags.get(index).getText();
}
/**
* This method gets a single flag type from the flag list as a string.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a flag type
*/
public final String getFlagType(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= flags.size()) {
throw new IndexOutOfBoundsException("Index error in getFlagType.");
}
return flags.get(index).getType();
}
/**
* This method return a boolean value if the given flag is set or not.
*
* @param value
* a searched flag
* @return true if the flag was found in the list
*/
public final boolean isFlagSet(String value) {
return MCRUtils.filterTrimmedNotEmpty(value)
.map(flagValue -> flags.stream().anyMatch(flag -> flagValue.equals(flag.getText())))
.orElse(false);
}
/**
* Proves if the type is set in the flag list.
* @param type
* a type as string
* @return true if the flag list contains flags with this type,
* otherwise false
*/
public final boolean isFlagTypeSet(String type) {
return flags.stream().anyMatch(flag -> StringUtils.equals(type, flag.getType()));
}
/**
* This method remove a flag from the flag list.
*
* @param index
* a index in the list
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void removeFlag(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= flags.size()) {
throw new IndexOutOfBoundsException("Index error in removeFlag.");
}
flags.remove(index);
}
/**
* This method removes all flags of the specified type from
* the flag list.
*
* @param type
* a type as string
*/
public final void removeFlags(String type) {
flags.removeIf(f -> StringUtils.equals(type, f.getType()));
}
/**
* This method set a flag in the flag list.
*
* @param index
* a index in the list
* @param value
* the value of a flag as string
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void replaceFlag(int index, String value) throws IndexOutOfBoundsException {
MCRUtils.filterTrimmedNotEmpty(value)
.ifPresent(flagValue -> updateFlag(index, flag -> flag.setText(value)));
}
private void updateFlag(int index, Consumer<MCRMetaLangText> flagUpdater) {
MCRMetaLangText flag = flags.get(index);
flagUpdater.accept(flag);
}
/**
* This method sets the type value of a flag at the specified index.
*
* @param index
* a index in the list
* @param type
* the type a flag as string
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void replaceFlagType(int index, String type) throws IndexOutOfBoundsException {
String lType = StringUtils.trim(type);
updateFlag(index, flag -> flag.setType(lType));
}
/**
* This method add a rule to the rules list.
*
* @param permission -
* the new permission as string
* @param condition -
* the new rule as JDOM tree Element
*/
public final void addRule(String permission, Element condition) {
if (condition == null) {
return;
}
MCRUtils.filterTrimmedNotEmpty(permission)
.filter(p -> getRuleIndex(p) == -1)
.map(p -> new MCRMetaAccessRule("servacl", null, 0, p, condition))
.ifPresent(rules::add);
}
/**
* This method return the size of the rules list.
*
* @return the size of the rules list
*/
public final int getRulesSize() {
return rules.size();
}
/**
* This method return the index of a permission in the rules list.
*
* @return the index of a permission in the rules list
*/
public final int getRuleIndex(String permission) {
int notFound = -1;
if (permission == null || permission.trim().length() == 0) {
return notFound;
}
return IntStream.range(0, rules.size())
.filter(i -> rules.get(i).getPermission().equals(permission))
.findAny()
.orElse(notFound);
}
/**
* This method get a single rule from the rules list as a JDOM Element.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a the MCRMetaAccessRule instance
*/
public final MCRMetaAccessRule getRule(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= rules.size()) {
throw new IndexOutOfBoundsException("Index error in getRule.");
}
return rules.get(index);
}
/**
* This method get a single permission name of rule from the rules list as a
* string.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a rule permission string
*/
public final String getRulePermission(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= rules.size()) {
throw new IndexOutOfBoundsException("Index error in getRulePermission.");
}
return rules.get(index).getPermission();
}
/**
* This method remove a rule from the rules list.
*
* @param index
* a index in the list
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void removeRule(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= rules.size()) {
throw new IndexOutOfBoundsException("Index error in removeRule.");
}
rules.remove(index);
}
/**
* Returns the rules.
*
* @return list of rules
*/
protected final ArrayList<MCRMetaAccessRule> getRules() {
return rules;
}
/**
* This method create a XML stream for all structure data.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML data of the structure data part
*/
public final Element createXML() throws MCRException {
try {
validate();
} catch (MCRException exc) {
throw new MCRException("The content is not valid.", exc);
}
Element elm = new Element("service");
if (dates.size() != 0) {
Element elmm = new Element("servdates");
elmm.setAttribute("class", "MCRMetaISO8601Date");
for (MCRMetaISO8601Date date : dates) {
elmm.addContent(date.createXML());
}
elm.addContent(elmm);
}
if (rules.size() != 0) {
Element elmm = new Element("servacls");
elmm.setAttribute("class", "MCRMetaAccessRule");
for (MCRMetaAccessRule rule : rules) {
elmm.addContent(rule.createXML());
}
elm.addContent(elmm);
}
if (flags.size() != 0) {
Element elmm = new Element("servflags");
elmm.setAttribute("class", "MCRMetaLangText");
for (MCRMetaLangText flag : flags) {
elmm.addContent(flag.createXML());
}
elm.addContent(elmm);
}
if (messages.size() != 0) {
Element elmm = new Element("servmessages");
elmm.setAttribute("class", "MCRMetaDateLangText");
for (MCRMetaDateLangText message : messages) {
elmm.addContent(message.createXML());
}
elm.addContent(elmm);
}
if (classifications.size() != 0) {
Element elmm = new Element("servclasses");
elmm.setAttribute("class", "MCRMetaClassification");
for (MCRMetaClassification classification : classifications) {
elmm.addContent(classification.createXML());
}
elm.addContent(elmm);
}
if (state != null) {
Element elmm = new Element("servstates");
elmm.setAttribute("class", "MCRMetaClassification");
MCRMetaClassification stateClass = new MCRMetaClassification("servstate", 0, null, state);
elmm.addContent(stateClass.createXML());
elm.addContent(elmm);
}
return elm;
}
/**
* Creates the JSON representation of this service.
*
* <pre>
* {
* dates: [
* {@link MCRMetaISO8601Date#createJSON()},
* ...
* ],
* rules: [
* {@link MCRMetaAccessRule#createJSON()},
* ...
* ],
* flags: [
* {@link MCRMetaLangText#createJSON()},
* ...
* ],
* messages: [
* {@link MCRMetaDateLangText#createJSON()},
* ...
* ],
* classifications: [
* {@link MCRMetaClassification#createJSON()},
* ...
* ],
* state: {
*
* }
* }
* </pre>
*
* @return a json gson representation of this service
*/
public final JsonObject createJSON() {
JsonObject service = new JsonObject();
// dates
if (!getDates().isEmpty()) {
JsonObject dates = new JsonObject();
getDates()
.stream()
.forEachOrdered(date -> {
JsonObject jsonDate = date.createJSON();
jsonDate.remove("type");
dates.add(date.getType(), jsonDate);
});
service.add("dates", dates);
}
// rules
if (!getRules().isEmpty()) {
JsonArray rules = new JsonArray();
getRules()
.stream()
.map(MCRMetaAccessRule::createJSON)
.forEachOrdered(rules::add);
service.add("rules", rules);
}
// flags
if (!getFlags().isEmpty()) {
JsonArray flags = new JsonArray();
getFlagsAsList()
.stream()
.map(MCRMetaLangText::createJSON)
.forEachOrdered(flags::add);
service.add("flags", flags);
}
// messages
if (!getMessages().isEmpty()) {
JsonArray messages = new JsonArray();
getMessagesAsList()
.stream()
.map(MCRMetaDateLangText::createJSON)
.forEachOrdered(messages::add);
service.add("messages", messages);
}
// classifications
if (!getClassifications().isEmpty()) {
JsonArray classifications = new JsonArray();
getClassificationsAsList()
.stream()
.map(MCRMetaClassification::createJSON)
.forEachOrdered(classifications::add);
service.add("classifications", classifications);
}
// state
Optional.ofNullable(getState()).ifPresent(stateId -> {
JsonObject state = new JsonObject();
if (stateId.getId() != null) {
state.addProperty("id", stateId.getId());
}
state.addProperty("rootId", stateId.getRootID());
});
return service;
}
/**
* This method check the validation of the content of this class. The method
* returns <em>true</em> if
* <ul>
* <li>the date value of "createdate" is not null or empty
* <li>the date value of "modifydate" is not null or empty
* </ul>
* otherwise the method return <em>false</em>
*
* @return a boolean value
*/
public final boolean isValid() {
try {
validate();
return true;
} catch (MCRException exc) {
LOGGER.warn("The <service> part is invalid.");
}
return false;
}
/**
* Validates the content of this class. This method throws an exception if:
* <ul>
* <li>the date value of "createdate" is not null or empty</li>
* <li>the date value of "modifydate" is not null or empty</li>
* </ul>
*
* @throws MCRException the content is invalid
*/
public void validate() {
// TODO: this makes no sense - there is nothing to validate
if (getISO8601Date(DATE_TYPE_CREATEDATE) == null) {
setDate(DATE_TYPE_CREATEDATE);
}
if (getISO8601Date(DATE_TYPE_MODIFYDATE) == null) {
setDate(DATE_TYPE_MODIFYDATE);
}
}
/**
* This method returns the index for the given flag value.
*
* @param value
* the value of a flag as string
* @return the index number or -1 if the value was not found
*/
public final int getFlagIndex(String value) {
return MCRUtils.filterTrimmedNotEmpty(value)
.map(v -> {
for (int i = 0; i < flags.size(); i++) {
if (flags.get(i).getText().equals(v)) {
return i;
}
}
return -1;
})
.orElse(-1);
}
/**
* This method return the size of the message list.
*
* @return the size of the message list
*/
public final int getMessagesSize() {
return messages.size();
}
/**
* Returns the messages as list.
*
* @return messages as list
*/
protected final ArrayList<MCRMetaDateLangText> getMessagesAsList() {
return messages;
}
/**
* This method returns all message values of the specified type.
*
* @param type
* a type as string.
* @return a list of message values
*/
protected final ArrayList<MCRMetaDateLangText> getMessagesAsMCRMetaDateLangText(String type) {
return messages.stream()
.filter(metaLangText -> type.equals(metaLangText.getType()))
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method returns all messages values of any type.
*
* @return a list of message values
*/
public final ArrayList<String> getMessages() {
return messages.stream()
.map(MCRMetaDateLangText::getText)
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method returns all messages values of the specified type.
*
* @param type
* a type as string.
* @return a list of message values
*/
public final ArrayList<String> getMessages(String type) {
return getMessagesAsMCRMetaDateLangText(type).stream()
.map(MCRMetaDateLangText::getText)
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method get a single messages from the message list as a string.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a message string
*/
public final String getMessage(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= messages.size()) {
throw new IndexOutOfBoundsException("Index error in getMessage.");
}
return messages.get(index).getText();
}
/**
* This method gets a single message type from the message list as a string.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a message type
*/
public final String getMessageType(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= messages.size()) {
throw new IndexOutOfBoundsException("Index error in getMessageType.");
}
return messages.get(index).getType();
}
/**
* This method gets a single message date from the message list as a {@link MCRISO8601Date}.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a message value
*/
public final MCRISO8601Date getMessageDate(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= messages.size()) {
throw new IndexOutOfBoundsException("Index error in getMessageMCRMetaLangText.");
}
return messages.get(index).getDate();
}
/**
* This method add a message to the flag list.
*
* @param value -
* the new messages as string
*/
public final void addMessage(String value) {
addMessage(null, value);
}
/**
* This method adds a message to the message list.
*
* @param type
* a type as string
* @param value
* the new message value as string
*/
public final void addMessage(String type, String value) {
addMessage(type, value, null);
}
/**
* This method adds a message to the message list.
*
* @param type
* a type as string
* @param value
* the new message value as string
* @param form
* a form as string, defaults to 'plain'
*/
public final void addMessage(String type, String value, String form) {
String lType = StringUtils.trim(type);
MCRUtils.filterTrimmedNotEmpty(value)
.map(messageValue -> {
MCRMetaDateLangText message = new MCRMetaDateLangText("servmessage", null, lType, 0, form,
messageValue);
message.setDate(MCRISO8601Date.now());
return message;
})
.ifPresent(messages::add);
}
/**
* This method set a message in the message list.
*
* @param index
* a index in the list
* @param value
* the value of a message as string
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void replaceMessage(int index, String value) throws IndexOutOfBoundsException {
MCRUtils.filterTrimmedNotEmpty(value)
.ifPresent(messageValue -> updateMessage(index, message -> message.setText(value)));
}
/**
* This method sets the type value of a message at the specified index.
*
* @param index
* a index in the list
* @param type
* the type of a message as string
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void replaceMessageType(int index, String type) throws IndexOutOfBoundsException {
String lType = StringUtils.trim(type);
updateMessage(index, message -> message.setType(lType));
}
private void updateMessage(int index, Consumer<MCRMetaDateLangText> messageUpdater) {
MCRMetaDateLangText message = messages.get(index);
messageUpdater.accept(message);
}
/**
* This method remove a message from the message list.
*
* @param index
* a index in the list
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void removeMessage(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= messages.size()) {
throw new IndexOutOfBoundsException("Index error in removeMessage.");
}
messages.remove(index);
}
/**
* This method removes all messages of the specified type from
* the message list.
*
* @param type
* a type as string
*/
public final void removeMessages(String type) {
List<MCRMetaDateLangText> internalList = getMessagesAsMCRMetaDateLangText(type);
messages.removeAll(internalList);
}
/**
* This method return the size of the classification list.
*
* @return the size of the classification list
*/
public final int getClassificationsSize() {
return this.classifications.size();
}
/**
* This method returns all classification values.
*
* @return classifications as list
*/
protected final ArrayList<MCRMetaClassification> getClassificationsAsList() {
return classifications;
}
/**
* This method returns all classification values of the specified type.
*
* @param type
* a type as string.
* @return a list of classification values
*/
protected final ArrayList<MCRMetaClassification> getClassificationsAsMCRMetaClassification(String type) {
return classifications.stream()
.filter(metaLangText -> type.equals(metaLangText.getType()))
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method returns all classification values of any type.
*
* @return a list of classification values
*/
public final ArrayList<MCRCategoryID> getClassifications() {
return classifications.stream()
.map(c -> new MCRCategoryID(c.getClassId(), c.getCategId()))
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method returns all classification values of the specified type.
*
* @param type
* a type as string.
* @return a list of classification values
*/
public final ArrayList<MCRCategoryID> getClassifications(String type) {
return getClassificationsAsMCRMetaClassification(type).stream()
.map(c -> new MCRCategoryID(c.getClassId(), c.getCategId()))
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* This method get a single classification from the classification list as a string.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a classification string
*/
public final MCRCategoryID getClassification(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= classifications.size()) {
throw new IndexOutOfBoundsException("Index error in getClassification.");
}
MCRMetaClassification classification = classifications.get(index);
return new MCRCategoryID(classification.getCategId(), classification.getClassId());
}
/**
* This method gets a single classification type from the classification list as a string.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a classification type
*/
public final String getClassificationType(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= classifications.size()) {
throw new IndexOutOfBoundsException("Index error in getClassification.");
}
return classifications.get(index).getType();
}
/**
* This method get a single classification from the classification list as.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
* @return a classification value
*/
public final MCRMetaClassification getClassificationAsMCRMetaClassification(int index)
throws IndexOutOfBoundsException {
if (index < 0 || index >= classifications.size()) {
throw new IndexOutOfBoundsException("Index error in getClassificationAsMCRMetaClassification.");
}
return classifications.get(index);
}
/**
* This method adds a classification to the classification list.
*
* @param value -
* the new classification
*/
public final void addClassification(MCRCategoryID value) {
addClassification(null, value);
}
/**
* This method adds a classification to the classification list.
*
* @param type
* a type as string
* @param value
* the new classification value as {@link MCRCategoryID}
*/
public final void addClassification(String type, MCRCategoryID value) {
String lType = StringUtils.trim(type);
classifications.add(new MCRMetaClassification("servclass", 0, lType, value));
}
/**
* This method set a classification in the classification list.
*
* @param index
* a index in the list
* @param value
* the classification as {@link MCRCategoryID}
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void replaceClassification(int index, MCRCategoryID value) throws IndexOutOfBoundsException {
updateClassification(index,
classificationValue -> classificationValue.setValue(value.getRootID(), value.getId()));
}
/**
* This method sets the type value of a classification at the specified index.
*
* @param index
* a index in the list
* @param type
* the type of a flag as string
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void replaceClassificationType(int index, String type) throws IndexOutOfBoundsException {
String lType = StringUtils.trim(type);
updateClassification(index, classification -> classification.setType(lType));
}
private void updateClassification(int index, Consumer<MCRMetaClassification> classificationUpdater) {
MCRMetaClassification classification = classifications.get(index);
classificationUpdater.accept(classification);
}
/**
* This method remove a classification from the classification list.
*
* @param index
* a index in the list
* @exception IndexOutOfBoundsException
* throw this exception, if the index is invalid
*/
public final void removeClassification(int index) throws IndexOutOfBoundsException {
if (index < 0 || index >= classifications.size()) {
throw new IndexOutOfBoundsException("Index error in removeClassification.");
}
classifications.remove(index);
}
/**
* This method removes all classification with the specified type from
* the classification list.
*
* @param type
* a type as string
*/
public final void removeClassifications(String type) {
String lType = StringUtils.trim(type);
classifications.removeIf(c -> StringUtils.equals(lType, c.getType()));
}
}
| 42,890 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectDerivate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectDerivate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.datamodel.niofs.MCRPath;
/**
* This class implements all methode for handling one derivate data.
*
* @author Jens Kupferschmidt
*/
public class MCRObjectDerivate {
private static final Logger LOGGER = LogManager.getLogger();
// derivate data
private MCRMetaLinkID linkmeta;
private final ArrayList<MCRMetaLink> externals;
private MCRMetaIFS internals;
private final ArrayList<MCRMetaLangText> titles;
private final ArrayList<MCRMetaClassification> classifications;
private String derivateURN;
private List<MCRFileMetadata> files;
private MCRObjectID derivateID;
/**
* This is the constructor of the MCRObjectDerivate class. All data are set
* to null.
*/
public MCRObjectDerivate(MCRObjectID derivateID) {
linkmeta = null;
externals = new ArrayList<>();
internals = null;
titles = new ArrayList<>();
classifications = new ArrayList<>();
files = Collections.emptyList();
this.derivateID = derivateID;
}
public MCRObjectDerivate(MCRObjectID derivateID, Element derivate) {
this(derivateID);
setFromDOM(derivate);
}
/**
* This methode read the XML input stream part from a DOM part for the
* structure data of the document.
*
* @param derivate
* a list of relevant DOM elements for the derivate
*/
private void setFromDOM(Element derivate) {
// Link to Metadata part
Element linkmetaElement = derivate.getChild("linkmetas").getChild("linkmeta");
MCRMetaLinkID link = new MCRMetaLinkID();
link.setFromDOM(linkmetaElement);
linkmeta = link;
// External part
Element externalsElement = derivate.getChild("externals");
externals.clear();
if (externalsElement != null) {
List<Element> externalList = externalsElement.getChildren();
for (Element externalElement : externalList) {
MCRMetaLink eLink = new MCRMetaLink();
eLink.setFromDOM(externalElement);
externals.add(eLink);
}
}
// Internal part
Element internalsElement = derivate.getChild("internals");
if (internalsElement != null) {
Element internalElement = internalsElement.getChild("internal");
if (internalElement != null) {
internals = new MCRMetaIFS();
internals.setFromDOM(internalElement);
}
}
// Title part
Element titlesElement = derivate.getChild("titles");
titles.clear();
if (titlesElement != null) {
List<Element> titleList = titlesElement.getChildren();
for (Element titleElement : titleList) {
MCRMetaLangText text = new MCRMetaLangText();
text.setFromDOM(titleElement);
if (text.isValid()) {
titles.add(text);
}
}
}
// Classification part
Element classificationElement = derivate.getChild("classifications");
classifications.clear();
if (classificationElement != null) {
final List<Element> classificationList = classificationElement.getChildren();
classificationList.stream().map((classElement) -> {
MCRMetaClassification clazzObject = new MCRMetaClassification();
clazzObject.setFromDOM(classElement);
return clazzObject;
}).forEach(classifications::add);
}
// fileset part
Element filesetElements = derivate.getChild("fileset");
if (filesetElements != null) {
String mainURN = filesetElements.getAttributeValue("urn");
if (mainURN != null) {
this.derivateURN = mainURN;
}
List<Element> filesInList = filesetElements.getChildren();
if (!filesInList.isEmpty()) {
files = new ArrayList<>(filesInList.size());
for (Element file : filesInList) {
files.add(new MCRFileMetadata(file));
}
}
}
}
/**
* returns link to the MCRObject.
*
* @return a metadata link as MCRMetaLinkID
*/
public MCRMetaLinkID getMetaLink() {
return linkmeta;
}
/**
* This method set the metadata link
*
* @param link
* the MCRMetaLinkID object
*/
public final void setLinkMeta(MCRMetaLinkID link) {
linkmeta = link;
}
/**
* This method return the size of the external array.
*/
public final int getExternalSize() {
return externals.size();
}
/**
* This method get a single link from the external list as a MCRMetaLink.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is false
* @return a external link as MCRMetaLink
*/
public final MCRMetaLink getExternal(int index) throws IndexOutOfBoundsException {
if ((index < 0) || (index > externals.size())) {
throw new IndexOutOfBoundsException("Index error in getExternal(" + index + ").");
}
return externals.get(index);
}
/**
* This method return the size of the title array.
*/
public final int getTitleSize() {
return titles.size();
}
/**
* This method get a single text from the titles list as a MCRMetaLangText.
*
* @exception IndexOutOfBoundsException
* throw this exception, if the index is false
* @return a title text as MCRMetaLangText
*/
public final MCRMetaLangText getTitle(int index) throws IndexOutOfBoundsException {
if ((index < 0) || (index > titles.size())) {
throw new IndexOutOfBoundsException("Index error in getTitle(" + index + ").");
}
return titles.get(index);
}
/**
* This method get a single data from the internal list as a MCRMetaIFS.
*
* @return a internal data as MCRMetaIFS
*/
public final MCRMetaIFS getInternals() {
return internals;
}
/**
* @param file the file to add
* @param urn the urn of the file, if already known, if not provide null
*
* @throws NullPointerException if first argument is null
*/
public MCRFileMetadata getOrCreateFileMetadata(MCRPath file, String urn) {
return getOrCreateFileMetadata(file, urn, null);
}
public MCRFileMetadata getOrCreateFileMetadata(MCRPath file, String urn, String handle) {
Objects.requireNonNull(file, "File may not be null");
String path = "/" + file.subpathComplete();
return getOrCreateFileMetadata(path, urn, handle);
}
private MCRFileMetadata getOrCreateFileMetadata(String path, String urn, String handle) {
if (path == null) {
throw new NullPointerException("path may not be null");
}
int fileCount = files.size();
for (int i = 0; i < fileCount; i++) {
MCRFileMetadata fileMetadata = files.get(i);
int compare = fileMetadata.getName().compareTo(path);
if (compare == 0) {
return fileMetadata;
} else if (compare > 0) {
//we need to create entry here
MCRFileMetadata newFileMetadata = createFileMetadata(path, urn, handle);
files.add(i, newFileMetadata);
return newFileMetadata;
}
}
//add path to end of list;
if (files.isEmpty()) {
files = new ArrayList<>();
}
MCRFileMetadata newFileMetadata = createFileMetadata(path, urn, handle);
files.add(newFileMetadata);
return newFileMetadata;
}
public final MCRFileMetadata getOrCreateFileMetadata(String path) {
return getOrCreateFileMetadata(MCRPath.getPath(derivateID.toString(), path), null, null);
}
public MCRFileMetadata getOrCreateFileMetadata(MCRPath file) {
return getOrCreateFileMetadata(file, null, null);
}
private MCRFileMetadata createFileMetadata(String path, String urn, String handle) {
MCRPath mcrFile = MCRPath.getPath(derivateID.toString(), path);
if (!Files.exists(mcrFile)) {
throw new MCRPersistenceException("File does not exist: " + mcrFile);
}
return new MCRFileMetadata(path, urn, handle, null);
}
public List<MCRFileMetadata> getFileMetadata() {
return Collections.unmodifiableList(files);
}
/**
* Removes file metadata (urn information) from the {@link MCRObjectDerivate}
*/
public void removeFileMetadata() {
this.files = Collections.emptyList();
this.derivateURN = null;
}
/**
* Deletes file metadata of file idendified by absolute path.
* @param path absolute path of this node starting with a '/'
* @return true if metadata was deleted and false if file has no metadata.
*/
public boolean deleteFileMetaData(String path) {
Iterator<MCRFileMetadata> it = files.iterator();
while (it.hasNext()) {
MCRFileMetadata metadata = it.next();
if (metadata.getName().equals(path)) {
it.remove();
return true;
}
}
return false;
}
/**
* This method set the metadata internals (the IFS data)
*
* @param ifs
* the MCRMetaIFS object
*/
public final void setInternals(MCRMetaIFS ifs) {
if (ifs == null) {
return;
}
internals = ifs;
}
/**
* This methode create a XML stream for all derivate data.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML data of the structure data part
*/
public final Element createXML() throws MCRException {
try {
validate();
} catch (MCRException exc) {
throw new MCRException("The content is not valid.", exc);
}
Element elm = new Element("derivate");
Element linkmetas = new Element("linkmetas");
linkmetas.setAttribute("class", "MCRMetaLinkID");
linkmetas.setAttribute("heritable", "false");
linkmetas.addContent(linkmeta.createXML());
elm.addContent(linkmetas);
if (externals.size() != 0) {
Element extEl = new Element("externals");
extEl.setAttribute("class", "MCRMetaLink");
extEl.setAttribute("heritable", "false");
for (MCRMetaLink external : externals) {
extEl.addContent(external.createXML());
}
elm.addContent(extEl);
}
if (internals != null) {
Element intEl = new Element("internals");
intEl.setAttribute("class", "MCRMetaIFS");
intEl.setAttribute("heritable", "false");
intEl.addContent(internals.createXML());
elm.addContent(intEl);
}
if (titles.size() != 0) {
Element titEl = new Element("titles");
titEl.setAttribute("class", "MCRMetaLangText");
titEl.setAttribute("heritable", "false");
titles.stream()
.map(MCRMetaLangText::createXML)
.forEach(titEl::addContent);
elm.addContent(titEl);
}
if (classifications.size() > 0) {
Element clazzElement = new Element("classifications");
clazzElement.setAttribute("class", "MCRMetaClassification");
clazzElement.setAttribute("heritable", "false");
classifications.stream()
.map(MCRMetaClassification::createXML)
.forEach(clazzElement::addContent);
elm.addContent(clazzElement);
}
if (this.derivateURN != null || !files.isEmpty()) {
Element fileset = new Element("fileset");
if (this.derivateURN != null) {
fileset.setAttribute("urn", this.derivateURN);
}
Collections.sort(files);
for (MCRFileMetadata file : files) {
fileset.addContent(file.createXML());
}
elm.addContent(fileset);
}
return elm;
}
/**
* This method check the validation of the content of this class. The method
* returns <em>true</em> if <br>
* <ul>
* <li>the linkmeta exist and the XLink type of linkmeta is not "arc"</li>
* <li>no information in the external AND internal tags</li>
* </ul>
*
* @return a boolean value
*/
public final boolean isValid() {
try {
validate();
return true;
} catch (MCRException exc) {
LOGGER.warn("The <derivate> part of the mycorederivate '{}' is invalid.", derivateID, exc);
}
return false;
}
/**
* Validates this MCRObjectDerivate. This method throws an exception if:
* <ul>
* <li>the linkmeta is null</li>
* <li>the linkmeta xlink:type is not 'locator'</li>
* <li>the internals and the externals are empty</li>
* </ul>
*
* @throws MCRException the MCRObjectDerivate is invalid
*/
public void validate() throws MCRException {
if (linkmeta == null) {
throw new MCRException("linkmeta == null");
}
if (!linkmeta.getXLinkType().equals("locator")) {
throw new MCRException("linkmeta type != locator");
}
if ((internals == null) && (externals.size() == 0)) {
throw new MCRException("(internals == null) && (externals.size() == 0)");
}
}
public void setURN(String urn) {
derivateURN = urn;
}
public String getURN() {
return derivateURN;
}
void setDerivateID(MCRObjectID id) {
this.derivateID = id;
}
public ArrayList<MCRMetaClassification> getClassifications() {
return classifications;
}
public ArrayList<MCRMetaLangText> getTitles() {
return titles;
}
}
| 15,422 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREditableMetaEnrichedLinkID.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCREditableMetaEnrichedLinkID.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.List;
import org.jdom2.Content;
import org.jdom2.Element;
import org.mycore.datamodel.classifications2.MCRCategoryID;
public class MCREditableMetaEnrichedLinkID extends MCRMetaEnrichedLinkID {
public void setOrder(int order) {
setOrCreateElement(ORDER_ELEMENT_NAME, String.valueOf(order));
}
public void setMainDoc(String mainDoc) {
setOrCreateElement(MAIN_DOC_ELEMENT_NAME, mainDoc);
}
public void setClassifications(List<MCRCategoryID> list) {
elementsWithNameFromContentList(CLASSIFICATION_ELEMENT_NAME).forEach(getContentList()::remove);
list.stream().map(clazz -> {
final Element classElement = new Element(CLASSIFICATION_ELEMENT_NAME);
classElement.setAttribute(CLASSID_ATTRIBUTE_NAME, clazz.getRootID());
classElement.setAttribute(CATEGID_ATTRIBUTE_NAME, clazz.getId());
return classElement;
}).forEach(getContentList()::add);
}
public void setTitles(List<MCRMetaLangText> titles) {
elementsWithNameFromContentList(TITLE_ELEMENT_NAME).forEach(getContentList()::remove);
titles.stream().map(MCRMetaLangText::createXML).forEach(getContentList()::add);
}
public void setOrCreateElement(String elementName, String textContent) {
elementsWithNameFromContentList(elementName)
.findFirst()
.orElseGet(() -> createNewElement(elementName))
.setText(textContent);
}
protected Element createNewElement(String name) {
final List<Content> contentList = getContentList();
Element orderElement = new Element(name);
contentList.add(orderElement);
return orderElement;
}
}
| 2,484 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaIFS.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaIFS.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.Objects;
import java.util.Optional;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import com.google.gson.JsonObject;
/**
* This class implements all method for handling the IFS metadata. The
* MCRMetaIFS class present all informations to store and retrieve derivates to
* the IFS.
* <p>
* <tag class="MCRMetaIFS" > <br>
* <subtag sourcepath="..." maindoc="..." ifsid="..." /> <br>
* </tag> <br>
*
* @author Jens Kupferschmidt
*/
public final class MCRMetaIFS extends MCRMetaDefault {
// MCRMetaIFS data
private String sourcePath;
private String maindoc;
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. All other data was set to
* empty.
*/
public MCRMetaIFS() {
super();
sourcePath = "";
maindoc = "";
}
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The subtag element was set to
* the value of <em>subtag</em>. If the
* value of <em>subtag</em> is null or empty an exception was throwed.
* The type element was set empty.
* The sourcepath must be NOT null or empty.
* @param subtag the name of the subtag
* @param sourcePath the sourcepath attribute
* @exception MCRException if the subtag value, the set_classid value or
* the set_categid are null, empty, too long or not a MCRObjectID
*/
public MCRMetaIFS(String subtag, String sourcePath) throws MCRException {
super(subtag, null, null, 0);
setSourcePath(sourcePath);
maindoc = "";
}
/**
* The method return the derivate source path.
*
* @return the sourcepath
*/
public String getSourcePath() {
return sourcePath;
}
/**
* The method return the derivate main document name.
*
* @return the main document name.
*/
public String getMainDoc() {
return maindoc;
}
/**
* The method return the derivate IFS ID.
*
* @return the IFS ID.
* @deprecated will always return empty String
*/
@Deprecated
public String getIFSID() {
return "";
}
/**
* This method set the value of derivate source path.
*
* @param sourcePath
* the derivate source path
*/
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
/**
* This method set the value of derivate main document.
*
* @param mainDoc
* the derivate main document name
*/
public void setMainDoc(String mainDoc) {
if (mainDoc == null) {
maindoc = "";
} else {
maindoc = mainDoc.startsWith("/") ? mainDoc.substring(1) : mainDoc;
}
}
/**
* This method set the value of derivate IFS ID.
*
* @param ifsId
* the derivate IFS ID
* @deprecated out of use
*/
@Deprecated
public void setIFSID(String ifsId) {
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
* @exception MCRException
* if the set_sourcepath value is null or empty
*/
@Override
public void setFromDOM(Element element) throws MCRException {
super.setFromDOM(element);
setSourcePath(element.getAttributeValue("sourcepath"));
setMainDoc(element.getAttributeValue("maindoc"));
}
/**
* This method create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaIFS definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRClassification part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
if (sourcePath != null) {
elm.setAttribute("sourcepath", sourcePath);
}
elm.setAttribute("maindoc", maindoc);
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* sourcepath: "...",
* maindoc: "image.tif",
* ifsid: "ve3s8a3j00xsfk8z"
* }
* </pre>
*
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
if (sourcePath != null) {
obj.addProperty("sourcepath", sourcePath);
}
obj.addProperty("maindoc", maindoc);
return obj;
}
/**
* Validates this MCRMetaIFS. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the trimmed sourcepath is null empty</li>
* </ul>
*
* @throws MCRException the MCRMetaIFS is invalid
*/
public void validate() throws MCRException {
super.validate();
if (sourcePath == null) {
return;
}
sourcePath = Optional.of(sourcePath)
.map(String::trim)
.orElseThrow(() -> new MCRException(getSubTag() + ": sourcepath is empty"));
}
@Override
public MCRMetaIFS clone() {
MCRMetaIFS clone = (MCRMetaIFS) super.clone();
clone.maindoc = this.maindoc;
clone.sourcePath = this.sourcePath;
return clone;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaIFS other = (MCRMetaIFS) obj;
return Objects.equals(sourcePath, other.sourcePath) && Objects.equals(maindoc, other.maindoc);
}
}
| 6,768 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaClassification.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaClassification.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import com.google.gson.JsonObject;
/**
* This class implements all method for handling with the MCRMetaClassification
* part of a metadata object. The MCRMetaClassification class present a link to
* a category of a classification.
* <p>
* <tag class="MCRMetaClassification" heritable="..."> <br>
* <subtag classid="..." categid="..." /> <br>
* </tag> <br>
*
* @author Jens Kupferschmidt
*/
public class MCRMetaClassification extends MCRMetaDefault {
private static final Logger LOGGER = LogManager.getLogger();
// MCRMetaClassification data
protected MCRCategoryID category;
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The classid and categid value
* was set to an empty string.
*/
public MCRMetaClassification() {
super();
}
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The subtag element was set to
* the value of <em>subtag</em>. If the
* value of <em>subtag</em> is null or empty an exception was throwed.
* The type element was set to an empty string.
* the <em>classid</em> and the <em>categid</em> must be not null
* or empty!
* @param subtag the name of the subtag
* @param inherted a value >= 0
* @param type the type attribute
* @param classid the classification ID
* @param categid the category ID
*
* @exception MCRException if the subtag value, the classid value or
* the categid are null, empty, too long or not a MCRObjectID
*/
public MCRMetaClassification(String subtag, int inherted, String type, String classid,
String categid) throws MCRException {
super(subtag, null, type, inherted);
setValue(classid, categid);
}
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The subtag element was set to
* the value of <em>subtag</em>. If the
* value of <em>subtag</em> is null or empty an exception was throwed.
* The type element was set to an empty string.
* the <em>classid</em> and the <em>categid</em> must be not null
* or empty!
* @param subtag the name of the subtag
* @param inherted a value >= 0
* @param type the type attribute
* @param category a category id
*
* @exception MCRException if the subtag value is empty, too long or not a MCRObjectID
*/
public MCRMetaClassification(String subtag, int inherted, String type, MCRCategoryID category)
throws MCRException {
super(subtag, null, type, inherted);
if (category == null) {
throw new MCRException("Category is not set in " + getSubTag());
}
this.category = category;
}
/**
* The method return the classification ID.
*
* @return the classId
*/
public final String getClassId() {
return category.getRootID();
}
/**
* The method return the category ID.
*
* @return the categId
*/
public final String getCategId() {
return category.getId();
}
/**
* This method set values of classid and categid.
*
* @param classid
* the classification ID
* @param categid
* the category ID
* @exception MCRException
* if the classid value or the categid are null,
* empty, too long or not a MCRObjectID
*/
public final void setValue(String classid, String categid) throws MCRException {
category = new MCRCategoryID(classid, categid);
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
* @exception MCRException
* if the classid value or the categid are null,
* empty, too long or not a MCRObjectID
*/
@Override
public void setFromDOM(Element element) throws MCRException {
super.setFromDOM(element);
String classid = element.getAttributeValue("classid");
String categid = element.getAttributeValue("categid");
setValue(classid, categid);
}
/**
* This method create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaClassification definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRClassification part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
elm.setAttribute("classid", getClassId());
elm.setAttribute("categid", getCategId());
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* classid: "mycore_class_00000001",
* categid: "category1"
* }
* </pre>
*
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
obj.addProperty("classid", category.getRootID());
obj.addProperty("categid", category.getId());
return obj;
}
/**
* Validates this MCRMetaClassification. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the category is null</li>
* </ul>
*
* @throws MCRException the MCRMetaClassification is invalid
*/
public void validate() throws MCRException {
super.validate();
if (category == null) {
throw new MCRException(getSubTag() + ": category is not yet set");
}
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaClassification clone() {
MCRMetaClassification clone = (MCRMetaClassification) super.clone();
clone.category = this.category; // immutable so shallow copy ok
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Category = {}", category);
LOGGER.debug(" ");
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaClassification other = (MCRMetaClassification) obj;
return Objects.equals(this.category, other.category);
}
}
| 8,013 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMaindocEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMaindocEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.niofs.MCRPath;
/**
* This eventhandler deals with changes to the maindoc file.
*
* It sets the maindoc entry in derivate metadata empty,
* if the maindoc was deleted
*
* @author Robert Stephan
*
*/
public class MCRMaindocEventHandler extends MCREventHandlerBase {
private static Logger LOGGER = LogManager.getLogger(MCRMaindocEventHandler.class);
@Override
protected void handlePathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) {
if (attrs != null && attrs.isDirectory()) {
return;
}
MCRObjectID derivateID = MCRObjectID.getInstance(MCRPath.toMCRPath(path).getOwner());
if (!MCRMetadataManager.exists(derivateID)) {
LOGGER.warn("Derivate {} from file '{}' does not exist.", derivateID, path);
return;
}
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
MCRObjectDerivate objectDerivate = derivate.getDerivate();
String filePath = path.subpath(0, path.getNameCount()).toString();
boolean wasMainDocDeleted = filePath.equals(objectDerivate.getInternals().getMainDoc());
if (wasMainDocDeleted) {
objectDerivate.getInternals().setMainDoc("");
try {
MCRMetadataManager.update(derivate);
} catch (MCRPersistenceException | MCRAccessException e) {
throw new MCRPersistenceException("Could not update derivate: " + derivateID, e);
}
LOGGER.warn("The maindoc '{}' was deleted.", path);
}
}
}
| 2,716 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectStructure.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectStructure.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* This class implements code for the inheritance of metadata of linked objects
* and the linking of derivates onto an MCRObject. These links are described by
* the <em>MCRMetaLink</em> class. For links to another object, there are
* "locators" in use only, and the href variable gives the ID of the linked
* object, while the label and title attributes can be used freely. Subtag name = "
* <child>" means a child link from a "parent" object (collected in the
* "children" and "parents" section of the "structure" part, respectively). The
* child inherits all heritable metadata of the parent. If the parent itself is
* a child of another parent, the heritable metadata of this "grand parent" is
* inherited by the child as well. This mechanism recursively traces the full
* inheritance hierarchy. So if the grand parent itself has a parent, this grand
* parent parent's heritable metadata will be inherited and so on. Note, that it
* is impossible to inherit metadata from multiple parents. In cases of multiple
* inheritance request, an exception is thrown. A child link cannot occur twice
* from the same object to the same href (preventing from doubled links). Not
* supported by this class are links from or to a defined place of a document
* (inner structure and combination of inner and outer structures of the
* objects). This will possibly be done in a later extension of
* <em>MCRMetaLink</em> and <em>MCRObjectStructure</em>.
*
* @author Mathias Hegner
* @author Jens Kupferschmidt
*/
public class MCRObjectStructure {
private MCRMetaLinkID parent;
private final ArrayList<MCRMetaLinkID> children;
private final ArrayList<MCRMetaEnrichedLinkID> derivates;
private static final Logger LOGGER = LogManager.getLogger();
/**
* The constructor initializes NL (non-static, in order to enable different
* NL's for different objects) and the link vectors the elements of which
* are MCRMetaLink's.
*/
public MCRObjectStructure() {
children = new ArrayList<>();
derivates = new ArrayList<>();
}
/**
* This method clean the data lists parent, children and derivates of this
* class.
*/
public final void clear() {
parent = null;
children.clear();
derivates.clear();
}
/**
* This method clean the data lists children of this class.
*/
public final void clearChildren() {
children.clear();
}
/**
* This method clean the data lists derivate of this class.
*/
public final void clearDerivates() {
derivates.clear();
}
/**
* The method returns the parent link.
*
* @return MCRMetaLinkID the corresponding link
*/
public final MCRMetaLinkID getParent() {
return parent;
}
/**
* The method return the parent reference as a MCRObjectID.
*
* @return the parent MCRObjectID or null if there is no parent present
*/
public final MCRObjectID getParentID() {
if (parent == null) {
return null;
}
return parent.getXLinkHrefID();
}
/**
* This method set the parent value from a given MCRMetaLinkID.
*
* @param parent
* the MCRMetaLinkID to set
*
*/
public final void setParent(MCRMetaLinkID parent) {
this.parent = parent;
}
public final void setParent(MCRObjectID parentID) {
setParent(parentID.toString());
}
public final void setParent(String parentID) {
parent = new MCRMetaLinkID();
parent.setSubTag("parent");
parent.setReference(parentID, null, null);
}
/**
* Removes the parent reference. Use this method with care!
*/
public final void removeParent() {
parent = null;
}
/**
* The method appends a child ID to the child link list if and only if it is
* not already contained in the list, preventing from doubly-linked objects.
* If the link could be added a "true" will be returned, otherwise "false".
*
* @param child
* the MCRMetaLinkID of the child
* @return boolean true, if successfully done
*/
public final boolean addChild(MCRMetaLinkID child) {
for (MCRMetaLinkID c : children) {
if (c.getXLinkHrefID().equals(child.getXLinkHrefID())) {
return false;
}
}
children.add(child);
return true;
}
/**
* removes a child link to another object.
* If the link was found a "true" will be returned, otherwise
* "false".
*
* @param href
* the MCRObjectID of the child
* @return boolean true, if successfully completed
*/
public final boolean removeChild(MCRObjectID href) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Remove child ID {}", href);
}
return removeMetaLink(getChildren(), href);
}
/**
* Checks if the child is in the children vector.
*
* @param childId child to check
*/
public final boolean containsChild(MCRObjectID childId) {
return getChildren().stream().map(MCRMetaLinkID::getXLinkHrefID).anyMatch(childId::equals);
}
/**
* removes a derivate link.
* If the link was found a "true" will be returned, otherwise
* "false".
*
* @param href
* the MCRObjectID of the child
* @return boolean true, if successfully completed
*/
public final boolean removeDerivate(MCRObjectID href) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Remove derivate ID {}", href);
}
return removeMetaLink(getDerivates(), href);
}
/**
* Removes a MCRMetaLinkID instance by it MCRObjectID.
*/
private boolean removeMetaLink(List<? extends MCRMetaLinkID> list, MCRObjectID href) {
final List<MCRMetaLink> toRemove = list.stream()
.filter(ml -> ml.getXLinkHrefID().equals(href))
.collect(Collectors.toList());
return list.removeAll(toRemove);
}
/**
* Returns all children in this structure
* */
public final List<MCRMetaLinkID> getChildren() {
return children;
}
/**
* <em>addDerivate</em> methode append the given derivate link data to the
* derivate vector. If the link could be added a "true" will be returned,
* otherwise "false".
*
* @param derivate
* the link to be added as MCRMetaLinkID
*/
public final boolean addDerivate(MCRMetaEnrichedLinkID derivate) {
MCRObjectID href = derivate.getXLinkHrefID();
if (containsDerivate(href)) {
return false;
}
if (!MCRMetadataManager.exists(href)) {
LOGGER.warn("Cannot find derivate {}, will add it anyway.", href);
}
derivates.add(derivate);
derivates.sort(Comparator.comparingInt(MCRMetaEnrichedLinkID::getOrder));
return true;
}
/**
* Adds or updates the derivate link. Returns true if the derivate is added
* or updated. Returns false when nothing is done.
*
* @param derivateLink the link to add or update
* @return true when the structure is changed
*/
public final boolean addOrUpdateDerivate(MCRMetaEnrichedLinkID derivateLink) {
if (derivateLink == null) {
return false;
}
MCRObjectID derivateId = derivateLink.getXLinkHrefID();
MCRMetaLinkID oldLink = getDerivateLink(derivateId);
if (derivateLink.equals(oldLink)) {
return false;
}
if (oldLink != null) {
removeDerivate(oldLink.getXLinkHrefID());
}
return addDerivate(derivateLink);
}
/**
* Checks if the derivate is in the derivate vector.
*
* @param derivateId derivate to check
*/
public final boolean containsDerivate(MCRObjectID derivateId) {
return getDerivateLink(derivateId) != null;
}
/**
* Returns the derivate link by id or null.
*/
public final MCRMetaEnrichedLinkID getDerivateLink(MCRObjectID derivateId) {
return getDerivates().stream()
.filter(derivate -> derivate.getXLinkHrefID().equals(derivateId))
.findAny()
.orElse(null);
}
/**
* @return a list with all related derivate ids encapsulated within a {@link MCRMetaLinkID}
* */
public List<MCRMetaEnrichedLinkID> getDerivates() {
return this.derivates;
}
/**
* While the preceding methods dealt with the structure's copy in memory
* only, the following three will affect the operations to or from datastore
* too. Thereby <em>setFromDOM</em> will read the structure data from an
* XML input stream (the "structure" entry).
*
* @param element
* the structure node list
*/
public final void setFromDOM(Element element) {
clear();
Element subElement = element.getChild("children");
if (subElement != null) {
List<Element> childList = subElement.getChildren();
for (Element linkElement : childList) {
MCRMetaLinkID link = new MCRMetaLinkID();
link.setFromDOM(linkElement);
children.add(link);
}
}
// Stricture parent part
subElement = element.getChild("parents");
if (subElement != null) {
parent = new MCRMetaLinkID();
parent.setFromDOM(subElement.getChild("parent"));
}
// Structure derivate part
subElement = element.getChild("derobjects");
if (subElement != null) {
List<Element> derobjectList = subElement.getChildren();
for (Element derElement : derobjectList) {
addDerivate(MCRMetaEnrichedLinkIDFactory.getInstance().fromDom(derElement));
}
}
}
/**
* <em>createXML</em> is the inverse of setFromDOM and converts the
* structure's memory copy into XML.
*
* @exception MCRException
* if the content of this class is not valid
* @return the structure XML
*/
public final Element createXML() throws MCRException {
try {
validate();
} catch (MCRException exc) {
throw new MCRException("The content is not valid.", exc);
}
Element elm = new Element("structure");
if (parent != null) {
Element elmm = new Element("parents");
elmm.setAttribute("class", "MCRMetaLinkID");
elmm.addContent(parent.createXML());
elm.addContent(elmm);
}
if (children.size() > 0) {
Element elmm = new Element("children");
elmm.setAttribute("class", "MCRMetaLinkID");
for (MCRMetaLinkID child : getChildren()) {
elmm.addContent(child.createXML());
}
elm.addContent(elmm);
}
if (derivates.size() > 0) {
Element elmm = new Element("derobjects");
elmm.setAttribute("class", "MCRMetaEnrichedLinkID");
for (MCRMetaLinkID derivate : getDerivates()) {
elmm.addContent(derivate.createXML());
}
elm.addContent(elmm);
}
return elm;
}
/**
* Creates the JSON representation of this structure.
*
* <pre>
* {
* parent: {@link MCRMetaLinkID#createJSON()},
* children: [
* {@link MCRMetaLinkID#createJSON()}
* ...
* ],
* derivates: [
* {@link MCRMetaLinkID#createJSON()}
* ...
* ]
* }
* </pre>
*
* @return a json gson representation of this structure
*/
public JsonObject createJSON() {
JsonObject structure = new JsonObject();
// parent
Optional.ofNullable(getParent()).ifPresent(link -> structure.add("parent", link.createJSON()));
// children
JsonArray children = new JsonArray();
getChildren().forEach(child -> children.add(child.createJSON()));
structure.add("children", children);
// derivates
JsonArray derivates = new JsonArray();
getDerivates().forEach(derivate -> derivates.add(derivate.createJSON()));
structure.add("derivates", derivates);
return structure;
}
/**
* The method print all informations about this MCRObjectStructure.
*/
public final void debug() {
if (LOGGER.isDebugEnabled()) {
for (MCRMetaLinkID linkID : derivates) {
linkID.debug();
}
if (parent != null) {
parent.debug();
}
for (MCRMetaLinkID linkID : children) {
linkID.debug();
}
}
}
/**
* <em>isValid</em> checks whether all of the MCRMetaLink's in the link
* vectors are valid or not.
*
* @return boolean true, if structure is valid
*/
public final boolean isValid() {
try {
validate();
return true;
} catch (MCRException exc) {
LOGGER.warn("The <structure> part of a <mycoreobject> is invalid.", exc);
}
return false;
}
/**
* Validates this MCRObjectStructure. This method throws an exception if:
* <ul>
* <li>the parent is not null but invalid</li>
* <li>one of the children is invalid</li>
* <li>one of the derivates is invalid</li>
* </ul>
*
* @throws MCRException the MCRObjectStructure is invalid
*/
public void validate() throws MCRException {
for (MCRMetaLinkID child : getChildren()) {
try {
child.validate();
} catch (Exception exc) {
throw new MCRException("The link to the children '" + child.getXLinkHref() + "' is invalid.", exc);
}
}
if (parent != null) {
try {
parent.validate();
} catch (Exception exc) {
throw new MCRException("The link to the parent '" + parent.getXLinkHref() + "' is invalid.", exc);
}
}
for (MCRMetaLinkID derivate : getDerivates()) {
try {
derivate.validate();
} catch (Exception exc) {
throw new MCRException("The link to the derivate '" + derivate.getXLinkHref() + "' is invalid.", exc);
}
if (!derivate.getXLinkType().equals("locator")) {
throw new MCRException("The xlink:type of the derivate link '" + derivate.getXLinkHref()
+ "' has to be 'locator' and not '" + derivate.getXLinkType() + "'.");
}
String typeId = derivate.getXLinkHrefID().getTypeId();
if (!typeId.equals("derivate")) {
throw new MCRException("The derivate link '" + derivate.getXLinkHref()
+ "' is invalid. The _type_ has to be 'derivate' and not '" + typeId + "'.");
}
}
}
}
| 16,380 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaLink.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaLink.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xml.utils.XMLChar;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import com.google.gson.JsonObject;
/**
* This class implements all method for generic handling with the MCRMetaLink part of a metadata object.
* The MCRMetaLink class present two types. At once a reference to an URL.
* At second a bidirectional link between two URL's. Optional you can append the reference with the label attribute.
* See to W3C XLink Standard for more informations.
* <p>
* <tag class="MCRMetaLink"> <br>
* <subtag xlink:type="locator" xlink:href=" <em>URL</em>" xlink:label="..." xlink:title="..."/> <br>
* <subtag xlink:type="arc" xlink:from=" <em>URL</em>" xlink:to="URL"/> <br>
* </tag> <br>
*
* @author Jens Kupferschmidt
*/
public class MCRMetaLink extends MCRMetaDefault {
// MetaLink data
protected String href;
protected String label;
protected String title;
protected String linktype;
protected String role;
protected String from;
protected String to;
private static final Logger LOGGER = LogManager.getLogger();
/**
* initializes with empty values.
*/
public MCRMetaLink() {
super();
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>default_lang</em> is null, empty or false <b>en </b> was set.
* The subtag element was set to the value of <em>subtag</em>.
* If the value of <em>subtag</em> is null or empty an exception was throwed.
* @param subtag
* the name of the subtag
* @param inherted
* a value >= 0
* @exception MCRException
* if the set_datapart or subtag value is null or empty
*/
public MCRMetaLink(String subtag, int inherted) throws MCRException {
super(subtag, null, null, inherted);
}
/**
* This method set a reference with xlink:href, xlink:label and xlink:title.
*
* @param href
* the reference
* @param label
* the new label string
* @param title
* the new title string
* @exception MCRException
* if the href value is null or empty
*/
public void setReference(String href, String label, String title) throws MCRException {
linktype = "locator";
this.href = MCRUtils.filterTrimmedNotEmpty(href)
.orElseThrow(() -> new MCRException("The href value is null or empty."));
setXLinkLabel(label);
this.title = title;
}
/**
* This method set a bidirectional link with xlink:from, xlink:to and xlink:title.
*
* @param from
* the source
* @param to
* the target
* @param title
* the new title string
* @exception MCRException
* if the from or to element is null or empty
*/
public void setBiLink(String from, String to, String title) throws MCRException {
this.from = MCRUtils.filterTrimmedNotEmpty(from)
.orElseThrow(() -> new MCRException("The from value is null or empty."));
this.to = MCRUtils.filterTrimmedNotEmpty(to)
.orElseThrow(() -> new MCRException("The to value is null or empty."));
linktype = "arc";
this.title = title;
}
/**
* This method get the xlink:type element.
*
* @return the xlink:type
*/
public final String getXLinkType() {
return linktype;
}
/**
* This method get the xlink:href element as string.
*
* @return the xlink:href element as string
*/
public final String getXLinkHref() {
return href;
}
/**
* This method get the xlink:label element.
*
* @return the xlink:label
*/
public final String getXLinkLabel() {
return label;
}
/**
* This method set the xlink:label
*
* @param label
* the xlink:label
*/
public final void setXLinkLabel(String label) {
if (label != null && !XMLChar.isValidNCName(label)) {
throw new MCRException("xlink:label is not a valid NCName: " + label);
}
this.label = label;
}
/**
* This method get the xlink:title element.
*
* @return the xlink:title
*/
public final String getXLinkTitle() {
return title;
}
/**
* This method set the xlink:title
*
* @param title
* the xlink:title
*/
public final void setXLinkTitle(String title) {
this.title = title;
}
/**
* This method get the xlink:from element as string.
*
* @return the xlink:from element as string
*/
public final String getXLinkFrom() {
return from;
}
/**
* This method get the xlink:to element as string.
*
* @return the xlink:to element as string
*/
public final String getXLinkTo() {
return to;
}
/**
* This method sets the xlink:role.
*
*/
public void setXLinkRole(String role) {
this.role = role;
}
/**
* This method get the xlink:role element as string.
*
*/
public String getXLinkRole() {
return role;
}
/**
* The method compare this instance of MCRMetaLink with a input object of the class type MCRMetaLink.
* The both instances are equal, if: <br>
* <ul>
* <li>for the type 'arc' the 'from' and 'to' element is equal</li>
* <li>for the type 'locator' the 'href' element is equal</li>
* </ul>
* <br>
*
* @param input
* the MCRMetaLink input
* @return true if it is compare, else return false
*/
public final boolean compare(MCRMetaLink input) {
if (linktype.equals("locator")) {
if (linktype.equals(input.getXLinkType()) && href.equals(input.getXLinkHref())) {
return true;
}
}
if (linktype.equals("arc")) {
return linktype.equals(input.getXLinkType()) && from.equals(input.getXLinkFrom())
&& to.equals(input.getXLinkTo());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), from, href, label, linktype, role, title, to);
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
MCRMetaLink other = (MCRMetaLink) obj;
if (!Objects.equals(from, other.from)) {
return false;
} else if (!Objects.equals(href, other.href)) {
return false;
} else if (!Objects.equals(label, other.label)) {
return false;
} else if (!Objects.equals(linktype, other.linktype)) {
return false;
} else if (!Objects.equals(role, other.role)) {
return false;
} else if (!Objects.equals(title, other.title)) {
return false;
} else {
return Objects.equals(to, other.to);
}
}
/**
* This method read the XML input stream part from a DOM part for the metadata of the document.
*
* @param element
* a relevant DOM element for the metadata
* @exception MCRException
* if the xlink:type is not locator or arc or if href or from and to are null or empty
*/
@Override
public void setFromDOM(Element element) throws MCRException {
super.setFromDOM(element);
String temp = element.getAttributeValue("type", XLINK_NAMESPACE);
if (temp != null && (temp.equals("locator") || temp.equals("arc"))) {
linktype = temp;
} else {
throw new MCRException("The xlink:type is not locator or arc.");
}
if (linktype.equals("locator")) {
String temp1 = element.getAttributeValue("href", XLINK_NAMESPACE);
String temp2 = element.getAttributeValue("label", XLINK_NAMESPACE);
String temp3 = element.getAttributeValue("title", XLINK_NAMESPACE);
setReference(temp1, temp2, temp3);
} else {
String temp1 = element.getAttributeValue("from", XLINK_NAMESPACE);
String temp2 = element.getAttributeValue("to", XLINK_NAMESPACE);
String temp3 = element.getAttributeValue("title", XLINK_NAMESPACE);
setBiLink(temp1, temp2, temp3);
}
setXLinkRole(element.getAttributeValue("role", XLINK_NAMESPACE));
}
/**
* This method create a XML stream for all data in this class,
* defined by the MyCoRe XML MCRMetaLink definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaLink part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
elm.setAttribute("type", linktype, XLINK_NAMESPACE);
if (title != null) {
elm.setAttribute("title", title, XLINK_NAMESPACE);
}
if (label != null) {
elm.setAttribute("label", label, XLINK_NAMESPACE);
}
if (role != null) {
elm.setAttribute("role", role, XLINK_NAMESPACE);
}
if (linktype.equals("locator")) {
elm.setAttribute("href", href, XLINK_NAMESPACE);
} else {
elm.setAttribute("from", from, XLINK_NAMESPACE);
elm.setAttribute("to", to, XLINK_NAMESPACE);
}
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* For linktype equals 'locator':
* <pre>
* {
* label: "MyCoRe Derivate Image",
* title: "MyCoRe Derivate Image",
* role: "image_reference",
* href: "mycore_derivate_00000001/image.tif"
* }
* </pre>
*
* For all other linktypes (arc):
* <pre>
* {
* label: "Link between Issue and Person",
* title: "Link between Issue and Person",
* role: "link",
* from: "mycore_issue_00000001",
* to: "mycore_person_00000001"
* }
* </pre>
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
if (title != null) {
obj.addProperty("title", title);
}
if (label != null) {
obj.addProperty("label", label);
}
if (role != null) {
obj.addProperty("role", role);
}
if (linktype.equals("locator")) {
obj.addProperty("href", href);
} else {
obj.addProperty("from", from);
obj.addProperty("to", to);
}
return obj;
}
/**
* Validates this MCRMetaLink. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the xlink:type not "locator" or "arc"</li>
* <li>the from or to are not valid</li>
* </ul>
*
* @throws MCRException the MCRMetaLink is invalid
*/
public void validate() throws MCRException {
super.validate();
if (label != null && label.length() > 0) {
if (!XMLChar.isValidNCName(label)) {
throw new MCRException(getSubTag() + ": label is no valid NCName:" + label);
}
}
if (linktype == null) {
throw new MCRException(getSubTag() + ": linktype is null");
}
if (!linktype.equals("locator") && !linktype.equals("arc")) {
throw new MCRException(getSubTag() + ": linktype is unsupported: " + linktype);
}
if (linktype.equals("arc")) {
if (from == null || from.length() == 0) {
throw new MCRException(getSubTag() + ": from is null or empty");
} else if (!XMLChar.isValidNCName(from)) {
throw new MCRException(getSubTag() + ": from is no valid NCName:" + from);
}
if (to == null || to.length() == 0) {
throw new MCRException(getSubTag() + ": to is null or empty");
} else if (!XMLChar.isValidNCName(to)) {
throw new MCRException(getSubTag() + ": to is no valid NCName:" + to);
}
}
if (linktype.equals("locator")) {
if (href == null || href.length() == 0) {
throw new MCRException(getSubTag() + ": href is null or empty");
}
}
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaLink clone() {
MCRMetaLink clone = (MCRMetaLink) super.clone();
clone.href = this.href;
clone.label = this.label;
clone.title = this.title;
clone.linktype = this.linktype;
clone.role = this.role;
clone.from = this.from;
clone.to = this.to;
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public final void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Link Type = {}", linktype);
LOGGER.debug("Label = {}", label);
LOGGER.debug("Title = {}", title);
LOGGER.debug("HREF = {}", href);
LOGGER.debug("Role = {}", role);
LOGGER.debug("From = {}", from);
LOGGER.debug("To = {}", to);
LOGGER.debug("");
}
}
}
| 14,885 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObject.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObject.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.io.IOException;
import java.net.URI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.MCRException;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.common.MCRActiveLinkException;
import com.google.gson.JsonObject;
/**
* This class holds all information of a metadata object.
* For persistence operations see methods of {@link MCRMetadataManager}.
*
* @author Jens Kupferschmidt
* @author Mathias Hegner
* @author Thomas Scheffler (yagee)
*/
public final class MCRObject extends MCRBase {
private static final Logger LOGGER = LogManager.getLogger();
public static final String ROOT_NAME = "mycoreobject";
/**
* constant value for the object id length
*/
public static final int MAX_LABEL_LENGTH = 256;
/**
* the object content
*/
private final MCRObjectStructure structure;
private final MCRObjectMetadata metadata;
protected String mcrLabel = null;
/**
* This is the constructor of the MCRObject class. It creates an instance of
* the parser class and the metadata class. <br>
* The constructor reads the following information from the property file:
* <ul>
* <li>MCR.XMLParser.Class</li>
* </ul>
*
* @exception MCRException
* general Exception of MyCoRe
*/
public MCRObject() throws MCRException {
super();
structure = new MCRObjectStructure();
metadata = new MCRObjectMetadata();
mcrLabel = "";
}
public MCRObject(byte[] bytes, boolean valid) throws JDOMException {
this();
setFromXML(bytes, valid);
}
public MCRObject(Document doc) {
this();
setFromJDOM(doc);
}
public MCRObject(URI uri) throws IOException, JDOMException {
this();
setFromURI(uri);
}
/**
* This method returns the instance of the MCRObjectMetadata class. If there
* was no MCRObjectMetadata found, null will be returned.
*
* @return the instance of the MCRObjectMetadata class
*/
public MCRObjectMetadata getMetadata() {
return metadata;
}
/**
* This method return the instance of the MCRObjectStructure class. If this
* was not found, null was returned.
*
* @return the instance of the MCRObjectStructure class
*/
public MCRObjectStructure getStructure() {
return structure;
}
/**
* This methode return the object label. If this is not set, null was
* returned.
*
* @return the lable as a string
*/
public String getLabel() {
return mcrLabel;
}
/**
* This method set the object label.
*
* @param label
* the object label
*/
public void setLabel(String label) {
if (label == null) {
mcrLabel = label;
} else {
mcrLabel = label.trim();
if (mcrLabel.length() > MAX_LABEL_LENGTH) {
mcrLabel = mcrLabel.substring(0, MAX_LABEL_LENGTH);
}
}
}
/**
* The given DOM was convert into an internal view of metadata. This are the
* object ID and the object label, also the blocks structure, flags and
* metadata.
*
* @exception MCRException
* general Exception of MyCoRe
*/
@Override
protected void setUp() throws MCRException {
super.setUp();
setLabel(jdomDocument.getRootElement().getAttributeValue("label"));
// get the structure data of the object
Element structureElement = jdomDocument.getRootElement().getChild("structure");
if (structureElement != null) {
structure.setFromDOM(structureElement);
}
// get the metadata of the object
Element metadataElement = jdomDocument.getRootElement().getChild("metadata");
if (metadataElement != null) {
metadata.setFromDOM(metadataElement);
}
}
/**
* This method creates a XML stream for all object data.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Document with the XML data of the object as byte array
*/
@Override
public Document createXML() throws MCRException {
try {
Document doc = super.createXML();
Element elm = doc.getRootElement();
if (mcrLabel != null) {
elm.setAttribute("label", mcrLabel);
}
elm.addContent(structure.createXML());
elm.addContent(metadata.createXML());
elm.addContent(mcrService.createXML());
return doc;
} catch (MCRException exc) {
throw new MCRException("The content of '" + mcrId + "' is invalid.", exc);
}
}
/**
* Creates the JSON representation of this object. Extends the {@link MCRBase#createJSON()}
* method with the following content:
*
* <pre>
* {
* id: "mycore_project_00000001",
* version: "3.0"
* label: "my mycore object",
*
* structure: {@link MCRObjectStructure#createJSON},
* metadata: {@link MCRObjectMetadata#createJSON},
* service: {@link MCRObjectService#createJSON},
* }
* </pre>
*
* @return a json gson representation of this object
*/
@Override
public JsonObject createJSON() {
JsonObject object = super.createJSON();
if (mcrLabel != null) {
object.addProperty("label", mcrLabel);
}
object.add("structure", structure.createJSON());
object.add("metadata", metadata.createJSON());
object.add("service", mcrService.createJSON());
return object;
}
@Override
protected String getRootTagName() {
return ROOT_NAME;
}
/**
* The method print all informations about this MCRObject.
*/
public void debug() {
if (LOGGER.isDebugEnabled()) {
if (mcrId == null) {
LOGGER.debug("MCRObject ID : missing");
} else {
LOGGER.debug("MCRObject ID : {}", mcrId);
}
LOGGER.debug("MCRObject Label : {}", mcrLabel);
LOGGER.debug("MCRObject Schema : {}", mcrSchema);
LOGGER.debug("");
}
structure.debug();
metadata.debug();
}
/**
* Validates this MCRObject. This method throws an exception if:
* <ul>
* <li>the mcr_id is null</li>
* <li>the XML schema is null or empty</li>
* <li>the service part is null or invalid</li>
* <li>the structure part is null or invalid</li>
* <li>the metadata part is null or invalid</li>
* </ul>
*
* @throws MCRException the MCRObject is invalid
*/
@Override
public void validate() {
super.validate();
MCRObjectStructure structure = getStructure();
MCRObjectMetadata metadata = getMetadata();
if (structure == null) {
throw new MCRException("The <structure> part of '" + getId() + "' is undefined.");
}
if (metadata == null) {
throw new MCRException("The <metadata> part of '" + getId() + "' is undefined.");
}
try {
structure.validate();
} catch (MCRException exc) {
throw new MCRException("The <structure> part of '" + getId() + "' is invalid.", exc);
}
if (getId().equals(getParent())) {
throw new MCRException("This object '" + getId() + "' cannot be parent/child of itself.");
}
try {
metadata.validate();
} catch (MCRException exc) {
throw new MCRException("The <metadata> part of '" + getId() + "' is invalid.", exc);
}
}
/**
* @return true if the MCRObject has got a parent mcrobject, false otherwise
*/
public boolean hasParent() {
return getStructure().getParentID() != null;
}
public MCRObjectID getParent() {
return getStructure().getParentID();
}
public void checkLinkTargets() {
for (int i = 0; i < getMetadata().size(); i++) {
MCRMetaElement elm = getMetadata().getMetadataElement(i);
for (int j = 0; j < elm.size(); j++) {
MCRMetaInterface inf = elm.getElement(j);
if (inf instanceof MCRMetaClassification classification) {
String classID = classification.getClassId();
String categID = classification.getCategId();
boolean exists = MCRCategoryDAOFactory.getInstance().exist(new MCRCategoryID(classID, categID));
if (exists) {
continue;
}
MCRActiveLinkException activeLink = new MCRActiveLinkException(
"Failure while adding link!. Destination does not exist.");
String destination = classID + "##" + categID;
activeLink.addLink(getId().toString(), destination);
// throw activeLink;
// TODO: should trigger undo-Event
}
if (inf instanceof MCRMetaLinkID linkID) {
MCRObjectID destination = linkID.getXLinkHrefID();
if (MCRMetadataManager.exists(destination)) {
continue;
}
MCRActiveLinkException activeLink = new MCRActiveLinkException(
"Failure while adding link!. Destination does not exist.");
activeLink.addLink(getId().toString(), destination.toString());
// throw activeLink;
// TODO: should trigger undo-Event
}
}
}
}
}
| 10,899 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaDefault.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaDefault.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.language.MCRLanguageFactory;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.gson.JsonObject;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* This class implements any methods for handling the basic data for all
* metadata classes of the metadata objects. The methods createXML() and
* createTypedContent() and createTextSearch() are abstract methods.
*
* @author Jens Kupferschmidt
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY,
setterVisibility = JsonAutoDetect.Visibility.NONE)
public abstract class MCRMetaDefault implements MCRMetaInterface {
// public data
public static final int DEFAULT_LANG_LENGTH = 12;
public static final int DEFAULT_TYPE_LENGTH = 256;
public static final int DEFAULT_STRING_LENGTH = 4096;
// common data
protected static final String NL = System.getProperties().getProperty("line.separator");
protected static final String DEFAULT_LANGUAGE = MCRConfiguration2.getString("MCR.Metadata.DefaultLang")
.orElse(MCRConstants.DEFAULT_LANG);
protected static final String DEFAULT_ELEMENT_DATAPART = "metadata";
protected static final String DEFAULT_ATTRIBUTE_INHERITED = "inherited";
protected static final String DEFAULT_ATTRIBUTE_LANG = "lang";
protected static final String DEFAULT_ATTRIBUTE_SEQUENCE = "sequence";
protected static final String DEFAULT_ATTRIBUTE_TYPE = "type";
protected static final int DEFAULT_INHERITED = 0;
protected static final int DEFAULT_SEQUENCE = -1;
// logger
private static Logger LOGGER = LogManager.getLogger();
// MetaLangText data
protected String subtag;
protected String lang;
protected String type;
protected int sequence;
protected int inherited;
protected String datapart;
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The datapart element was set
* to <b>metadata </b>All other elemnts was set to an empty string. The
* inherited value is set to 0!
*/
public MCRMetaDefault() {
inherited = DEFAULT_INHERITED;
sequence = DEFAULT_SEQUENCE;
datapart = DEFAULT_ELEMENT_DATAPART;
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>lang</em> is
* empty or false <b>en </b> was set. The datapart was set to default. All
* other elemnts was set to an empty string. The inherited value is set to
* 0!
*
* @param lang
* the default language
*/
public MCRMetaDefault(String lang) {
this();
this.lang = lang;
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>lang</em> is
* null, empty or false <b>en </b> was set. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was throwed. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The datapart element was set. If the value of
* <em>datapart,</em> is null or empty the default was set.
* @param subtag the name of the subtag
* @param lang the language
* @param type the optional type string
* @param inherited a int value , > 0 if the data are inherited,
* else = 0.
*
* @exception MCRException if the subtag value is null or empty
*/
public MCRMetaDefault(String subtag, String lang, String type, int inherited)
throws MCRException {
this(lang);
setInherited(inherited);
this.subtag = subtag;
this.type = type;
this.sequence = DEFAULT_SEQUENCE;
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>lang</em> is
* null, empty or false <b>en </b> was set. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was throwed. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The datapart element was set. If the value of
* <em>datapart,</em> is null or empty the default was set.
* @param subtag the name of the subtag
* @param lang the language
* @param type the optional type string
* @param sequence the optional sequence attribute as integer
* @param inherited a int value , > 0 if the data are inherited,
* else = 0.
*
* @exception MCRException if the subtag value is null or empty
*/
public MCRMetaDefault(String subtag, String lang, String type, int sequence, int inherited)
throws MCRException {
this(lang);
setInherited(inherited);
this.subtag = subtag;
this.type = type;
setSequence(sequence);
}
/**
* This method set the inherited level. This can be 0 or an integer higher
* 0.
*
* @param value
* the inherited level value, if it is < 0, 0 is set
*/
public final void setInherited(int value) {
inherited = value;
}
/**
* This method increments the inherited value with 1.
*/
public final void incrementInherited() {
inherited++;
}
/**
* This method decrements the inherited value with 1.
*/
public final void decrementInherited() {
inherited--;
}
/**
* This method set the language element. If the value of
* <em>lang</em> is null, empty or false nothing was changed.
*
* @param lang
* the language
*/
public final void setLang(String lang) {
this.lang = lang;
}
/**
* This method set the subtag element. If the value of <em>subtag</em>
* is null or empty an exception was throwed.
*
* @param subtag
* the subtag
* @exception MCRException
* if the subtag value is null or empty
*/
public final void setSubTag(String subtag) throws MCRException {
this.subtag = subtag;
}
/**
* This method set the type element. If the value of <em>type</em> is
* null or empty nothing was changed.
*
* @param type
* the optional type
*/
public final void setType(String type) {
this.type = type;
}
/**
* This method set the sequence element. If the value of <em>sequence</em> is
* null or empty nothing was changed.
*
* @param sequence
* the optional sequence attribute
*/
public final void setSequence(int sequence) {
this.sequence = sequence;
}
/**
* This method get the inherited element.
*
* @return the inherited flag as int
*/
public final int getInherited() {
return inherited;
}
/**
* This method get the language element.
*
* @return the language
*/
public final String getLang() {
return lang;
}
/**
* This method get the subtag element.
*
* @return the subtag
*/
@Schema(hidden = true)
@JsonIgnore
public final String getSubTag() {
return subtag;
}
/**
* This method get the type element.
*
* @return the type
*/
public final String getType() {
return type;
}
/**
* This method get the sequence element.
*
* @return the sequence element
*/
public int getSequence() {
return sequence;
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant DOM element for the metadata
* @exception MCRException
* if the subtag value is null or empty
*/
public void setFromDOM(Element element) throws MCRException {
if (element == null) {
return;
}
subtag = element.getName();
MCRUtils.filterTrimmedNotEmpty(element.getAttributeValue(DEFAULT_ATTRIBUTE_LANG, Namespace.XML_NAMESPACE))
.ifPresent(tempLang -> lang = tempLang);
MCRUtils.filterTrimmedNotEmpty(element.getAttributeValue(DEFAULT_ATTRIBUTE_TYPE))
.ifPresent(tempType -> type = tempType);
MCRUtils.filterTrimmedNotEmpty(element.getAttributeValue(DEFAULT_ATTRIBUTE_SEQUENCE))
.map(Integer::parseInt)
.ifPresent(tempSequence -> sequence = tempSequence);
MCRUtils.filterTrimmedNotEmpty(element.getAttributeValue(DEFAULT_ATTRIBUTE_INHERITED))
.map(Integer::parseInt)
.ifPresent(tempInherited -> inherited = tempInherited);
}
/**
* This abstract method create a XML stream for all data in this class,
* defined by the MyCoRe XML MCRMeta... definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMeta... part
*/
public Element createXML() throws MCRException {
try {
validate();
} catch (MCRException exc) {
debug();
throw exc;
}
Element elm = new Element(subtag);
if (getLang() != null && getLang().length() > 0) {
elm.setAttribute(DEFAULT_ATTRIBUTE_LANG, getLang(), Namespace.XML_NAMESPACE);
}
if (getType() != null && getType().length() > 0) {
elm.setAttribute(DEFAULT_ATTRIBUTE_TYPE, getType());
}
if (getSequence() >= 0) {
elm.setAttribute(DEFAULT_ATTRIBUTE_SEQUENCE, Integer.toString(getSequence()));
}
elm.setAttribute(DEFAULT_ATTRIBUTE_INHERITED, Integer.toString(getInherited()));
return elm;
}
/**
* Creates a json object in the form of:
* <pre>
* {
* lang: "de",
* type: "title",
* sequence: "0001"
* inherited: 0
* }
* </pre>
*/
@Override
public JsonObject createJSON() {
JsonObject obj = new JsonObject();
if (getLang() != null) {
obj.addProperty(DEFAULT_ATTRIBUTE_LANG, getLang());
}
if (getType() != null) {
obj.addProperty(DEFAULT_ATTRIBUTE_TYPE, getType());
}
if (getSequence() >= 0) {
obj.addProperty(DEFAULT_ATTRIBUTE_SEQUENCE, getSequence());
}
obj.addProperty(DEFAULT_ATTRIBUTE_INHERITED, getInherited());
return obj;
}
/**
* This method check the validation of the content of this class. The method
* returns <em>true</em> if
* <ul>
* <li>the subtag is not null or empty
* <li>the lang value was supported
* </ul>
* otherwise the method return <em>false</em>
*
* @return a boolean value
*/
@JsonIgnore
public boolean isValid() {
try {
validate();
return true;
} catch (MCRException exc) {
LOGGER.warn("The the metadata element '{}' is invalid.", subtag, exc);
}
return false;
}
/**
* Validates this MCRMetaDefault. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* </ul>
*
* @throws MCRException the MCRMetaDefault is invalid
*/
public void validate() throws MCRException {
subtag = MCRUtils.filterTrimmedNotEmpty(subtag).orElse(null);
if (subtag == null) {
throw new MCRException("No tag name defined!");
}
if (lang != null && !MCRLanguageFactory.instance().isSupportedLanguage(lang)) {
throw new MCRException(getSubTag() + ": language is not supported: " + lang);
}
if (getInherited() < 0) {
throw new MCRException(getSubTag() + ": inherited can not be smaller than '0': " + getInherited());
}
}
@Override
public int hashCode() {
return Objects.hash(datapart, inherited, lang, subtag, type, sequence);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
MCRMetaDefault other = (MCRMetaDefault) obj;
return Objects.equals(datapart, other.datapart) && Objects.equals(inherited, other.inherited)
&& Objects.equals(lang, other.lang) && Objects.equals(subtag, other.subtag)
&& Objects.equals(type, other.type) && Objects.equals(sequence, other.sequence);
}
/**
* This method put debug data to the logger (for the debug mode).
*/
public void debug() {
if (LOGGER.isDebugEnabled()) {
debugDefault();
LOGGER.debug(" ");
}
}
/**
* This method put common debug data to the logger (for the debug mode).
*/
public final void debugDefault() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("SubTag = {}", subtag);
LOGGER.debug("Language = {}", lang);
LOGGER.debug("Type = {}", type);
LOGGER.debug("Sequence = {}", String.valueOf(sequence));
LOGGER.debug("DataPart = {}", datapart);
LOGGER.debug("Inhreited = {}", String.valueOf(inherited));
}
}
@Override
public MCRMetaDefault clone() {
try {
MCRMetaDefault clone = (MCRMetaDefault) super.clone();
clone.subtag = this.subtag;
clone.lang = this.lang;
clone.type = this.type;
clone.sequence = this.sequence;
clone.datapart = this.datapart;
clone.inherited = this.inherited;
return clone;
} catch (CloneNotSupportedException e) {
//this is impossible!
return null;
}
}
}
| 15,597 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jdom2.Attribute;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.common.MCRLinkTableManager;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
/**
* This class contains several helper methods for {@link MCRObject}.
*
* @author Matthias Eichner
*/
public abstract class MCRObjectUtils {
private static XPathExpression<Attribute> META_LINK_HREF;
private static XPathExpression<Element> META_CLASS;
static {
// META_LINK_HREF
String linkExp = "./mycoreobject/metadata/*[@class='MCRMetaLinkID']/*/@xlink:href";
META_LINK_HREF = XPathFactory.instance().compile(linkExp, Filters.attribute(), null,
MCRConstants.getStandardNamespaces());
// META_CLASS
String classExp = "./mycoreobject/metadata/*[@class='MCRMetaClassification']/*";
META_CLASS = XPathFactory.instance().compile(classExp, Filters.element(), null,
MCRConstants.getStandardNamespaces());
}
/**
* Retrieves a list of all ancestors of the given object. The first entry
* is the parent object, the last entry is the root node. Returns an empty
* list if no ancestor is found.
*
* @return list of ancestors
*/
public static List<MCRObject> getAncestors(MCRObject mcrObject) {
List<MCRObject> ancestorList = new ArrayList<>();
while (mcrObject.hasParent()) {
MCRObjectID parentID = mcrObject.getStructure().getParentID();
MCRObject parent = MCRMetadataManager.retrieveMCRObject(parentID);
ancestorList.add(parent);
mcrObject = parent;
}
return ancestorList;
}
/**
* Returns a list of all ancestors and the object itself. The first entry
* is the object itself, the last entry is the root node. Returns a list
* with one entry if no ancestor is found.
*
* @return list of ancestors
*/
public static List<MCRObject> getAncestorsAndSelf(MCRObject mcrObject) {
List<MCRObject> ancestorList = new ArrayList<>();
ancestorList.add(mcrObject);
ancestorList.addAll(getAncestors(mcrObject));
return ancestorList;
}
/**
* Returns the root ancestor of the given object. If the object has
* no parent null is returned.
*
* @param mcrObject object to get the root node
* @return root <code>MCRObject</code>
*/
public static MCRObject getRoot(MCRObject mcrObject) {
List<MCRObject> ancestorList = getAncestors(mcrObject);
return ancestorList.isEmpty() ? null : ancestorList.get(ancestorList.size() - 1);
}
/**
* Returns all children of the given object. If the object has no
* children, an empty list is returned.
*
* @param mcrObject the mycore object
* @return list of all children
*/
public static List<MCRObject> getChildren(MCRObject mcrObject) {
return mcrObject.getStructure()
.getChildren()
.stream()
.map(MCRMetaLinkID::getXLinkHrefID)
.map(MCRMetadataManager::retrieveMCRObject)
.collect(Collectors.toList());
}
/**
* Returns a list of all descendants and the object itself. For more information
* see {@link MCRObjectUtils#getDescendants}.
*
* @return list of all descendants and the object itself
*/
public static List<MCRObject> getDescendantsAndSelf(MCRObject mcrObject) {
List<MCRObject> objectList = getDescendants(mcrObject);
objectList.add(mcrObject);
return objectList;
}
/**
* Returns a list of all descendants of the given object. Be aware that
* there is no specific order. The list is empty if the object has no
* children.
*
* @return list of all descendants
*/
public static List<MCRObject> getDescendants(MCRObject mcrObject) {
List<MCRObject> objectList = new ArrayList<>();
getChildren(mcrObject).forEach(child -> objectList.addAll(getDescendantsAndSelf(child)));
return objectList;
}
/**
* Returns all derivates connected with this object. This includes derivates which are defined in the
* structure part and also derivate links.
*
* @param mcrObjectID object identifier to get the root node
* @return set of derivates
*/
public static List<MCRObjectID> getDerivates(MCRObjectID mcrObjectID) {
MCRLinkTableManager linkTableManager = MCRLinkTableManager.instance();
Stream<String> derivateStream = linkTableManager
.getDestinationOf(mcrObjectID, MCRLinkTableManager.ENTRY_TYPE_DERIVATE).stream();
Stream<String> derivateLinkStream = linkTableManager
.getDestinationOf(mcrObjectID, MCRLinkTableManager.ENTRY_TYPE_DERIVATE_LINK).stream()
.map(link -> link.substring(0, link.indexOf("/")));
return Stream.concat(derivateStream, derivateLinkStream).distinct().map(MCRObjectID::getInstance)
.collect(Collectors.toList());
}
/**
* Returns a list of {@link MCRObject}s which are linked in the given object
* by an {@link MCRMetaLinkID}. This does not return any {@link MCRObjectStructure}
* links or any {@link MCRMetaDerivateLink}s.
*
* @param object the object where to get the entitylinks from
* @return a list of linked objects
* @throws MCRPersistenceException one of the linked objects does not exists
*/
public static List<MCRObject> getLinkedObjects(MCRObject object) throws MCRPersistenceException {
Stream<String> stream = META_LINK_HREF.evaluate(object.createXML()).stream().map(Attribute::getValue);
return stream.map(MCRObjectID::getInstance).peek(id -> {
if (!MCRMetadataManager.exists(id)) {
throw new MCRPersistenceException("MCRObject " + id + " is linked with (part of the metadata) "
+ object.getId() + " but does not exist.");
}
}).map(MCRMetadataManager::retrieveMCRObject).collect(Collectors.toList());
}
/**
* <p>Removes all links of the source object. This includes parent links, children links and metadata links. A list
* of all updated objects is returned.</p>
* <p>Be aware that this method does not take care of storing the returned objects.</p>
*
* @param sourceId id of the object
* @return a stream of updated objects where a link of the source was removed
*/
public static Stream<MCRObject> removeLinks(MCRObjectID sourceId) {
return MCRLinkTableManager.instance().getSourceOf(sourceId).stream().filter(MCRObjectID::isValid)
.map(MCRObjectID::getInstance).distinct().map(MCRMetadataManager::retrieveMCRObject)
.flatMap(linkedObject -> MCRObjectUtils.removeLink(linkedObject, sourceId) ? Stream.of(linkedObject)
: Stream.empty());
}
/**
* <p>Removes the <b>linkToRemove</b> in the metadata and the structure part of the <b>source</b> object. Be aware
* that this can lead to a zombie source object without a parent! Use this method with care!</p>
*
* <p>This method does not take care of storing the source object.</p>
*
* @param source the source object where the links should be removed from
* @param linkToRemove the link id to remove
* @return true if a link was removed (the source object changed)
*/
public static boolean removeLink(MCRObject source, MCRObjectID linkToRemove) {
final AtomicBoolean updated = new AtomicBoolean(false);
// remove parent
if (source.getParent() != null && source.getParent().equals(linkToRemove)) {
source.getStructure().removeParent();
updated.set(true);
}
// remove children
if (source.getStructure().removeChild(linkToRemove)) {
updated.set(true);
}
// remove metadata parts
List<MCRMetaElement> emptyElements = source.getMetadata().stream()
.filter(metaElement -> metaElement.getClazz().equals(MCRMetaLinkID.class))
.flatMap(metaElement -> {
List<MCRMetaLinkID> linksToRemove = metaElement.stream().map(MCRMetaLinkID.class::cast)
.filter(metaLinkID -> metaLinkID.getXLinkHrefID().equals(linkToRemove))
.collect(Collectors.toList());
if (linksToRemove.size() > 0) {
updated.set(true);
linksToRemove.forEach(metaElement::removeMetaObject);
}
return metaElement.size() == 0 ? Stream.of(metaElement) : Stream.empty();
}).collect(Collectors.toList());
emptyElements.forEach(source.getMetadata()::removeMetadataElement);
return updated.get();
}
/**
* Returns a list of {@link MCRCategoryID}s which are used in the given object.
*
* @param object the object where to get the categories from
* @return a list of linked categories
*/
public static List<MCRCategoryID> getCategories(MCRObject object) {
Stream<Element> stream = META_CLASS.evaluate(object.createXML()).stream();
return stream.map((e) -> {
String classId = e.getAttributeValue("classid");
String categId = e.getAttributeValue("categid");
return new MCRCategoryID(classId, categId);
}).distinct().collect(Collectors.toList());
}
/**
* Restores a MyCoRe Object to the selected revision. Please note that children and derivates
* are not deleted or reverted!
*
* @param mcrId the mycore object identifier
* @param revision The revision to restore to. If this is lower than zero, the last revision is used.
* @return the new {@link MCRObject}
*
* @throws IOException An error occurred while retrieving the revision information. This is most
* likely due an svn error.
* @throws MCRPersistenceException There is no such object with the given id and revision.
* @throws ClassCastException The returning type must be the same as the type of the restored object
*/
public static <T extends MCRBase> T restore(MCRObjectID mcrId, String revision) throws IOException,
MCRPersistenceException {
@SuppressWarnings("unchecked")
T mcrBase = (T) (mcrId.getTypeId().equals("derivate") ? new MCRDerivate() : new MCRObject());
// get content
MCRXMLMetadataManager xmlMetadataManager = MCRXMLMetadataManager.instance();
MCRContent content = xmlMetadataManager.retrieveContent(mcrId, revision);
if (content == null) {
throw new MCRPersistenceException("No such object " + mcrId + " with revision " + revision + ".");
}
// store it
try {
mcrBase.setFromJDOM(content.asXML());
if (MCRMetadataManager.exists(mcrId)) {
// set modified date to now() to force update
mcrBase.getService().setDate(MCRObjectService.DATE_TYPE_MODIFYDATE, new Date());
MCRMetadataManager.update(mcrBase);
} else {
if (mcrBase instanceof MCRObject object) {
MCRMetadataManager.create(object);
} else {
MCRMetadataManager.create((MCRDerivate) mcrBase);
}
}
return mcrBase;
} catch (Exception exc) {
throw new MCRException("Unable to get object " + mcrId + " with revision " + revision + ".", exc);
}
}
}
| 12,919 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaBoolean.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaBoolean.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import com.google.gson.JsonObject;
/**
* This class implements all method for handling with the MCRMetaBoolean part of
* a metadata object. The MCRMetaBoolean class present a logical value of true
* or false and optional a type.
* <p>
* <tag class="MCRMetaBoolean" heritable="..."> <br>
* <subtag type="..."> <br>
* true|false<br>
* </subtag> <br>
* </tag> <br>
*
* @author Jens Kupferschmidt
*/
public final class MCRMetaBoolean extends MCRMetaDefault {
private boolean value;
private static final Logger LOGGER = LogManager.getLogger();
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The boolean value was set to
* false.
*/
public MCRMetaBoolean() {
super();
value = false;
}
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was thrown. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The boolean string <em>value</em>
* was set to a boolean element, if it is null, false was set.
* @param subtag the name of the subtag
* @param lang the language
* @param type the optional type string
* @param inherted a value >= 0
* @param value the boolean value (true or false) as string
*
* @exception MCRException if the subtag value is null or empty
*/
@Deprecated
public MCRMetaBoolean(String subtag, String lang, String type, int inherted, String value)
throws MCRException {
this(subtag, type, inherted, false);
setValue(value);
}
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was thrown. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The boolean string <em>value</em>
* was set to a boolean element, if it is null, false was set.
* @param subtag the name of the subtag
* @param type the optional type string
* @param inherted a value >= 0
* @param value the boolean value (true or false) as string
*
* @exception MCRException if the subtag value is null or empty
*/
public MCRMetaBoolean(String subtag, String type, int inherted, String value)
throws MCRException {
super(subtag, null, type, inherted);
setValue(value);
}
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was thrown. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The boolean string <em>value</em>
* was set to a boolean element, if it is null, false was set.
* @param subtag the name of the subtag
* @param type the optional type string
* @param inherted a value >= 0
* @param value the boolean value (true or false)
* @exception MCRException if the subtag value is null or empty
*/
public MCRMetaBoolean(String subtag, String type, int inherted, boolean value) throws MCRException {
super(subtag, null, type, inherted);
setValue(value);
}
/**
* This method set value. It set false if the string is corrupt.
*
* @param value
* the boolean value (true or false) as string
*/
public void setValue(String value) {
this.value = Boolean.parseBoolean(value);
}
/**
* This method set the value.
*
* @param value
* the boolean value
*/
public void setValue(boolean value) {
this.value = value;
}
/**
* This method get the value element.
*
* @return the value as Boolean
*/
public boolean getValue() {
return value;
}
/**
* This method get the value element as String.
*
* @return the value as String
*/
public String getValueToString() {
return String.valueOf(value);
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
setValue(element.getTextTrim());
}
/**
* This method create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRBoolean definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRBoolean part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
elm.addContent(getValueToString());
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* value: true|false
* }
* </pre>
*
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
obj.addProperty("value", getValue());
return obj;
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaBoolean clone() {
MCRMetaBoolean clone = (MCRMetaBoolean) super.clone();
clone.value = this.value;
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Value = {}", Boolean.toString(value));
LOGGER.debug(" ");
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaBoolean other = (MCRMetaBoolean) obj;
return this.value == other.value;
}
}
| 7,634 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetadataManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetadataManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import static org.mycore.access.MCRAccessManager.PERMISSION_DELETE;
import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.mycore.access.MCRAccessException;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRCache.ModifiedHandle;
import org.mycore.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventManager;
import org.mycore.datamodel.common.MCRActiveLinkException;
import org.mycore.datamodel.common.MCRDefaultObjectIDGenerator;
import org.mycore.datamodel.common.MCRLinkTableManager;
import org.mycore.datamodel.common.MCRMarkManager;
import org.mycore.datamodel.common.MCRMarkManager.Operation;
import org.mycore.datamodel.common.MCRObjectIDGenerator;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.share.MCRMetadataShareAgent;
import org.mycore.datamodel.metadata.share.MCRMetadataShareAgentFactory;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter;
import org.mycore.datamodel.niofs.utils.MCRTreeCopier;
import jakarta.persistence.PersistenceException;
/**
* Delivers persistence operations for {@link MCRObject} and {@link MCRDerivate} .
*
* @author Thomas Scheffler (yagee)
* @since 2.0.92
*/
public final class MCRMetadataManager {
private static final Logger LOGGER = LogManager.getLogger();
private static final MCRCache<MCRObjectID, MCRObjectID> DERIVATE_OBJECT_MAP = new MCRCache<>(10000,
"derivate objectid cache");
private static final MCRCache<MCRObjectID, List<MCRObjectID>> OBJECT_DERIVATE_MAP = new MCRCache<>(10000,
"derivate objectid cache");
private static final MCRXMLMetadataManager XML_MANAGER = MCRXMLMetadataManager.instance();
private static final MCRObjectIDGenerator MCROBJECTID_GENERATOR
= MCRConfiguration2.getSingleInstanceOf("MCR.Metadata.ObjectID.Generator.Class",
MCRDefaultObjectIDGenerator.class).get();
private MCRMetadataManager() {
}
public static MCRObjectIDGenerator getMCRObjectIDGenerator() {
return MCROBJECTID_GENERATOR;
}
/**
* Returns the MCRObjectID of the object containing derivate with the given ID.
*
* @param derivateID
* derivateID
* @param expire
* when should lastModified information expire
* @return null if derivateID has no object referenced
* @see #getDerivateIds(MCRObjectID, long, TimeUnit)
*/
public static MCRObjectID getObjectId(final MCRObjectID derivateID, final long expire, TimeUnit unit) {
ModifiedHandle modifiedHandle = XML_MANAGER.getLastModifiedHandle(derivateID, expire, unit);
MCRObjectID mcrObjectID = null;
try {
mcrObjectID = DERIVATE_OBJECT_MAP.getIfUpToDate(derivateID, modifiedHandle);
} catch (IOException e) {
LOGGER.warn("Could not determine last modified timestamp of derivate {}", derivateID);
}
if (mcrObjectID != null) {
return mcrObjectID;
}
//one cheap db query
Collection<String> list = MCRLinkTableManager.instance().getSourceOf(derivateID,
MCRLinkTableManager.ENTRY_TYPE_DERIVATE);
if (!(list == null || list.isEmpty())) {
mcrObjectID = MCRObjectID.getInstance(list.iterator().next());
} else {
//one expensive process
if (MCRMetadataManager.exists(derivateID)) {
mcrObjectID = MCRMetadataManager.retrieveMCRDerivate(derivateID).getOwnerID();
}
}
if (mcrObjectID == null) {
return null;
}
DERIVATE_OBJECT_MAP.put(derivateID, mcrObjectID);
return mcrObjectID;
}
/**
* Returns a list of MCRObjectID of the derivates contained in the object with the given ID.
*
* @param objectId
* objectId
* @param expire
* when should lastModified information expire
* @return null if object with objectId does not exist
* @see #getObjectId(MCRObjectID, long, TimeUnit)
*/
public static List<MCRObjectID> getDerivateIds(final MCRObjectID objectId, final long expire, final TimeUnit unit) {
ModifiedHandle modifiedHandle = XML_MANAGER.getLastModifiedHandle(objectId, expire, unit);
List<MCRObjectID> derivateIds = null;
try {
derivateIds = OBJECT_DERIVATE_MAP.getIfUpToDate(objectId, modifiedHandle);
} catch (IOException e) {
LOGGER.warn("Could not determine last modified timestamp of derivate {}", objectId);
}
if (derivateIds != null) {
return derivateIds;
}
derivateIds = MCRObjectUtils.getDerivates(objectId);
if (!derivateIds.isEmpty()) {
return derivateIds;
} else {
if (MCRMetadataManager.exists(objectId)) {
MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(objectId);
List<MCRMetaEnrichedLinkID> derivates = mcrObject.getStructure().getDerivates();
for (MCRMetaEnrichedLinkID der : derivates) {
derivateIds.add(der.getXLinkHrefID());
}
}
}
return derivateIds;
}
/**
* Stores the derivate.
*
* @param mcrDerivate
* derivate instance to store
* @throws MCRPersistenceException
* if a persistence problem is occurred
* @throws MCRAccessException
* if write permission to object is missing or create permission to derivate is missing
*/
public static void create(final MCRDerivate mcrDerivate) throws MCRPersistenceException, MCRAccessException {
MCRObjectID derivateId = mcrDerivate.getId();
checkCreatePrivilege(derivateId);
if (MCRMetadataManager.exists(derivateId)) {
throw new MCRPersistenceException("The derivate " + derivateId + " already exists, nothing done.");
}
// assign new id if necessary
if (derivateId.getNumberAsInteger() == 0) {
derivateId = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(derivateId.getBase());
mcrDerivate.setId(derivateId);
LOGGER.info("Assigned new derivate id {}", derivateId);
}
try {
mcrDerivate.validate();
} catch (MCRException exc) {
throw new MCRPersistenceException("The derivate " + derivateId + " is not valid.", exc);
}
final MCRObjectID objectId = mcrDerivate.getDerivate().getMetaLink().getXLinkHrefID();
if (!MCRAccessManager.checkPermission(objectId, PERMISSION_WRITE)) {
throw MCRAccessException.missingPermission("Add derivate " + derivateId + " to object.",
objectId.toString(),
PERMISSION_WRITE);
}
byte[] objectBackup;
try {
objectBackup = MCRXMLMetadataManager.instance().retrieveBLOB(objectId);
} catch (IOException ioExc) {
throw new MCRPersistenceException("Unable to retrieve xml blob of " + objectId);
}
if (objectBackup == null) {
throw new MCRPersistenceException(
"Cannot find " + objectId + " to attach derivate " + derivateId + " to it.");
}
// prepare the derivate metadata and store under the XML table
if (mcrDerivate.getService().getDate("createdate") == null || !mcrDerivate.isImportMode()) {
mcrDerivate.getService().setDate("createdate");
}
if (mcrDerivate.getService().getDate("modifydate") == null || !mcrDerivate.isImportMode()) {
mcrDerivate.getService().setDate("modifydate");
}
// handle events
fireEvent(mcrDerivate, null, MCREvent.EventType.CREATE);
// create data in IFS
if (mcrDerivate.getDerivate().getInternals() != null) {
MCRPath rootPath = MCRPath.getPath(derivateId.toString(), "/");
if (mcrDerivate.getDerivate().getInternals().getSourcePath() == null) {
try {
rootPath.getFileSystem().createRoot(rootPath.getOwner());
} catch (IOException ioExc) {
throw new MCRPersistenceException(
"Cannot create root of '" + rootPath.getOwner() + "'.", ioExc);
}
} else {
final String sourcepath = mcrDerivate.getDerivate().getInternals().getSourcePath();
final Path f = Paths.get(sourcepath);
if (Files.exists(f)) {
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Starting File-Import");
}
importDerivate(derivateId.toString(), f);
} catch (final Exception e) {
if (Files.exists(rootPath)) {
deleteDerivate(derivateId.toString());
}
MCRMetadataManager.restore(mcrDerivate, objectId, objectBackup);
throw new MCRPersistenceException("Can't add derivate to the IFS", e);
}
} else {
LOGGER.warn("Empty derivate, the File or Directory -->{}<-- was not found.", sourcepath);
}
}
}
// add the link to metadata
final MCRMetaEnrichedLinkID der = MCRMetaEnrichedLinkIDFactory.getInstance().getDerivateLink(mcrDerivate);
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("adding Derivate in data store");
}
MCRMetadataManager.addOrUpdateDerivateToObject(objectId, der, mcrDerivate.isImportMode());
} catch (final Exception e) {
MCRMetadataManager.restore(mcrDerivate, objectId, objectBackup);
// throw final exception
throw new MCRPersistenceException("Error while creating link to MCRObject " + objectId + ".", e);
}
}
private static void deleteDerivate(String derivateID) throws MCRPersistenceException {
try {
MCRPath rootPath = MCRPath.getPath(derivateID, "/");
if (!Files.exists(rootPath)) {
LOGGER.info("Derivate does not exist: {}", derivateID);
return;
}
Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance());
rootPath.getFileSystem().removeRoot(derivateID);
} catch (Exception exc) {
throw new MCRPersistenceException("Unable to delete derivate " + derivateID, exc);
}
}
private static void importDerivate(String derivateID, Path sourceDir) throws MCRPersistenceException {
try {
MCRPath rootPath = MCRPath.getPath(derivateID, "/");
if (Files.exists(rootPath)) {
LOGGER.info("Derivate does already exist: {}", derivateID);
}
rootPath.getFileSystem().createRoot(derivateID);
Files.walkFileTree(sourceDir, new MCRTreeCopier(sourceDir, rootPath));
} catch (Exception exc) {
throw new MCRPersistenceException(
"Unable to import derivate " + derivateID + " from source " + sourceDir.toAbsolutePath(),
exc);
}
}
/**
* Stores the object.
*
* @param mcrObject
* object instance to store
* @exception MCRPersistenceException
* if a persistence problem is occured
* @throws MCRAccessException if "create-{objectType}" privilege is missing
*/
public static void create(final MCRObject mcrObject) throws MCRPersistenceException, MCRAccessException {
MCRObjectID objectId = Objects.requireNonNull(mcrObject.getId(), "ObjectID must not be null");
checkCreatePrivilege(objectId);
// exist the object?
if (MCRMetadataManager.exists(objectId)) {
throw new MCRPersistenceException("The object " + objectId + " already exists, nothing done.");
}
// assign new id if necessary
if (objectId.getNumberAsInteger() == 0) {
MCRObjectID oldId = objectId;
objectId = MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId(objectId.getBase());
mcrObject.setId(objectId);
LOGGER.info("Assigned new object id {}", objectId);
// if label was id with 00000000, set label to new id
if (Objects.equals(mcrObject.getLabel(), oldId.toString())) {
mcrObject.setLabel(objectId.toString());
}
}
// create this object in datastore
if (mcrObject.getService().getDate("createdate") == null) {
mcrObject.getService().setDate("createdate");
}
if (mcrObject.getService().getDate("modifydate") == null) {
mcrObject.getService().setDate("modifydate");
}
// prepare this object with parent metadata
receiveMetadata(mcrObject);
final MCRObjectID parentId = mcrObject.getStructure().getParentID();
MCRObject parent = null;
if (parentId != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parent ID = {}", parentId);
}
parent = MCRMetadataManager.retrieveMCRObject(parentId);
}
// handle events
fireEvent(mcrObject, null, MCREvent.EventType.CREATE);
// add the MCRObjectID to the child list in the parent object
if (parentId != null) {
parent.getStructure().addChild(new MCRMetaLinkID("child", objectId,
mcrObject.getStructure().getParent().getXLinkLabel(), mcrObject.getLabel()));
MCRMetadataManager.fireUpdateEvent(parent);
}
}
public static void checkCreatePrivilege(MCRObjectID objectId) throws MCRAccessException {
String createBasePrivilege = "create-" + objectId.getBase();
String createTypePrivilege = "create-" + objectId.getTypeId();
if (!MCRAccessManager.checkPermission(createBasePrivilege)
&& !MCRAccessManager.checkPermission(createTypePrivilege)) {
throw MCRAccessException.missingPrivilege("Create base with id " + objectId, createBasePrivilege,
createTypePrivilege);
}
}
/**
* Deletes MCRDerivate.
*
* @param mcrDerivate
* to be deleted
* @throws MCRPersistenceException
* if persistence problem occurs
* @throws MCRAccessException
* if delete permission is missing
*/
public static void delete(final MCRDerivate mcrDerivate) throws MCRPersistenceException, MCRAccessException {
MCRObjectID id = mcrDerivate.getId();
if (!MCRAccessManager.checkDerivateContentPermission(id, PERMISSION_DELETE)) {
throw MCRAccessException.missingPermission("Delete derivate", id.toString(), PERMISSION_DELETE);
}
// mark for deletion
MCRMarkManager.instance().mark(id, Operation.DELETE);
// remove link
MCRObjectID metaId = null;
try {
metaId = mcrDerivate.getDerivate().getMetaLink().getXLinkHrefID();
if (MCRMetadataManager.removeDerivateFromObject(metaId, id)) {
LOGGER.info("Link in MCRObject {} to MCRDerivate {} is deleted.", metaId, id);
} else {
LOGGER.warn("Link in MCRObject {} to MCRDerivate {} could not be deleted.", metaId, id);
}
} catch (final Exception e) {
LOGGER.warn("Can't delete link for MCRDerivate {} from MCRObject {}. Error ignored.", id, metaId);
}
// delete data from IFS
if (mcrDerivate.getDerivate().getInternals() != null) {
try {
deleteDerivate(id.toString());
LOGGER.info("IFS entries for MCRDerivate {} are deleted.", id);
} catch (final Exception e) {
throw new MCRPersistenceException("Error while delete MCRDerivate " + id + " in IFS", e);
}
}
// handle events
fireEvent(mcrDerivate, null, MCREvent.EventType.DELETE);
// remove mark
MCRMarkManager.instance().remove(id);
}
/**
* Deletes MCRObject.
*
* @param mcrObject
* to be deleted
* @throws MCRActiveLinkException
* cannot be deleted cause its still linked
* @throws MCRPersistenceException
* if persistence problem occurs
* @throws MCRAccessException
* if delete permission is missing
*/
public static void delete(final MCRObject mcrObject)
throws MCRPersistenceException, MCRActiveLinkException, MCRAccessException {
delete(mcrObject, MCRMetadataManager::removeChildObject);
}
/**
* Deletes the <code>mcrObject</code>.
*
* @param mcrObject
* the object to be deleted
* @param parentOperation
* function to handle the parent of the object @see {@link #removeChildObject(MCRObject, MCRObjectID)}
* @throws MCRPersistenceException
* if persistence problem occurs
* @throws MCRActiveLinkException
* object couldn't be deleted because its linked somewhere
* @throws MCRAccessException
* if delete permission is missing
*/
private static void delete(final MCRObject mcrObject, BiConsumer<MCRObject, MCRObjectID> parentOperation)
throws MCRPersistenceException, MCRActiveLinkException, MCRAccessException {
MCRObjectID id = mcrObject.getId();
if (id == null) {
throw new MCRPersistenceException("The MCRObjectID is null.");
}
if (!MCRAccessManager.checkPermission(id, PERMISSION_DELETE)) {
throw MCRAccessException.missingPermission("Delete object", mcrObject.getId().toString(),
PERMISSION_DELETE);
}
// check for active links
final Collection<String> sources = MCRLinkTableManager.instance().getSourceOf(mcrObject.mcrId,
MCRLinkTableManager.ENTRY_TYPE_REFERENCE);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sources size:{}", sources.size());
}
if (sources.size() > 0) {
final MCRActiveLinkException activeLinks = new MCRActiveLinkException("Error while deleting object " + id
+ ". This object is still referenced by other objects and "
+ "can not be removed until all links are released.");
for (final String curSource : sources) {
activeLinks.addLink(curSource, id.toString());
}
throw activeLinks;
}
// mark for deletion
MCRMarkManager.instance().mark(id, Operation.DELETE);
// remove child from parent
final MCRObjectID parentId = mcrObject.getStructure().getParentID();
if (parentId != null) {
parentOperation.accept(mcrObject, parentId);
}
// remove all children
for (MCRMetaLinkID child : mcrObject.getStructure().getChildren()) {
MCRObjectID childId = child.getXLinkHrefID();
if (!MCRMetadataManager.exists(childId)) {
LOGGER.warn("Unable to remove not existing object {} of parent {}", childId, id);
continue;
}
MCRMetadataManager.deleteMCRObject(childId, (MCRObject o, MCRObjectID p) -> {
// Do nothing with the parent, because its removed anyway.
});
}
// remove all derivates
for (MCRMetaLinkID derivate : mcrObject.getStructure().getDerivates()) {
MCRObjectID derivateId = derivate.getXLinkHrefID();
if (!MCRMetadataManager.exists(derivateId)) {
LOGGER.warn("Unable to remove not existing derivate {} of object {}", derivateId, id);
continue;
}
MCRMetadataManager.deleteMCRDerivate(derivateId);
}
// handle events
fireEvent(mcrObject, null, MCREvent.EventType.DELETE);
// remove mark
MCRMarkManager.instance().remove(id);
}
/**
* Helper method to remove the <code>mcrObject</code> of the given parent. This does just
* remove the linking between both objects.
*
* @param mcrObject
* the object (child) to remove
* @param
* parentId the parent id
* @throws PersistenceException
* when the child cannot be removed due persistent problems
*/
private static void removeChildObject(final MCRObject mcrObject, final MCRObjectID parentId)
throws PersistenceException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parent ID = {}", parentId);
}
try {
if (MCRXMLMetadataManager.instance().exists(parentId)) {
final MCRObject parent = MCRMetadataManager.retrieveMCRObject(parentId);
parent.getStructure().removeChild(mcrObject.getId());
MCRMetadataManager.fireUpdateEvent(parent);
} else {
LOGGER.warn("Unable to find parent {} of {}", parentId, mcrObject.getId());
}
} catch (Exception exc) {
throw new PersistenceException(
"Error while deleting object. Unable to remove child " + mcrObject.getId() + " from parent " + parentId
+ ".",
exc);
}
}
/**
* Delete the derivate. The order of delete steps is:<br>
* <ul>
* <li>remove link in object metadata</li>
* <li>remove all files from IFS</li>
* <li>remove derivate</li>
* </ul>
*
* @param id
* the object ID
* @exception MCRPersistenceException
* if a persistence problem is occurred
* @throws MCRAccessException if delete permission is missing
*/
public static void deleteMCRDerivate(final MCRObjectID id) throws MCRPersistenceException, MCRAccessException {
final MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(id);
MCRMetadataManager.delete(derivate);
}
/**
* Deletes the object.
*
* @exception MCRPersistenceException
* if a persistence problem is occurred
* @throws MCRActiveLinkException
* if object is referenced by other objects
* @throws MCRAccessException if delete permission is missing
*/
public static void deleteMCRObject(final MCRObjectID id)
throws MCRPersistenceException, MCRActiveLinkException, MCRAccessException {
deleteMCRObject(id, MCRMetadataManager::removeChildObject);
}
/**
* Deletes the mcr object with the given <code>id</code>.
*
* @param id
* the object to be deleted
* @param parentOperation
* function to handle the parent of the object @see {@link #removeChildObject(MCRObject, MCRObjectID)}
* @throws MCRPersistenceException
* if persistence problem occurs
* @throws MCRActiveLinkException
* object couldn't be deleted because its linked somewhere
* @throws MCRAccessException if delete permission is missing
*/
private static void deleteMCRObject(final MCRObjectID id, BiConsumer<MCRObject, MCRObjectID> parentOperation)
throws MCRPersistenceException, MCRActiveLinkException, MCRAccessException {
final MCRObject object = retrieveMCRObject(id);
MCRMetadataManager.delete(object, parentOperation);
}
/**
* Tells if the object or derivate with <code>id</code> exists.
*
* @param id
* the object ID
* @throws MCRPersistenceException
* the xml couldn't be read
*/
public static boolean exists(final MCRObjectID id) throws MCRPersistenceException {
return MCRXMLMetadataManager.instance().exists(id);
}
/**
* Fires {@link MCREvent.EventType#REPAIR} for given derivate.
*
*/
public static void fireRepairEvent(final MCRDerivate mcrDerivate) throws MCRPersistenceException {
// handle events
fireEvent(mcrDerivate, null, MCREvent.EventType.REPAIR);
}
/**
* Fires {@link MCREvent.EventType#REPAIR} for given object.
*
*/
public static void fireRepairEvent(final MCRBase mcrBaseObj) throws MCRPersistenceException {
if (mcrBaseObj instanceof MCRDerivate derivate) {
MCRMetadataManager.fireRepairEvent(derivate);
} else if (mcrBaseObj instanceof MCRObject object) {
MCRMetadataManager.fireRepairEvent(object);
}
}
/**
* Fires {@link MCREvent.EventType#REPAIR} for given object.
*
*/
public static void fireRepairEvent(final MCRObject mcrObject) throws MCRPersistenceException {
// check derivate link
for (MCRMetaLinkID derivate : mcrObject.getStructure().getDerivates()) {
if (!MCRMetadataManager.exists(derivate.getXLinkHrefID())) {
LOGGER.error("Can't find MCRDerivate {}", derivate.getXLinkHrefID());
}
}
// handle events
fireEvent(mcrObject, null, MCREvent.EventType.REPAIR);
}
/**
* Fires {@link MCREvent.EventType#UPDATE} for given object. If {@link MCRObject#isImportMode()} modifydate
* will not be updated.
*
* @param mcrObject
* mycore object which is updated
*/
public static void fireUpdateEvent(final MCRObject mcrObject) throws MCRPersistenceException {
if (!mcrObject.isImportMode() || mcrObject.getService().getDate("modifydate") == null) {
mcrObject.getService().setDate("modifydate");
}
// remove ACL if it is set from data source
mcrObject.getService().getRules().clear();
// handle events
fireEvent(mcrObject, retrieveMCRObject(mcrObject.getId()), MCREvent.EventType.UPDATE);
}
/**
* Retrieves instance of {@link MCRDerivate} with the given {@link MCRObjectID}
*
* @param id
* the derivate ID
* @exception MCRPersistenceException
* if a persistence problem is occurred
*/
public static MCRDerivate retrieveMCRDerivate(final MCRObjectID id) throws MCRPersistenceException {
try {
Document xml = MCRXMLMetadataManager.instance().retrieveXML(id);
if (xml == null) {
throw new MCRPersistenceException("Could not retrieve xml of derivate: " + id);
}
return new MCRDerivate(xml);
} catch (IOException | JDOMException e) {
throw new MCRPersistenceException("Could not retrieve xml of derivate: " + id, e);
}
}
/**
* Retrieves an instance of {@link MCRObject} with the given {@link MCRObjectID}
*
* @param id
* the object ID
* @exception MCRPersistenceException
* if a persistence problem is occurred
*/
public static MCRObject retrieveMCRObject(final MCRObjectID id) throws MCRPersistenceException {
try {
Document xml = MCRXMLMetadataManager.instance().retrieveXML(id);
if (xml == null) {
throw new MCRPersistenceException("Could not retrieve xml of object: " + id);
}
return new MCRObject(xml);
} catch (IOException | JDOMException e) {
throw new MCRPersistenceException("Could not retrieve xml of object: " + id, e);
}
}
/**
* Retrieves an instance of {@link MCRObject} or {@link MCRDerivate} depending on {@link MCRObjectID#getTypeId()}
*
* @param id
* derivate or object id
* @exception MCRPersistenceException
* if a persistence problem is occurred
*/
public static MCRBase retrieve(final MCRObjectID id) throws MCRPersistenceException {
if (id.getTypeId().equals("derivate")) {
return retrieveMCRDerivate(id);
}
return retrieveMCRObject(id);
}
/**
* Updates the <code>MCRObject</code> or <code>MCRDerivate</code>.
*
* @param base the object to update
*
* @throws MCRPersistenceException
* if a persistence problem is occurred
* @throws MCRAccessException
* if write permission is missing or see {@link #create(MCRObject)}
*/
public static void update(final MCRBase base)
throws MCRPersistenceException, MCRAccessException {
if (base instanceof MCRObject object) {
MCRMetadataManager.update(object);
} else if (base instanceof MCRDerivate derivate) {
MCRMetadataManager.update(derivate);
} else {
throw new IllegalArgumentException("Type is unsupported " + base.getId());
}
}
/**
* Updates the derivate or creates it if it does not exist yet.
*
* @throws MCRPersistenceException
* if a persistence problem is occurred
* @throws MCRAccessException
* if write permission to object or derivate is missing
*/
public static void update(final MCRDerivate mcrDerivate)
throws MCRPersistenceException, MCRAccessException {
MCRObjectID derivateId = mcrDerivate.getId();
// check deletion mark
if (MCRMarkManager.instance().isMarkedForDeletion(derivateId)) {
return;
}
if (!MCRMetadataManager.exists(derivateId)) {
MCRMetadataManager.create(mcrDerivate);
return;
}
if (!MCRAccessManager.checkDerivateMetadataPermission(derivateId, PERMISSION_WRITE)) {
throw MCRAccessException.missingPermission("Update derivate", derivateId.toString(), PERMISSION_WRITE);
}
Path fileSourceDirectory = null;
MCRMetaIFS internals = mcrDerivate.getDerivate().getInternals();
if (internals != null && internals.getSourcePath() != null) {
fileSourceDirectory = Paths.get(internals.getSourcePath());
if (!Files.exists(fileSourceDirectory)) {
LOGGER.warn("{}: the directory {} was not found.", derivateId, fileSourceDirectory);
fileSourceDirectory = null;
}
//MCR-2645
internals.setSourcePath(null);
}
// get the old Item
MCRDerivate old = MCRMetadataManager.retrieveMCRDerivate(derivateId);
// remove the old link to metadata
MCRMetaLinkID oldLink = old.getDerivate().getMetaLink();
MCRMetaLinkID newLink = mcrDerivate.getDerivate().getMetaLink();
MCRObjectID oldMetadataObjectID = oldLink.getXLinkHrefID();
MCRObjectID newMetadataObjectID = newLink.getXLinkHrefID();
if (!oldMetadataObjectID.equals(newLink.getXLinkHrefID())) {
try {
MCRMetadataManager.removeDerivateFromObject(oldMetadataObjectID, derivateId);
} catch (final MCRException e) {
LOGGER.warn(e.getMessage(), e);
}
}
// update the derivate
mcrDerivate.getService().setDate("createdate", old.getService().getDate("createdate"));
if (!mcrDerivate.getService().isFlagTypeSet(MCRObjectService.FLAG_TYPE_CREATEDBY)) {
for (String flagCreatedBy : old.getService().getFlags(MCRObjectService.FLAG_TYPE_CREATEDBY)) {
mcrDerivate.getService().addFlag(MCRObjectService.FLAG_TYPE_CREATEDBY, flagCreatedBy);
}
}
MCRMetadataManager.updateMCRDerivateXML(mcrDerivate);
// update to IFS
if (fileSourceDirectory != null) {
MCRPath targetPath = MCRPath.getPath(derivateId.toString(), "/");
try {
Files.walkFileTree(fileSourceDirectory, new MCRTreeCopier(fileSourceDirectory, targetPath));
} catch (Exception exc) {
throw new MCRPersistenceException(
"Unable to update IFS. Copy failed from " + fileSourceDirectory.toAbsolutePath()
+ " to target " + targetPath.toAbsolutePath(),
exc);
}
}
// add the link to metadata
final MCRMetaEnrichedLinkID derivateLink = MCRMetaEnrichedLinkIDFactory.getInstance()
.getDerivateLink(mcrDerivate);
MCRMetadataManager.addOrUpdateDerivateToObject(newMetadataObjectID, derivateLink, mcrDerivate.isImportMode());
}
/**
* Updates the object or creates it if it does not exist yet.
*
* @throws MCRPersistenceException
* if a persistence problem is occurred
* @throws MCRAccessException
* if write permission is missing or see {@link #create(MCRObject)}
*/
public static void update(final MCRObject mcrObject)
throws MCRPersistenceException, MCRAccessException {
MCRObjectID id = mcrObject.getId();
// check deletion mark
if (MCRMarkManager.instance().isMarkedForDeletion(id)) {
return;
}
if (!MCRMetadataManager.exists(id)) {
MCRMetadataManager.create(mcrObject);
return;
}
if (!MCRAccessManager.checkPermission(id, PERMISSION_WRITE)) {
throw MCRAccessException.missingPermission("Update object.", id.toString(), PERMISSION_WRITE);
}
MCRObject old = MCRMetadataManager.retrieveMCRObject(id);
Date diskModifyDate = old.getService().getDate(MCRObjectService.DATE_TYPE_MODIFYDATE);
Date updateModifyDate = mcrObject.getService().getDate(MCRObjectService.DATE_TYPE_MODIFYDATE);
if (!mcrObject.isImportMode() && diskModifyDate != null && updateModifyDate != null
&& updateModifyDate.before(diskModifyDate)) {
throw new MCRPersistenceException("The object " + mcrObject.getId() + " was modified(" + diskModifyDate
+ ") during the time it was opened in the editor.");
}
// save the order of derivates and clean the structure
final List<String> childOrder = mcrObject.getStructure()
.getChildren()
.stream()
.map(MCRMetaLinkID::getXLinkHref)
.collect(Collectors.toList());
mcrObject.getStructure().clearChildren();
final List<MCRMetaEnrichedLinkID> derivateLinks = mcrObject.getStructure().getDerivates();
derivateLinks.clear();
old.getStructure().getDerivates()
.forEach(mcrObject.getStructure()::addDerivate);
// set the parent from the original and this update
MCRObjectID oldParentID = old.getStructure().getParentID();
MCRObjectID newParentID = mcrObject.getStructure().getParentID();
if (oldParentID != null && exists(oldParentID) && (!oldParentID.equals(newParentID))) {
// remove child from the old parent
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parent ID = {}", oldParentID);
}
final MCRObject parent = MCRMetadataManager.retrieveMCRObject(oldParentID);
parent.getStructure().removeChild(id);
MCRMetadataManager.fireUpdateEvent(parent);
}
// set the children from the original -> but with new order
List<MCRMetaLinkID> children = old.getStructure().getChildren();
children.sort((link1, link2) -> {
int i1 = childOrder.indexOf(link1.getXLinkHref());
int i2 = childOrder.indexOf(link2.getXLinkHref());
return Integer.compare(i1, i2);
});
mcrObject.getStructure().getChildren().addAll(children);
// import all herited matadata from the parent
receiveMetadata(mcrObject);
// if not imported via cli, createdate remains unchanged
if (!mcrObject.isImportMode() || mcrObject.getService().getDate("createdate") == null) {
mcrObject.getService().setDate("createdate", old.getService().getDate("createdate"));
}
if (!mcrObject.isImportMode() && !mcrObject.getService().isFlagTypeSet(MCRObjectService.FLAG_TYPE_CREATEDBY)) {
for (String flagCreatedBy : old.getService().getFlags(MCRObjectService.FLAG_TYPE_CREATEDBY)) {
mcrObject.getService().addFlag(MCRObjectService.FLAG_TYPE_CREATEDBY, flagCreatedBy);
}
}
// update this dataset
MCRMetadataManager.fireUpdateEvent(mcrObject);
// check if the parent was new set and set them
if (newParentID != null && !newParentID.equals(oldParentID)) {
MCRObject newParent = retrieveMCRObject(newParentID);
newParent.getStructure().addChild(new MCRMetaLinkID("child", id, null, mcrObject.getLabel()));
MCRMetadataManager.fireUpdateEvent(newParent);
}
// update all children
if (shareableMetadataChanged(mcrObject, old)) {
MCRMetadataShareAgent metadataShareAgent = MCRMetadataShareAgentFactory.getAgent(id);
metadataShareAgent.distributeMetadata(mcrObject);
}
}
/**
* This method is used to repair the shared metadata of an object.
* It should be only called if something programmatically changed in the shared metadata handling, like a bugfix
* or migration.
* @param mcrObject the object to repair
* @throws MCRAccessException
*/
public static void repairSharedMetadata(final MCRObject mcrObject)
throws MCRAccessException {
MCRObjectID id = mcrObject.getId();
receiveMetadata(mcrObject);
MCRMetadataManager.fireUpdateEvent(mcrObject);
MCRMetadataShareAgent metadataShareAgent = MCRMetadataShareAgentFactory.getAgent(id);
metadataShareAgent.distributeMetadata(mcrObject);
}
private static boolean shareableMetadataChanged(final MCRObject mcrObject, MCRObject old) {
MCRMetadataShareAgent metadataShareAgent = MCRMetadataShareAgentFactory.getAgent(mcrObject.getId());
return metadataShareAgent.shareableMetadataChanged(old, mcrObject);
}
private static void receiveMetadata(final MCRObject recipient) {
MCRMetadataShareAgent metadataShareAgent = MCRMetadataShareAgentFactory.getAgent(recipient.getId());
metadataShareAgent.receiveMetadata(recipient);
}
/**
* Updates only the XML part of the derivate.
*
* @exception MCRPersistenceException
* if a persistence problem is occurred
*/
private static void updateMCRDerivateXML(final MCRDerivate mcrDerivate) throws MCRPersistenceException {
if (!mcrDerivate.isImportMode() || mcrDerivate.getService().getDate("modifydate") == null) {
mcrDerivate.getService().setDate("modifydate");
}
fireEvent(mcrDerivate, retrieveMCRDerivate(mcrDerivate.getId()), MCREvent.EventType.UPDATE);
}
/**
* Adds or updates a derivate MCRMetaLinkID to the structure part and updates the object with the ID in the data
* store.
*
* @param id
* the object ID
* @param link
* a link to a derivate as MCRMetaLinkID
* @return True if the link is added or updated, false if nothing changed.
* @throws MCRPersistenceException
* if a persistence problem is occurred
* @deprecated in 2023.06
*/
@Deprecated
public static boolean addOrUpdateDerivateToObject(final MCRObjectID id, final MCRMetaEnrichedLinkID link) {
return addOrUpdateDerivateToObject(id, link, false);
}
/**
* Adds or updates a derivate MCRMetaLinkID to the structure part and updates the object with the ID in the data
* store.
*
* @param id
* the object ID
* @param link
* a link to a derivate as MCRMetaLinkID
* @return True if the link is added or updated, false if nothing changed.
* @throws MCRPersistenceException
* if a persistence problem is occurred
*/
public static boolean addOrUpdateDerivateToObject(final MCRObjectID id, final MCRMetaEnrichedLinkID link,
boolean isImportMode)
throws MCRPersistenceException {
final MCRObject object = MCRMetadataManager.retrieveMCRObject(id);
if (!object.getStructure().addOrUpdateDerivate(link)) {
return false;
}
if (!isImportMode && !object.isImportMode()) {
object.getService().setDate("modifydate");
}
MCRMetadataManager.fireUpdateEvent(object);
return true;
}
public static boolean removeDerivateFromObject(final MCRObjectID objectID, final MCRObjectID derivateID)
throws MCRPersistenceException {
final MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
if (object.getStructure().removeDerivate(derivateID)) {
object.getService().setDate("modifydate");
MCRMetadataManager.fireUpdateEvent(object);
return true;
}
return false;
}
private static void restore(final MCRDerivate mcrDerivate, final MCRObjectID mcrObjectId, final byte[] backup) {
try {
final MCRObject obj = new MCRObject(backup, false);
// If an event handler exception occurred, its crucial to restore the object first
// before updating it again. Otherwise the exception could be thrown again and
// the object will be in an invalid state (the not existing derivate will be
// linked with the object).
MCRXMLMetadataManager.instance().update(mcrObjectId, obj.createXML(), new Date());
// update and call event handlers
MCRMetadataManager.update(obj);
} catch (final Exception e1) {
LOGGER.warn("Error while restoring {}", mcrObjectId, e1);
} finally {
// remove derivate
fireEvent(mcrDerivate, null, MCREvent.EventType.DELETE);
}
}
private static void fireEvent(MCRBase base, MCRBase oldBase, MCREvent.EventType eventType) {
boolean objectEvent = base instanceof MCRObject;
MCREvent.ObjectType type = objectEvent ? MCREvent.ObjectType.OBJECT : MCREvent.ObjectType.DERIVATE;
final MCREvent evt = new MCREvent(type, eventType);
if (objectEvent) {
evt.put(MCREvent.OBJECT_KEY, base);
} else {
evt.put(MCREvent.DERIVATE_KEY, base);
}
Optional.ofNullable(oldBase)
.ifPresent(b -> evt.put(objectEvent ? MCREvent.OBJECT_OLD_KEY : MCREvent.DERIVATE_OLD_KEY, b));
if (MCREvent.EventType.DELETE == eventType) {
MCREventManager.instance().handleEvent(evt, MCREventManager.BACKWARD);
} else {
MCREventManager.instance().handleEvent(evt);
}
}
}
| 44,578 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaInstitutionName.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaInstitutionName.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.Objects;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import com.google.gson.JsonObject;
/**
* This class implements all methods for handling with the
* MCRMetaInstitutionName part of a metadata object. The MCRMetaInstitutionName
* class represents a name of an institution or corporation.
*
* @author J. Kupferschmidt
*/
public final class MCRMetaInstitutionName extends MCRMetaDefault {
// data
private String fullname;
private String nickname;
private String property;
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. All other elemnts are set to
* an empty string.
*/
public MCRMetaInstitutionName() {
super();
fullname = "";
nickname = "";
property = "";
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>lang</em> is
* null, empty or false <b>en </b> was set. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was throwed. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The fullname, nickname and property element
* was set to the value of <em>set_...</em>, if they are null,
* an empty string was set to this element.
* @param subtag the name of the subtag
* @param lang the default language
* @param type the optional type string
* @param inherted a value >= 0
* @param fullname the full name
* @param nickname the nickname
* @param property the property title
*
* @exception MCRException if the parameter values are invalid
*/
public MCRMetaInstitutionName(String subtag, String lang, String type, int inherted,
String fullname, String nickname, String property) throws MCRException {
super(subtag, lang, type, inherted);
this.fullname = "";
this.nickname = "";
this.property = "";
set(fullname, nickname, property);
}
/**
* This methode set all name componets.
*
* @param fullname
* the full name
* @param nickname
* the nickname
* @param property
* the property title
*/
public void set(String fullname, String nickname, String property) {
if (fullname == null || nickname == null || property == null) {
throw new MCRException("One parameter is null.");
}
this.fullname = fullname.trim();
this.nickname = nickname.trim();
this.property = property.trim();
}
/**
* This method get the name text element.
*
* @return the fullname
*/
public String getFullName() {
return fullname;
}
/**
* This method get the nickname text element.
*
* @return the nickname
*/
public String getNickname() {
return nickname;
}
/**
* This method get the property text element.
*
* @return the property
*/
public String getProperty() {
return property;
}
/**
* This method reads the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant DOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
fullname = element.getChildTextTrim("fullname");
if (fullname == null) {
fullname = "";
}
nickname = element.getChildTextTrim("nickname");
if (nickname == null) {
nickname = "";
}
property = element.getChildTextTrim("property");
if (property == null) {
property = "";
}
}
/**
* This method creates a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaInstitutionName definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaInstitutionName part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
elm.addContent(new Element("fullname").addContent(fullname));
nickname = nickname.trim();
if (nickname.length() != 0) {
elm.addContent(new Element("nickname").addContent(nickname));
}
property = property.trim();
if (property.length() != 0) {
elm.addContent(new Element("property").addContent(property));
}
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* fullname: "library of congress",
* nickname: "LOC",
* property: "USA"
* }
* </pre>
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
obj.addProperty("fullname", fullname);
if (nickname != null) {
obj.addProperty("nickname", nickname);
}
if (property != null) {
obj.addProperty("property", property);
}
return obj;
}
/**
* Validates this MCRMetaInstitutionName. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the trimmed fullname is null or empty</li>
* </ul>
*
* @throws MCRException the MCRMetaInstitutionName is invalid
*/
public void validate() throws MCRException {
super.validate();
fullname = MCRUtils.filterTrimmedNotEmpty(fullname)
.orElseThrow(() -> new MCRException(getSubTag() + ": fullname is null or empty"));
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaInstitutionName clone() {
MCRMetaInstitutionName clone = (MCRMetaInstitutionName) super.clone();
clone.fullname = this.fullname;
clone.nickname = this.nickname;
clone.property = this.property;
return clone;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaInstitutionName other = (MCRMetaInstitutionName) obj;
return Objects.equals(fullname, other.fullname) && Objects.equals(nickname, other.nickname)
&& Objects.equals(property, other.property);
}
}
| 7,720 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaPersonName.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaPersonName.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.Objects;
import java.util.function.BiConsumer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
/**
* This class implements all methods for handling a name with the
* MCRMetaPersonName datamodel. The MCRMetaPersonName class represents a natural
* or legal person specified by a list of names parts.
*
* @author J. Vogler
* @author J. Kupferschmidt
*/
public final class MCRMetaPersonName extends MCRMetaDefault {
private String firstname;
private String callname;
private String surname;
private String fullname;
private String academic;
private String peerage;
private String numeration;
private String title;
private String prefix;
private String affix;
private static final Logger LOGGER = LogManager.getLogger();
/**
* This is the constructor. <br>
* The language element was set to <b>application default language</b>. All
* other elements will be set to an empty string.
*/
public MCRMetaPersonName() {
super();
lang = DEFAULT_LANGUAGE;
firstname = "";
callname = "";
surname = "";
fullname = "";
academic = "";
peerage = "";
numeration = "";
title = "";
prefix = "";
affix = "";
}
/**
* This is the constructor. <br>
* The method set all common fields of all MCRMetaXXX datamodel types. It
* set the language to the <b>application default language</b>. The type
* attribute will be set to an empty String.
*
* @param subtag
* the name of the subtag
* @param inherited
* a value >= 0
*
* @exception MCRException
* if the parameter values are invalid
*/
public MCRMetaPersonName(String subtag, int inherited) throws MCRException {
super(subtag, DEFAULT_LANGUAGE, "", inherited);
type = "";
firstname = "";
callname = "";
surname = "";
fullname = "";
academic = "";
peerage = "";
numeration = "";
title = "";
prefix = "";
affix = "";
}
/**
* This method get the first name text element.
*
* @return the first name
*/
public String getFirstName() {
if(firstname != null && !firstname.isEmpty()) {
return firstname;
}
return callname;
}
/**
* This method set the first name text element.
*/
public void setFirstName(String firstname) {
this.firstname = firstname != null ? firstname.trim() : "";
}
/**
* This method get the call name text element.
*
* @return the call name
*/
public String getCallName() {
if(callname != null && !callname.isEmpty()) {
return callname;
}
return firstname;
}
/**
* This method set the call name text element.
*/
public void setCallName(String callName) {
this.callname = callName != null ? callName.trim() : "";
}
/**
* This method get the surname text element.
*
* @return the surname
*/
public String getSurName() {
return surname;
}
/**
* This method set the surname text element.
*/
public void setSurName(String surname) {
this.surname = surname != null ? surname.trim() : "";
}
/**
* This method get the full name text element.
*
* @return the full name
*/
public String getFullName() {
if(fullname != null && !fullname.isEmpty()) {
return fullname;
}
String sb = getAcademic() + " " + getPeerage() + " " + getFirstName() + " " + getPrefix() + " " + getSurName();
return sb.trim();
}
/**
* This method set the full name text element.
*/
public void setFullName(String fullName) {
this.fullname = fullName != null ? fullName.trim() : "";
}
/**
* This method get the academic text element.
*
* @return the academic
*/
public String getAcademic() {
return academic;
}
/**
* This method set the academic text element.
*/
public void setAcademic(String academic) {
this.academic = academic != null ? academic.trim() : "";
}
/**
* This method get the peerage text element.
*
* @return the peerage
*/
public String getPeerage() {
return peerage;
}
/**
* This method set the peerage text element.
*/
public void setPeerage(String peerage) {
this.peerage = peerage != null ? peerage.trim() : "";
}
/**
* This method get the numeration text element.
*
* @return the numeration
*/
public String getNumeration() {
return numeration;
}
/**
* This method set the numeration text element.
*/
public void setNumeration(String numeration) {
this.numeration = numeration != null ? numeration.trim() : "";
}
/**
* This method get the title text element.
*
* @return the title
*/
public String getTitle() {
return title;
}
/**
* This method set the title text element.
*/
public void setTitle(String title) {
this.title = title != null ? title.trim() : "";
}
/**
* This method get the prefix text element.
*
* @return the prefix
*/
public String getPrefix() {
return prefix;
}
/**
* This method set the prefix text element.
*/
public void setPrefix(String prefix) {
this.prefix = prefix != null ? prefix.trim() : "";
}
/**
* This method get the affix text element.
*
* @return the affix
*/
public String getAffix() {
return affix;
}
/**
* This method set the affix text element.
*/
public void setAffix(String affix) {
this.affix = affix != null ? affix.trim() : "";
}
/**
* This method reads the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
setFirstName(element.getChildTextTrim("firstname"));
setCallName(element.getChildTextTrim("callname"));
setSurName(element.getChildTextTrim("surname"));
setFullName(element.getChildTextTrim("fullname"));
setAcademic(element.getChildTextTrim("academic"));
setPeerage(element.getChildTextTrim("peerage"));
setNumeration(element.getChildTextTrim("numeration"));
setTitle(element.getChildTextTrim("title"));
setPrefix(element.getChildTextTrim("prefix"));
setAffix(element.getChildTextTrim("affix"));
}
/**
* This method creates a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaPersonName definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaPersonName part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
BiConsumer<String, String> addContent = (name, value) -> MCRUtils.filterTrimmedNotEmpty(value)
.ifPresent(trimmedValue -> elm.addContent(new Element(name).addContent(trimmedValue)));
addContent.accept("firstname", firstname);
addContent.accept("callname", callname);
addContent.accept("fullname", fullname);
addContent.accept("surname", surname);
addContent.accept("academic", academic);
addContent.accept("peerage", peerage);
addContent.accept("numeration", numeration);
addContent.accept("title", title);
addContent.accept("prefix", prefix);
addContent.accept("affix", affix);
return elm;
}
/**
* Validates this MCRMetaPersonName. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>getFullName() returns an empty string</li>
* </ul>
*
* @throws MCRException the MCRMetaPersonName is invalid
*/
public void validate() throws MCRException {
super.validate();
if (getFullName().isEmpty()) {
throw new MCRException(getSubTag() + ": full name is empty");
}
}
/**
* Clone of this instance. You will get a (deep) clone of this element.
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaPersonName clone() {
MCRMetaPersonName clone = (MCRMetaPersonName) super.clone();
clone.firstname = this.firstname;
clone.callname = this.callname;
clone.surname = this.surname;
clone.fullname = this.fullname;
clone.academic = this.academic;
clone.peerage = this.peerage;
clone.numeration = this.numeration;
clone.title = this.title;
clone.prefix = this.prefix;
clone.affix = this.affix;
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("First name = {}", firstname);
LOGGER.debug("Call name = {}", callname);
LOGGER.debug("Surname = {}", surname);
LOGGER.debug("Full name = {}", fullname);
LOGGER.debug("Academic = {}", academic);
LOGGER.debug("Peerage = {}", peerage);
LOGGER.debug("Numeration = {}", numeration);
LOGGER.debug("Title = {}", title);
LOGGER.debug("Prefix = {}", prefix);
LOGGER.debug("Affix = {}", affix);
LOGGER.debug("");
}
}
/**
* This method compares this instance with a MCRMetaPersonName object
*/
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaPersonName other = (MCRMetaPersonName) obj;
return Objects.equals(this.firstname, other.firstname) && Objects.equals(this.callname, other.callname) &&
Objects.equals(this.surname, other.surname) && Objects.equals(this.fullname, other.fullname) &&
Objects.equals(this.academic, other.academic) && Objects.equals(this.peerage, other.peerage) &&
Objects.equals(this.numeration, other.numeration) && Objects.equals(this.title, other.title) &&
Objects.equals(this.prefix, other.prefix) && Objects.equals(this.affix, other.affix);
}
}
| 11,948 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDPool.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRObjectIDPool.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import org.mycore.common.MCRException;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
/**
* holds weak references to generated {@link MCRObjectID} instances.
* @author Thomas Scheffler (yagee)
*
*/
class MCRObjectIDPool {
private static LoadingCache<String, MCRObjectID> objectIDCache = CacheBuilder
.newBuilder()
.weakValues()
.build(new CacheLoader<>() {
@Override
public MCRObjectID load(String id) {
return new MCRObjectID(id);
}
});
static MCRObjectID getMCRObjectID(String id) {
try {
return objectIDCache.getUnchecked(id);
} catch (UncheckedExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof MCRException mcre) {
throw mcre;
}
throw e;
}
}
static long getSize() {
objectIDCache.cleanUp();
//objectIDCache.size() may return more as actually present;
return objectIDCache.asMap()
.entrySet()
.stream()
.filter(e -> e.getKey() != null)
.filter(e -> e.getValue() != null)
.count();
}
static MCRObjectID getIfPresent(String id) {
return objectIDCache.getIfPresent(id);
}
}
| 2,239 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMetaLangText.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/datamodel/metadata/MCRMetaLangText.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.datamodel.metadata;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUtils;
import com.google.gson.JsonObject;
/**
* This class implements all method for handling with the MCRMetaLangText part
* of a metadata object. The MCRMetaLangText class present a single item, which
* has triples of a text and his corresponding language and optional a type.
*
* @author Jens Kupferschmidt
*/
public class MCRMetaLangText extends MCRMetaDefault {
protected String text;
protected String form;
private static final Logger LOGGER = LogManager.getLogger();
/**
* This is the constructor. <br>
* The language element was set to <b>en </b>. All other elements was set to
* an empty string. The <em>form</em> Attribute is set to 'plain'.
*/
public MCRMetaLangText() {
super();
text = "";
form = "plain";
}
/**
* This is the constructor. <br>
* The language element was set. If the value of <em>lang</em> is
* null, empty or false <b>en </b> was set. The subtag element was set to
* the value of <em>subtag</em>. If the value of <em>subtag</em>
* is null or empty an exception was thrown. The type element was set to
* the value of <em>type</em>, if it is null, an empty string was set
* to the type element. The text element was set to the value of
* <em>text</em>, if it is null, an empty string was set
* to the text element.
* @param subtag the name of the subtag
* @param lang the default language
* @param type the optional type string
* @param inherted a value >= 0
* @param form the format string, if it is empty 'plain' is set.
* @param text the text string
*
* @exception MCRException if the subtag value is null or empty
*/
public MCRMetaLangText(String subtag, String lang, String type, int inherted, String form, String text)
throws MCRException {
super(subtag, lang, type, inherted);
this.text = "";
if (text != null) {
this.text = text.trim();
}
this.form = "plain";
if (form != null) {
this.form = form.trim();
}
}
/**
* This method set the language, type and text.
*
* @param lang
* the new language string, if this is null or empty, nothing is
* to do
* @param type
* the optional type string
* @param text
* the new text string
*/
public final void set(String lang, String type, String form, String text) {
setLang(lang);
setType(type);
if (text != null) {
this.text = text.trim();
}
this.form = "plain";
if (form != null) {
this.form = form.trim();
}
}
/**
* This method set the text.
*
* @param text
* the new text string
*/
public final void setText(String text) {
if (text != null) {
this.text = text.trim();
}
}
/**
* This method set the form attribute.
*
* @param form
* the new form string
*/
public final void setForm(String form) {
if (form != null) {
text = form.trim();
}
}
/**
* This method get the text element.
*
* @return the text
*/
public final String getText() {
return text;
}
/**
* This method get the form attribute.
*
* @return the form attribute
*/
public final String getForm() {
return form;
}
/**
* This method read the XML input stream part from a DOM part for the
* metadata of the document.
*
* @param element
* a relevant JDOM element for the metadata
*/
@Override
public void setFromDOM(Element element) {
super.setFromDOM(element);
String tempText = element.getText();
if (tempText == null) {
tempText = "";
}
text = tempText.trim();
String tempForm = element.getAttributeValue("form");
if (tempForm == null) {
tempForm = "plain";
}
form = tempForm.trim();
}
/**
* This method create a XML stream for all data in this class, defined by
* the MyCoRe XML MCRMetaLangText definition for the given subtag.
*
* @exception MCRException
* if the content of this class is not valid
* @return a JDOM Element with the XML MCRMetaLangText part
*/
@Override
public Element createXML() throws MCRException {
Element elm = super.createXML();
MCRUtils.filterTrimmedNotEmpty(form)
.ifPresent(s -> elm.setAttribute("form", s));
elm.addContent(text);
return elm;
}
/**
* Creates the JSON representation. Extends the {@link MCRMetaDefault#createJSON()} method
* with the following data.
*
* <pre>
* {
* text: "Hallo Welt",
* form: "plain"
* }
* </pre>
*
*/
@Override
public JsonObject createJSON() {
JsonObject obj = super.createJSON();
if (getForm() != null) {
obj.addProperty("form", getForm());
}
obj.addProperty("text", getText());
return obj;
}
/**
* Validates this MCRMetaLangText. This method throws an exception if:
* <ul>
* <li>the subtag is not null or empty</li>
* <li>the lang value was supported</li>
* <li>the inherited value is lower than zero</li>
* <li>the trimmed text is null or empty</li>
* </ul>
*
* @throws MCRException the MCRMetaLangText is invalid
*/
public void validate() throws MCRException {
super.validate();
text = MCRUtils.filterTrimmedNotEmpty(text)
.orElseThrow(() -> new MCRException(getSubTag() + ": text is null or empty"));
form = MCRUtils.filterTrimmedNotEmpty(form)
.orElse("plain");
}
/**
* clone of this instance
*
* you will get a (deep) clone of this element
*
* @see java.lang.Object#clone()
*/
@Override
public MCRMetaLangText clone() {
MCRMetaLangText clone = (MCRMetaLangText) super.clone();
clone.form = this.form;
clone.text = this.text;
return clone;
}
/**
* This method put debug data to the logger (for the debug mode).
*/
@Override
public final void debug() {
if (LOGGER.isDebugEnabled()) {
super.debugDefault();
LOGGER.debug("Format = {}", form);
LOGGER.debug("Text = {}", text);
LOGGER.debug(" ");
}
}
/**
* Check the equivalence between this instance and the given object.
*
* @param obj the MCRMetaLangText object
* @return true if its equal
*/
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final MCRMetaLangText other = (MCRMetaLangText) obj;
return Objects.equals(this.text, other.text) && Objects.equals(this.form, other.form);
}
}
| 8,209 | 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.