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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRURNJsonBundle.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRURNJsonBundle.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.urn.rest;
import java.net.URL;
import org.mycore.pi.MCRPIRegistrationInfo;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* Class wraps the urn/url in json as needed by the dnb urn service api.
*
* @see <a href="https://wiki.dnb.de/display/URNSERVDOK/URN-Service+API">URN-Service API</a>
*
* @author shermann
* */
public class MCRURNJsonBundle {
protected enum Format {
register, update
}
private final MCRPIRegistrationInfo urn;
private final URL url;
private MCRURNJsonBundle(MCRPIRegistrationInfo urn, URL url) {
this.urn = urn;
this.url = url;
}
public static MCRURNJsonBundle instance(MCRPIRegistrationInfo urn, URL url) {
return new MCRURNJsonBundle(urn, url);
}
public MCRPIRegistrationInfo getUrn() {
return this.urn;
}
public URL getUrl() {
return this.url;
}
/**
* Returns the proper JSON with respect to the given {@link Format}
*
* @param format one of {@link Format}
*
* @return JSON
* */
public String toJSON(Format format) {
return format.equals(Format.register) ? getRegisterJson() : getUpdateJson();
}
/**
* @see <a href="https://wiki.dnb.de/display/URNSERVDOK/Beispiele%3A+URN-Verwaltung#Beispiele:URN-Verwaltung-AustauschenallereigenenURLsaneinerURN">https://wiki.dnb.de/</a>
* */
private String getUpdateJson() {
JsonArray urls = new JsonArray();
JsonObject url = new JsonObject();
url.addProperty("url", getURLString());
url.addProperty("priority", String.valueOf(1));
urls.add(url);
return urls.toString();
}
/**
* @see <a href="https://wiki.dnb.de/display/URNSERVDOK/Beispiele%3A+URN-Verwaltung#Beispiele:URN-Verwaltung-RegistriereneinerneuenURN">https://wiki.dnb.de/</a>
* */
private String getRegisterJson() {
JsonObject json = new JsonObject();
json.addProperty("urn", getURNString());
JsonArray urls = new JsonArray();
json.add("urls", urls);
JsonObject url = new JsonObject();
url.addProperty("url", getURLString());
url.addProperty("priority", String.valueOf(1));
urls.add(url);
return json.toString();
}
private String getURLString() {
if (getUrl() == null) {
return "url not set";
}
return getUrl().toString();
}
private String getURNString() {
if (getUrn() == null) {
return "urn not set";
}
return getUrn().getIdentifier();
}
}
| 3,362 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREpicurLite.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCREpicurLite.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.urn.rest;
import static org.mycore.common.MCRConstants.EPICURLITE_NAMESPACE;
import static org.mycore.common.MCRConstants.XSI_NAMESPACE;
import java.net.URL;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.pi.MCRPIRegistrationInfo;
/**
* Created by chi on 25.01.17.
*
* @author shermann
* @author Huu Chi Vu
*
* @deprecated Use {@link MCRURNJsonBundle}
*/
@Deprecated
public final class MCREpicurLite {
private final MCRPIRegistrationInfo urn;
private final URL url;
private UsernamePasswordCredentials credentials;
private boolean isFrontpage = false;
private boolean isPrimary = true;
private MCREpicurLite(MCRPIRegistrationInfo urn, URL url) {
this.urn = urn;
this.url = url;
}
public static MCREpicurLite instance(MCRPIRegistrationInfo urn, URL url) {
return new MCREpicurLite(urn, url);
}
/**
* Creates the epicur lite xml.
*/
public Document toXML() {
//TODO support multiple url elements
Element epicurLite = newEpicureElement("epicurlite");
epicurLite.addNamespaceDeclaration(XSI_NAMESPACE);
epicurLite.setAttribute("schemaLocation",
"http://nbn-resolving.org/epicurlite http://nbn-resolving.org/schemas/epicurlite/1.0/epicurlite.xsd",
XSI_NAMESPACE);
Document epicurLiteDoc = new Document(epicurLite);
// authentication information
if (credentials != null) {
Element login = newEpicureElement("login");
Element password = newEpicureElement("password");
login.setText(credentials.getUserName());
password.setText(credentials.getPassword());
epicurLite.addContent(login);
epicurLite.addContent(password);
}
// urn element
Element identifier = newEpicureElement("identifier");
Element value = newEpicureElement("value");
value.setText(urn.getIdentifier());
epicurLite.addContent(identifier.addContent(value));
// resource Element
Element resource = newEpicureElement("resource");
Element urlElem = newEpicureElement("url");
urlElem.setText(url.toString());
Element primary = newEpicureElement("primary");
primary.setText(String.valueOf(isPrimary));
Element frontpage = newEpicureElement("frontpage");
frontpage.setText(String.valueOf(isFrontpage));
resource.addContent(urlElem);
resource.addContent(primary);
resource.addContent(frontpage);
epicurLite.addContent(resource);
return epicurLiteDoc;
}
public String asXMLString() {
return new XMLOutputter(
Format.getPrettyFormat()).outputString(toXML());
}
private Element newEpicureElement(String epicurlite) {
return new Element(epicurlite, EPICURLITE_NAMESPACE);
}
public MCREpicurLite setCredentials(UsernamePasswordCredentials credentials) {
this.credentials = credentials;
return this;
}
public URL getUrl() {
return url;
}
/**
* @param frontpage the frontpage to set
*/
public MCREpicurLite setFrontpage(boolean frontpage) {
isFrontpage = frontpage;
return this;
}
/**
* @param primary the primary to set
*/
public MCREpicurLite setPrimary(boolean primary) {
isPrimary = primary;
return this;
}
@Override
public String toString() {
return urn.getIdentifier() + "|" + url;
}
}
| 4,435 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDerivateURNUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRDerivateURNUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.urn.rest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.xml.MCRXMLFunctions;
import org.mycore.datamodel.ifs.MCRFileNodeServlet;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetaIFS;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectDerivate;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRContentTypes;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.pi.MCRPIRegistrationInfo;
/**
* Created by chi on 07.02.17.
*
* @author Huu Chi Vu
*/
public class MCRDerivateURNUtils {
private static final Logger LOGGER = LogManager.getLogger(MCRDerivateURNUtils.class);
private static final String SUPPORTED_CONTENT_TYPE = MCRConfiguration2
.getString("MCR.PI.URNGranular.SupportedContentTypes").orElse("");
public static URL getURL(MCRPIRegistrationInfo piInfo) {
String derivateID = piInfo.getMycoreID();
if (piInfo.getService().endsWith("-dfg")) {
return getDFGViewerURL(piInfo);
}
try {
// the base urn, links to frontpage (metadata + viewer)
if (piInfo.getAdditional() == null || piInfo.getAdditional().trim().isEmpty()) {
MCRObjectID derID = MCRObjectID.getInstance(derivateID);
final MCRObjectID objectId = MCRMetadataManager.getObjectId(derID, 0, TimeUnit.SECONDS);
if (objectId == null) {
LOGGER.warn("Object for {} could NOT be found", derivateID);
return null;
}
return new URI(MCRFrontendUtil.getBaseURL() + "receive/" + objectId + "?derivate=" + derID).toURL();
} else /* an urn for a certain file, links to iview2 */ {
MCRPath file = MCRPath.getPath(derivateID, piInfo.getAdditional());
if (!Files.exists(file)) {
LOGGER.warn("File {} in object {} could NOT be found", file.getFileName().toString(), derivateID);
return null;
}
if (!isFileSupported(file)) {
LOGGER.info("File is not displayable within iView2. Use {} as url",
MCRFileNodeServlet.class.getSimpleName());
String filePath = "/" + file.getOwner()
+ MCRXMLFunctions.encodeURIPath(file.getOwnerRelativePath());
return new URI(MCRFrontendUtil.getBaseURL() + "servlets/" + MCRFileNodeServlet.class.getSimpleName()
+ filePath).toURL();
}
return new URI(getViewerURL(file)).toURL();
}
} catch (MalformedURLException | MCRPersistenceException | URISyntaxException e) {
LOGGER.error("Malformed URL for URN {}", piInfo.getIdentifier(), e);
}
return null;
}
private static String getViewerURL(MCRPath file) throws URISyntaxException {
return new MessageFormat("{0}rsc/viewer/{1}{2}", Locale.ROOT).format(
new Object[] { MCRFrontendUtil.getBaseURL(), file.getOwner(),
MCRXMLFunctions.encodeURIPath(file.getOwnerRelativePath()) });
}
public static URL getDFGViewerURL(MCRPIRegistrationInfo urn) {
URL url = null;
try {
MCRObjectID derivateId = MCRObjectID.getInstance(urn.getMycoreID());
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateId);
String mainDoc = Optional.ofNullable(derivate.getDerivate())
.map(MCRObjectDerivate::getInternals)
.map(MCRMetaIFS::getMainDoc)
.orElseThrow(() -> new RuntimeException(
"Could not get main doc for " + derivateId));
String spec;
String baseURL = MCRFrontendUtil.getBaseURL();
String id = URLEncoder.encode(derivateId.toString(), StandardCharsets.UTF_8);
if (mainDoc != null && mainDoc.length() > 0) {
String mainDocEnc = URLEncoder.encode(mainDoc, StandardCharsets.UTF_8);
spec = String.format(Locale.ROOT, "%sservlets/MCRDFGLinkServlet?deriv=%s&file=%s", baseURL, id,
mainDocEnc);
} else {
spec = baseURL + "servlets/MCRDFGLinkServlet?deriv="
+ id;
}
LOGGER.debug("Generated URL for urn {} is {}", urn.getIdentifier(), spec);
url = new URI(spec).toURL();
} catch (MalformedURLException | URISyntaxException e) {
LOGGER.error("Could not create dfg viewer url", e);
}
return url;
}
/**
* @param file image file
* @return if content type is in property <code>MCR.PI.URNGranular.SupportedContentTypes</code>
* @see MCRContentTypes#probeContentType(Path)
*/
private static boolean isFileSupported(MCRPath file) {
try {
return SUPPORTED_CONTENT_TYPE.contains(MCRContentTypes.probeContentType(file));
} catch (IOException e) {
e.printStackTrace();
}
return false;
// return true;
}
}
| 6,549 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHttpsClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRHttpsClient.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.urn.rest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
import java.util.function.Supplier;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Convinience class for sending http requests to the DNB urn service api.
*
* Created by chi on 08.05.17.
*
* @author Huu Chi Vu
*/
public class MCRHttpsClient {
final private static Logger LOGGER = LogManager.getLogger(MCRHttpsClient.class);
private static RequestConfig noRedirect() {
return RequestConfig
.copy(RequestConfig.DEFAULT)
.setRedirectsEnabled(false)
.build();
}
public static CloseableHttpClient getHttpsClient() {
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
int timeout = 5;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000)
.setSocketTimeout(timeout * 1000).build();
return clientBuilder.setDefaultRequestConfig(config).setSSLContext(SSLContexts.createSystemDefault()).build();
}
public static CloseableHttpResponse head(String url) {
return MCRHttpsClient.head(url, Optional.empty());
}
public static CloseableHttpResponse head(String url, Optional<UsernamePasswordCredentials> credentials) {
HttpHead httpHead = new HttpHead(url);
try (CloseableHttpClient httpClient = getHttpsClient()) {
return httpClient.execute(httpHead);
} catch (IOException e) {
LOGGER.error("There is a problem or the connection was aborted for URL: {}", url, e);
}
return null;
}
public static CloseableHttpResponse get(String url, Optional<UsernamePasswordCredentials> credentials) {
HttpGet get = new HttpGet(url);
if (credentials.isPresent()) {
setAuthorizationHeader(get, credentials);
}
try (CloseableHttpClient httpsClient = getHttpsClient()) {
return httpsClient.execute(get);
} catch (IOException e) {
LOGGER.error(e);
}
return null;
}
public static CloseableHttpResponse put(String url, String contentType, String data) {
return MCRHttpsClient.put(url, contentType, data, Optional.empty());
}
public static CloseableHttpResponse put(String url, String contentType, String data,
Optional<UsernamePasswordCredentials> credentials) {
return request(HttpPut::new, url, contentType, new StringEntity(data, "UTF-8"), credentials);
}
public static CloseableHttpResponse post(String url, String contentType, String data) {
return MCRHttpsClient.post(url, contentType, data, Optional.empty());
}
public static CloseableHttpResponse post(String url, String contentType, String data,
Optional<UsernamePasswordCredentials> credentials) {
return request(HttpPost::new, url, contentType, new StringEntity(data, "UTF-8"), credentials);
}
public static CloseableHttpResponse patch(String url, String contentType, String data) {
return MCRHttpsClient.patch(url, contentType, data, Optional.empty());
}
public static CloseableHttpResponse patch(String url, String contentType, String data,
Optional<UsernamePasswordCredentials> credentials) {
return request(HttpPatch::new, url, contentType, new StringEntity(data, "UTF-8"), credentials);
}
public static <R extends HttpEntityEnclosingRequestBase> CloseableHttpResponse request(Supplier<R> requestSupp,
String url, String contentType, HttpEntity entity) {
return MCRHttpsClient.request(requestSupp, url, contentType, entity, Optional.empty());
}
/**
* Sets the authorization header to the provided http request object.
*
* Unfortunately the procedure with {@link org.apache.http.client.CredentialsProvider} is not working with the
* DNB urn service api.
* */
private static HttpRequest setAuthorizationHeader(HttpRequest request,
Optional<UsernamePasswordCredentials> credentials) {
String auth = credentials.get().getUserName() + ":" + credentials.get().getPassword();
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
String authHeader = "Basic " + new String(encodedAuth, StandardCharsets.UTF_8);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
return request;
}
public static <R extends HttpEntityEnclosingRequestBase> CloseableHttpResponse request(Supplier<R> requestSupp,
String url, String contentType, HttpEntity entity, Optional<UsernamePasswordCredentials> credentials) {
try (CloseableHttpClient httpClient = getHttpsClient()) {
R request = requestSupp.get();
if (credentials.isPresent()) {
setAuthorizationHeader(request, credentials);
}
request.setURI(new URI(url));
request.setHeader("content-type", contentType);
request.setConfig(noRedirect());
request.setEntity(entity);
return httpClient.execute(request);
} catch (URISyntaxException e) {
LOGGER.error("Wrong format for URL: {}", url, e);
} catch (ClientProtocolException e) {
LOGGER.error("There is a HTTP protocol error for URL: {}", url, e);
} catch (IOException e) {
LOGGER.error("There is a problem or the connection was aborted for URL: {}", url, e);
}
return null;
}
}
| 7,298 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURNGranularRESTService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/urn/rest/MCRURNGranularRESTService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.urn.rest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
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.access.MCRAccessException;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectDerivate;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectService;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.pi.MCRPIManager;
import org.mycore.pi.MCRPIService;
import org.mycore.pi.MCRPIServiceDates;
import org.mycore.pi.backend.MCRPI;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import org.mycore.pi.urn.MCRDNBURN;
import org.mycore.pi.urn.MCRDNBURNParser;
import com.google.gson.Gson;
import jakarta.persistence.EntityTransaction;
/**
* Service for assigning granular URNs to Derivate. You can call it with a Derivate-ID and it will assign a Base-URN for
* the Derivate and granular URNs for every file in the Derivate (except IgnoreFileNames). If you then add a file to
* Derivate you can call with Derivate-ID and additional path of the file. E.g. mir_derivate_00000060 and /image1.jpg
* <p>
* <b>Inscriber is ignored with this {@link MCRPIService}</b>
* </p>
* Configuration Parameter(s): <dl>
* <dt>IgnoreFileNames</dt>
* <dd>Comma seperated list of regex file which should not have a urn assigned. Default: mets\\.xml</dd> </dl>
*/
public class MCRURNGranularRESTService extends MCRPIService<MCRDNBURN> {
private static final Logger LOGGER = LogManager.getLogger();
private final Function<MCRDerivate, Stream<MCRPath>> derivateFileStream;
public MCRURNGranularRESTService() {
this(MCRURNGranularRESTService::defaultDerivateFileStream);
}
public MCRURNGranularRESTService(Function<MCRDerivate, Stream<MCRPath>> derivateFileStreamFunc) {
super(MCRDNBURN.TYPE);
this.derivateFileStream = derivateFileStreamFunc;
}
private static Stream<MCRPath> defaultDerivateFileStream(MCRDerivate derivate) {
MCRObjectID derivateId = derivate.getId();
Path derivRoot = MCRPath.getPath(derivateId.toString(), "/");
try {
return Files.walk(derivRoot)
.map(MCRPath::toMCRPath)
.filter(p -> !Files.isDirectory(p))
.filter(p -> !p.equals(derivRoot));
} catch (IOException e) {
LOGGER.error("I/O error while access the starting file of derivate {}!", derivateId, e);
} catch (SecurityException s) {
LOGGER.error("No access to starting file of derivate {}!", derivateId, s);
}
return Stream.empty();
}
@Override
public MCRDNBURN register(MCRBase obj, String filePath, boolean updateObject)
throws MCRAccessException, MCRPersistentIdentifierException {
this.validateRegistration(obj, filePath);
if (obj instanceof MCRDerivate derivate) {
return registerURN(derivate, filePath);
} else {
throw new MCRPersistentIdentifierException("Object " + obj.getId() + " is not a MCRDerivate!");
}
}
private MCRDNBURN registerURN(MCRDerivate deriv, String filePath) throws MCRPersistentIdentifierException {
MCRObjectID derivID = deriv.getId();
Function<String, Integer> countCreatedPI = s -> MCRPIManager
.getInstance()
.getCreatedIdentifiers(derivID, getType(), getServiceID())
.size();
int seed = Optional.of(filePath)
.filter(p -> !Objects.equals(p, ""))
.map(countCreatedPI)
.map(count -> count + 1)
.orElse(1);
MCRDNBURN derivURN = Optional
.ofNullable(deriv.getDerivate())
.map(MCRObjectDerivate::getURN)
.flatMap(new MCRDNBURNParser()::parse)
.orElseGet(() -> createNewURN(deriv));
String setID = derivID.getNumberAsString();
GranularURNGenerator granularURNGen = new GranularURNGenerator(seed, derivURN, setID);
Function<MCRPath, Supplier<String>> generateURN = p -> granularURNGen.getURNSupplier();
LinkedHashMap<Supplier<String>, MCRPath> urnPathMap = derivateFileStream.apply(deriv)
.filter(notInIgnoreList().and(matchFile(filePath)))
.sorted()
.collect(Collectors.toMap(generateURN, p -> p, (m1, m2) -> m1,
LinkedHashMap::new));
if (!Objects.equals(filePath, "") && urnPathMap.isEmpty()) {
String errMsg = new MessageFormat("File {0} does not exist in {1}.\n", Locale.ROOT)
.format(new Object[] { filePath, derivID.toString() })
+ "Use absolute path of file without owner ID like /abs/path/to/file.\n";
throw new MCRPersistentIdentifierException(errMsg);
}
urnPathMap.forEach(createFileMetadata(deriv).andThen(persistURN(deriv)));
try {
MCRMetadataManager.update(deriv);
} catch (MCRPersistenceException | MCRAccessException e) {
LOGGER.error("Error while updating derivate {}", derivID, e);
}
EntityTransaction transaction = MCREntityManagerProvider
.getCurrentEntityManager()
.getTransaction();
if (!transaction.isActive()) {
transaction.begin();
}
transaction.commit();
return derivURN;
}
public MCRDNBURN createNewURN(MCRDerivate deriv) {
MCRObjectID derivID = deriv.getId();
try {
MCRDNBURN derivURN = getNewIdentifier(deriv, "");
deriv.getDerivate().setURN(derivURN.asString());
persistURNStr(deriv, null).accept(derivURN::asString, "");
if (Boolean.parseBoolean(getProperties().getOrDefault("supportDfgViewerURN", "false"))) {
String suffix = "dfg";
persistURNStr(deriv, null, getServiceID() + "-" + suffix)
.accept(() -> derivURN.withNamespaceSuffix(suffix + "-").asString(), "");
}
return derivURN;
} catch (MCRPersistentIdentifierException e) {
throw new MCRPICreationException("Could not create new URN for " + derivID, e);
}
}
private BiConsumer<Supplier<String>, MCRPath> createFileMetadata(MCRDerivate deriv) {
return (urnSup, path) -> deriv.getDerivate().getOrCreateFileMetadata(path, urnSup.get());
}
private BiConsumer<Supplier<String>, MCRPath> persistURN(MCRDerivate deriv) {
return (urnSup, path) -> persistURNStr(deriv, null).accept(urnSup, path.getOwnerRelativePath());
}
private BiConsumer<Supplier<String>, String> persistURNStr(MCRDerivate deriv, Date registerDate) {
return (urnSup, path) -> persistURNStr(deriv, registerDate, getServiceID()).accept(urnSup, path);
}
private BiConsumer<Supplier<String>, String> persistURNStr(MCRDerivate deriv, Date registerDate, String serviceID) {
return (urnSup, path) -> {
MCRPI mcrpi = new MCRPI(urnSup.get(), getType(), deriv.getId().toString(), path, serviceID,
new MCRPIServiceDates(registerDate, null));
MCREntityManagerProvider.getCurrentEntityManager().persist(mcrpi);
};
}
private Predicate<MCRPath> matchFile(String ownerRelativPath) {
return path -> Optional.of(ownerRelativPath)
.filter(""::equals)
.map(p -> Boolean.TRUE)
.orElseGet(() -> path.getOwnerRelativePath().equals(ownerRelativPath));
}
private Predicate<MCRPath> notInIgnoreList() {
Supplier<? extends RuntimeException> errorInIgnorList = () -> new RuntimeException(
"Error in ignore filename list!");
return path -> getIgnoreFileList()
.stream()
.map(Pattern::compile)
.map(Pattern::asPredicate)
.map(Predicate::negate)
.reduce(Predicate::and)
.orElseThrow(errorInIgnorList)
.test(path.getOwnerRelativePath());
}
private List<String> getIgnoreFileList() {
List<String> ignoreFileNamesList = new ArrayList<>();
String ignoreFileNames = getProperties().get("IgnoreFileNames");
if (ignoreFileNames != null) {
ignoreFileNamesList.addAll(Arrays.asList(ignoreFileNames.split(",")));
} else {
ignoreFileNamesList.add("mets\\.xml"); // default value
}
return ignoreFileNamesList;
}
@Override
protected MCRPIServiceDates registerIdentifier(MCRBase obj, String additional, MCRDNBURN urn) {
// not used in this impl
return new MCRPIServiceDates(null, null);
}
@Override
protected void delete(MCRDNBURN identifier, MCRBase obj, String additional)
throws MCRPersistentIdentifierException {
throw new MCRPersistentIdentifierException("Delete is not supported for " + getType());
}
@Override
protected void update(MCRDNBURN identifier, MCRBase obj, String additional) {
//TODO: improve API, don't override method to do nothing
LOGGER.info("No update in this implementation");
}
@Override
public void updateFlag(MCRObjectID id, String additional, MCRPI mcrpi) {
MCRBase obj = MCRMetadataManager.retrieve(id);
MCRObjectService service = obj.getService();
ArrayList<String> flags = service.getFlags(MCRPIService.PI_FLAG);
Gson gson = getGson();
//just update flag for derivate, where additional is ""
if (Objects.equals(additional, "")) {
Iterator<String> flagsIter = flags.iterator();
while (flagsIter.hasNext()) {
String flagStr = flagsIter.next();
MCRPI currentPi = gson.fromJson(flagStr, MCRPI.class);
if ("".equals(currentPi.getAdditional())
&& currentPi.getIdentifier().equals(mcrpi.getIdentifier())) {
//remove flag for update
flagsIter.remove();
}
}
addFlagToObject(obj, mcrpi);
try {
MCRMetadataManager.update(obj);
} catch (Exception e) {
throw new MCRException("Could not update flags of object " + id, e);
}
}
}
private static class GranularURNGenerator {
private final MCRDNBURN urn;
private final String setID;
private int counter;
private String leadingZeros;
GranularURNGenerator(int seed, MCRDNBURN derivURN, String setID) {
this.counter = seed;
this.urn = derivURN;
this.setID = setID;
}
public Supplier<String> getURNSupplier() {
int currentCount = counter++;
return () -> urn.toGranular(setID, getIndex(currentCount)).asString();
}
public String getIndex(int currentCount) {
return String.format(Locale.getDefault(), leadingZeros(counter), currentCount);
}
private String leadingZeros(int i) {
if (leadingZeros == null) {
leadingZeros = "%0" + numDigits(i) + "d";
}
return leadingZeros;
}
private long numDigits(long n) {
if (n < 10) {
return 1;
}
return 1 + numDigits(n / 10);
}
}
public static class MCRPICreationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public MCRPICreationException(String message, Throwable cause) {
super(message, cause);
}
}
}
| 13,212 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOIResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.util.stream.Stream;
import org.mycore.pi.MCRPIResolver;
import org.mycore.pi.doi.client.datacite.MCRDataciteRest;
import org.mycore.pi.doi.client.datacite.MCRDataciteRestResponse;
import org.mycore.pi.doi.client.datacite.MCRDataciteRestResponseEntry;
import org.mycore.pi.doi.client.datacite.MCRDataciteRestResponseEntryDataStringValue;
import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException;
public class MCRDOIResolver extends MCRPIResolver<MCRDigitalObjectIdentifier> {
public MCRDOIResolver() {
super("DOI-Resolver");
}
@Override
public Stream<String> resolve(MCRDigitalObjectIdentifier identifier) throws MCRIdentifierUnresolvableException {
MCRDataciteRestResponse restResponse = MCRDataciteRest.get(identifier);
if (restResponse.getResponseCode() == 1) {
return restResponse.getValues()
.stream()
.filter(responseEntry -> responseEntry.getType().equals("URL"))
.map(MCRDataciteRestResponseEntry::getData)
.filter(responseEntryData -> responseEntryData.getFormat().equals("string"))
.map(responseEntryData -> ((MCRDataciteRestResponseEntryDataStringValue) responseEntryData
.getValue()).getValue());
}
return Stream.empty();
}
}
| 2,091 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStaticDOIGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRStaticDOIGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.util.Optional;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.pi.MCRPIGenerator;
/**
* Just for testing. Provides the doi in the doi property.
*/
public class MCRStaticDOIGenerator extends MCRPIGenerator<MCRDigitalObjectIdentifier> {
public MCRStaticDOIGenerator() {
super();
checkPropertyExists("doi");
}
@Override
public MCRDigitalObjectIdentifier generate(MCRBase mcrBase, String additional) {
final String doi = getProperties().get("doi");
final Optional<MCRDigitalObjectIdentifier> generatedDOI = new MCRDOIParser().parse(doi);
return generatedDOI
.orElseThrow(() -> new MCRConfigurationException("The property " + doi + " is not a valid doi!"));
}
}
| 1,578 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCrossrefService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRCrossrefService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import javax.naming.OperationNotSupportedException;
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.MCRConstants;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRBaseContent;
import org.mycore.common.content.MCRContent;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.pi.doi.client.crossref.MCRCrossrefClient;
import org.mycore.pi.doi.crossref.MCRCrossrefUtil;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
public class MCRCrossrefService extends MCRDOIBaseService {
private static final String CONFIG_TEST = "Test";
private static final String CONFIG_REGISTRANT = "Registrant";
private static final String CONFIG_DEPOSITOR_MAIL = "DepositorMail";
private static final String CONFIG_DEPOSITOR = "Depositor";
public static final String DEFAULT_SCHEMA = "http://data.crossref.org/schemas/crossref4.4.1.xsd";
private static final String TEST_HOST = "test.crossref.org";
private static final String PRODUCTION_HOST = "doi.crossref.org";
private static final Logger LOGGER = LogManager.getLogger();
private String registrant;
private String depositor;
private String depositorMail;
@Override
protected String getDefaultSchemaPath() {
return DEFAULT_SCHEMA;
}
@Override
protected void checkConfiguration() throws MCRConfigurationException {
super.checkConfiguration();
init();
}
private void init() {
initCommonProperties();
registrant = requireNotEmptyProperty(CONFIG_REGISTRANT);
depositor = requireNotEmptyProperty(CONFIG_DEPOSITOR);
depositorMail = requireNotEmptyProperty(CONFIG_DEPOSITOR_MAIL);
}
@Override
protected boolean validateRegistrationDocument(MCRBase obj, MCRDigitalObjectIdentifier identifier,
String additional) {
try {
validateDocument(obj.getId().toString(), transform(obj, identifier.asString()));
return true;
} catch (MCRPersistentIdentifierException | MCRConfigurationException e) {
return false;
}
}
@Override
protected Document transform(MCRBase obj, String pi)
throws MCRPersistentIdentifierException {
Document resultDocument;
try {
final MCRContent result = getTransformer().transform(new MCRBaseContent(obj));
resultDocument = result.asXML();
} catch (IOException | JDOMException e) {
throw new MCRConfigurationException(
String.format(Locale.ROOT, "Could not transform the object %s with the trasformer %s", obj.getId(),
getTransformerID()),
e);
}
final Element root = resultDocument.getRootElement();
final Element headElement = root.getChild("head", MCRConstants.CROSSREF_NAMESPACE);
final String batchID = UUID.randomUUID() + "_" + obj.getId();
final String timestampMilliseconds = String.valueOf(new Date().getTime());
MCRCrossrefUtil.insertBatchInformation(headElement, batchID, timestampMilliseconds, depositor, depositorMail,
registrant);
MCRCrossrefUtil.replaceDOIData(root, (objectID) -> Objects.equals(obj.getId().toString(), objectID) ? pi : null,
MCRFrontendUtil.getBaseURL());
return resultDocument;
}
private String getHost() {
return Optional.ofNullable(getProperties().get(CONFIG_TEST))
.map(Boolean::valueOf)
.map(testMode -> testMode ? TEST_HOST : PRODUCTION_HOST)
.orElse(PRODUCTION_HOST);
}
@Override
protected void delete(MCRDigitalObjectIdentifier identifier, MCRBase obj, String additional)
throws MCRPersistentIdentifierException {
throw new MCRPersistentIdentifierException("Delete is not Supported!",
new OperationNotSupportedException("Delete is not Supported!"));
}
@Override
protected void deleteJob(Map<String, String> parameters) {
}
@Override
protected void updateJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
String doi = parameters.get(CONTEXT_DOI);
String idString = parameters.get(CONTEXT_OBJ);
if (!checkJobValid(idString, PiJobAction.UPDATE)) {
return;
}
MCRObjectID objectID = MCRObjectID.getInstance(idString);
this.validateJobUserRights(objectID);
MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
Document newCrossrefBatch = transform(object, doi);
validateDocument(object.getId().toString(), newCrossrefBatch);
final MCRCrossrefClient client = new MCRCrossrefClient(getHost(), getUsername(), getPassword());
client.doMDUpload(newCrossrefBatch);
}
@Override
protected void registerJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
String doi = parameters.get(CONTEXT_DOI);
String idString = parameters.get(CONTEXT_OBJ);
if (!checkJobValid(idString, PiJobAction.REGISTER)) {
return;
}
MCRObjectID objectID = MCRObjectID.getInstance(idString);
this.validateJobUserRights(objectID);
MCRObject mcrBase = MCRMetadataManager.retrieveMCRObject(objectID);
final Document resultDocument = transform(mcrBase, doi);
final MCRCrossrefClient client = new MCRCrossrefClient(getHost(), getUsername(), getPassword());
client.doMDUpload(resultDocument);
}
}
| 6,830 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMapObjectIDDOIGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRMapObjectIDDOIGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.util.Optional;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.pi.MCRPIGenerator;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
/**
* Uses mapping from MCRObjectID base to DOI prefix to generate DOIs.
* e.g. <code>MCR.PI.Generator.MapObjectIDDOI.Prefix.mycore_mods = 10.5072/my.</code> will map
* <code>mycore_mods_00004711</code> to <code>10.5072/my.4711</code>
*
* @author Thomas Scheffler (yagee)
*/
public class MCRMapObjectIDDOIGenerator extends MCRPIGenerator<MCRDigitalObjectIdentifier> {
private final MCRDOIParser mcrdoiParser;
private String generatorID;
public MCRMapObjectIDDOIGenerator() {
super();
mcrdoiParser = new MCRDOIParser();
}
@Override
public MCRDigitalObjectIdentifier generate(MCRBase mcrObject, String additional)
throws MCRPersistentIdentifierException {
final MCRObjectID objectId = mcrObject.getId();
return Optional.ofNullable(getProperties().get("Prefix." + objectId.getBase()))
.map(prefix -> {
final int objectIdNumberAsInteger = objectId.getNumberAsInteger();
return prefix.contains("/") ? prefix + objectIdNumberAsInteger
: prefix + '/' + objectIdNumberAsInteger;
})
.flatMap(mcrdoiParser::parse).map(MCRDigitalObjectIdentifier.class::cast)
.orElseThrow(() -> new MCRPersistentIdentifierException("Prefix." + objectId.getBase() +
" is not defined in " + generatorID + "."));
}
}
| 2,364 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOIParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.util.Optional;
import org.mycore.pi.MCRPIParser;
public class MCRDOIParser implements MCRPIParser<MCRDigitalObjectIdentifier> {
public static final String DIRECTORY_INDICATOR = "10.";
@Override
public Optional<MCRDigitalObjectIdentifier> parse(String doi) {
if (!doi.startsWith(DIRECTORY_INDICATOR)) {
return Optional.empty();
}
String[] doiParts = doi.split("/", 2);
if (doiParts.length != 2) {
return Optional.empty();
}
String prefix = doiParts[0];
String suffix = doiParts[1];
if (suffix.length() == 0) {
return Optional.empty();
}
return Optional.of(new MCRDigitalObjectIdentifier(prefix, suffix));
}
}
| 1,516 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUUIDDOIGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRUUIDDOIGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.util.Optional;
import java.util.UUID;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.pi.MCRPIGenerator;
import org.mycore.pi.MCRPersistentIdentifier;
public class MCRUUIDDOIGenerator extends MCRPIGenerator<MCRDigitalObjectIdentifier> {
private final MCRDOIParser mcrdoiParser;
private String prefix = MCRConfiguration2.getStringOrThrow("MCR.DOI.Prefix");
public MCRUUIDDOIGenerator() {
super();
mcrdoiParser = new MCRDOIParser();
}
@Override
public MCRDigitalObjectIdentifier generate(MCRBase mcrObject, String additional) {
Optional<MCRDigitalObjectIdentifier> parse = mcrdoiParser.parse(prefix + "/" + UUID.randomUUID());
MCRPersistentIdentifier doi = parse.get();
return (MCRDigitalObjectIdentifier) doi;
}
}
| 1,621 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOIBaseService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIBaseService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import javax.xml.validation.Schema;
import org.jdom2.Document;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRContentTransformerFactory;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.pi.MCRPIJobService;
import org.mycore.pi.MCRPIManager;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import org.xml.sax.SAXException;
import jakarta.persistence.NoResultException;
/**
* A doi Base Service which contains common DOI registration code.
*/
public abstract class MCRDOIBaseService extends MCRPIJobService<MCRDigitalObjectIdentifier> {
protected static final String CONTEXT_OBJ = "obj";
protected static final String CONTEXT_DOI = "doi";
private static final String CONFIG_TRANSFORMER = "Transformer";
private static final String CONFIG_USER_NAME = "Username";
private static final String CONFIG_PASSWORD = "Password";
private static final String CONFIG_SCHEMA = "Schema";
private static final String TYPE = "doi";
private String username;
private String password;
private Schema schema;
private String transformerID;
public MCRDOIBaseService() {
super(TYPE);
}
protected void initCommonProperties() {
setUsername(requireNotEmptyProperty(CONFIG_USER_NAME));
setPassword(requireNotEmptyProperty(CONFIG_PASSWORD));
setTransformerID(requireNotEmptyProperty(CONFIG_TRANSFORMER));
final MCRContentTransformer transformer = getTransformer();
final Map<String, String> properties = getProperties();
final String schemaURLString = properties.getOrDefault(CONFIG_SCHEMA, getDefaultSchemaPath());
setSchema(resolveSchema(schemaURLString));
}
public static Schema resolveSchema(final String schemaURLString) {
try {
return MCRXMLHelper.resolveSchema(schemaURLString, true);
} catch (SAXException | IOException e) {
throw new MCRConfigurationException("Error while loading " + schemaURLString + " schema!", e);
}
}
protected abstract String getDefaultSchemaPath();
@Override
protected Optional<String> getJobInformation(Map<String, String> contextParameters) {
String pattern = "{0} DOI: {1} for object: {2}";
return Optional.of(String.format(Locale.ROOT, pattern, getAction(contextParameters).toString(),
contextParameters.get(CONTEXT_DOI), contextParameters.get(CONTEXT_OBJ)));
}
protected boolean checkJobValid(String mycoreID, PiJobAction action) {
final MCRObjectID objectID = MCRObjectID.getInstance(mycoreID);
final boolean exists = MCRMetadataManager.exists(objectID);
try {
MCRPIManager.getInstance().get(getServiceID(), mycoreID, "");
} catch (NoResultException r) {
return false;
}
return exists;
}
@Override
protected HashMap<String, String> createJobContextParams(PiJobAction action, MCRBase obj,
MCRDigitalObjectIdentifier doi, String additional) {
HashMap<String, String> params = new HashMap<>();
params.put(CONTEXT_DOI, doi.asString());
params.put(CONTEXT_OBJ, obj.getId().toString());
return params;
}
protected MCRContentTransformer getTransformer() {
return MCRContentTransformerFactory.getTransformer(transformerID);
}
protected void validateDocument(String id, Document resultDocument)
throws MCRPersistentIdentifierException {
try {
getSchema().newValidator().validate(new JDOMSource(resultDocument));
} catch (SAXException | IOException e) {
throw new MCRPersistentIdentifierException(
"Error while validating generated xml for " + id, e);
}
}
protected abstract Document transform(MCRBase obj, String pi)
throws MCRPersistentIdentifierException;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Schema getSchema() {
return schema;
}
public void setSchema(Schema schema) {
this.schema = schema;
}
public String getTransformerID() {
return transformerID;
}
public void setTransformerID(String transformerID) {
this.transformerID = transformerID;
}
}
| 5,722 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOIService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDOIService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.xml.validation.Schema;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.transform.JDOMSource;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRBaseContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.xml.MCRXMLFunctions;
import org.mycore.common.xml.MCRXMLHelper;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRContentTypes;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.pi.MCRPIGenerator;
import org.mycore.pi.doi.client.datacite.MCRDataciteClient;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import org.mycore.services.i18n.MCRTranslation;
import org.xml.sax.SAXException;
/**
* Registers {@link MCRDigitalObjectIdentifier} at Datacite.
* <p>
* Properties:
* <dl>
* <dt>MetadataManager</dt>
* <dd>A metadata manager which inserts the {@link MCRDigitalObjectIdentifier} to a object</dd>
* <dt>Generator</dt>
* <dd>A {@link MCRPIGenerator} which generates {@link MCRDigitalObjectIdentifier}</dd>
* <dt>Username</dt>
* <dd>The username which will be used for authentication </dd>
* <dt>Password</dt>
* <dd>The password which will be used for authentication</dd>
* <dt>RegisterBaseURL</dt>
* <dd>The BaseURL (everything before /receive/mcr_object_0000000) which will be send to Datacite.</dd>
* <dt>UseTestPrefix</dt>
* <dd>Deprecated use UseTestServer instead.</dd>
* <dt>UseTestServer</dt>
* <dd>Use the test server of Datacite instead of the production server! (Default is UseTestPrefix or false) </dd>
* <dt>RegistrationConditionProvider</dt>
* <dd>Used to detect if the registration should happen. DOI will be created but the real registration will if the
* Condition is true. The Parameter is optional and the default condition is always true.</dd>
* <dt>Schema</dt>
* <dd>The path to the schema. (must be in classpath; default is {@link #DEFAULT_DATACITE_SCHEMA_PATH})</dd>
* <dt>Namespace</dt>
* <dd>The namespace for the Datacite version (Default is {@link #KERNEL_3_NAMESPACE_URI}</dd>
* <dt>JobApiUser</dt>
* <dd>The user which will be used to run the registration/update job</dd>
* </dl>
*/
public class MCRDOIService extends MCRDOIBaseService {
private static final String KERNEL_3_NAMESPACE_URI = "http://datacite.org/schema/kernel-3";
private static final String TEST_PREFIX = "UseTestPrefix";
private static final String TEST_SERVER = "UseTestServer";
private static final Logger LOGGER = LogManager.getLogger();
/**
* A media URL is longer then 255 chars
*/
private static final int ERR_CODE_1_1 = 0x1001;
/**
* The datacite document is not valid
*/
private static final int ERR_CODE_1_2 = 0x1002;
private static final int MAX_URL_LENGTH = 255;
public static final String DATACITE_SCHEMA_V3 = "http://schema.datacite.org/meta/kernel-3/metadata.xsd";
public static final String DATACITE_SCHEMA_V4 = "http://schema.datacite.org/meta/kernel-4/metadata.xsd";
public static final String DATACITE_SCHEMA_V41 = "http://schema.datacite.org/meta/kernel-4.1/metadata.xsd";
public static final String DATACITE_SCHEMA_V43 = "http://schema.datacite.org/meta/kernel-4.3/metadata.xsd";
private static final String DEFAULT_DATACITE_SCHEMA_PATH = DATACITE_SCHEMA_V3;
private static final String TRANSLATE_PREFIX = "component.pi.register.error.";
private static final String DEFAULT_CONTEXT_PATH = "receive/$ID";
private String host;
private String registerURL;
private String registerURLContext;
private Namespace nameSpace;
private boolean useTestServer;
private void init() {
Map<String, String> properties = getProperties();
useTestServer = Boolean
.parseBoolean(properties.getOrDefault(TEST_SERVER, properties.getOrDefault(TEST_PREFIX, "false")));
registerURL = properties.get("RegisterBaseURL");
nameSpace = Namespace.getNamespace("datacite", properties.getOrDefault("Namespace", KERNEL_3_NAMESPACE_URI));
if (!registerURL.endsWith("/")) {
registerURL += "/";
}
registerURLContext = properties.getOrDefault("RegisterURLContext", DEFAULT_CONTEXT_PATH);
host = "mds." + (usesTestServer() ? "test." : "") + "datacite.org";
}
@Override
protected String getDefaultSchemaPath() {
return DEFAULT_DATACITE_SCHEMA_PATH;
}
private void insertDOI(Document datacite, String doi)
throws MCRPersistentIdentifierException {
XPathExpression<Element> compile = XPathFactory.instance().compile(
"//datacite:identifier[@identifierType='DOI']",
Filters.element(), null, nameSpace);
List<Element> doiList = compile.evaluate(datacite);
if (doiList.size() > 1) {
throw new MCRPersistentIdentifierException("There is more then one identifier with type DOI!");
} else if (doiList.size() == 1) {
Element doiElement = doiList.stream().findAny().get();
LOGGER.warn("Found existing DOI({}) in Document will be replaced with {}", doiElement.getTextTrim(),
doi);
doiElement.setText(doi);
} else {
// must be 0
Element doiElement = new Element("identifier", nameSpace);
datacite.getRootElement().addContent(doiElement);
doiElement.setAttribute("identifierType", "DOI");
doiElement.setText(doi);
}
}
@Override
protected void checkConfiguration() throws MCRConfigurationException {
super.checkConfiguration();
this.initCommonProperties();
init();
try {
getDataciteClient().getDOIList();
} catch (MCRPersistentIdentifierException e) {
LOGGER.error("Error while checking Datacite credentials!", e);
}
}
@Deprecated
public boolean usesTestPrefix() {
return usesTestServer();
}
public boolean usesTestServer() {
return useTestServer;
}
public String getRegisterURL() {
return registerURL;
}
@Override
public void validateRegistration(MCRBase obj, String additional)
throws MCRPersistentIdentifierException, MCRAccessException {
List<Map.Entry<String, URI>> mediaList = getMediaList((MCRObject) obj);
for (Map.Entry<String, URI> stringURIEntry : mediaList) {
if (stringURIEntry.getValue().toString().length() > MAX_URL_LENGTH) {
throw new MCRPersistentIdentifierException(
"The URI " + stringURIEntry + " from media-list is to long!",
MCRTranslation.translate(TRANSLATE_PREFIX + ERR_CODE_1_1),
ERR_CODE_1_1);
}
}
super.validateRegistration(obj, additional);
}
public URI getRegisteredURI(MCRBase obj) throws URISyntaxException {
return new URI(this.registerURL + registerURLContext.replaceAll("\\$[iI][dD]", obj.getId().toString()));
}
/**
* Builds a list with with right content types and media urls assigned of a specific Object
*
* @param obj the object
* @return a list of entrys Media-Type, URL
*/
public List<Map.Entry<String, URI>> getMediaList(MCRObject obj) {
List<Map.Entry<String, URI>> entryList = new ArrayList<>();
Optional<MCRObjectID> derivateIdOptional = MCRMetadataManager.getDerivateIds(obj.getId(), 1, TimeUnit.MINUTES)
.stream().findFirst();
derivateIdOptional.ifPresent(derivateId -> {
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateId);
String mainDoc = derivate.getDerivate().getInternals().getMainDoc();
MCRPath mainDocumentPath = MCRPath.getPath(derivateId.toString(), mainDoc);
try {
String contentType = Optional.ofNullable(MCRContentTypes.probeContentType(mainDocumentPath))
.orElse("application/octet-stream");
entryList.add(new AbstractMap.SimpleEntry<>(contentType, new URI(this.registerURL + MCRXMLFunctions
.encodeURIPath("/servlets/MCRFileNodeServlet/" + derivateId + "/" + mainDoc))));
} catch (IOException | URISyntaxException e) {
LOGGER.error("Error while detecting the file to register!", e);
}
});
return entryList;
}
public MCRDataciteClient getDataciteClient() {
return new MCRDataciteClient(host, getUsername(), getPassword());
}
@Override
protected boolean validateRegistrationDocument(MCRBase obj, MCRDigitalObjectIdentifier identifier,
String additional) {
try {
transform(obj, identifier.asString());
return true;
} catch (MCRPersistentIdentifierException e) {
LOGGER.error("Error while validating Datacite document!", e);
return false;
}
}
@Override
protected Document transform(MCRBase mcrBase, String doi)
throws MCRPersistentIdentifierException {
MCRObjectID id = mcrBase.getId();
MCRBaseContent content = new MCRBaseContent(mcrBase);
try {
MCRContent transform = getTransformer().transform(content);
Document dataciteDocument = transform.asXML();
insertDOI(dataciteDocument, doi);
Schema dataciteSchema = getSchema();
try {
dataciteSchema.newValidator().validate(new JDOMSource(dataciteDocument));
} catch (SAXException e) {
String translatedInformation = MCRTranslation.translate(TRANSLATE_PREFIX + ERR_CODE_1_2);
throw new MCRPersistentIdentifierException(
"The document " + id + " does not generate well formed Datacite!",
translatedInformation, ERR_CODE_1_2, e);
}
return dataciteDocument;
} catch (IOException | JDOMException e) {
throw new MCRPersistentIdentifierException(
"Could not transform the content of " + id + " with the transformer " + getTransformerID(), e);
}
}
@Override
public void delete(MCRDigitalObjectIdentifier doi, MCRBase obj, String additional) {
if (hasRegistrationStarted(obj.getId(), additional) || this.isRegistered(obj.getId(), additional)) {
LOGGER.warn("Object {} with registered doi {} got deleted. Try to set DOI inactive.", obj.getId(),
doi.asString());
if (this.isRegistered(obj.getId(), additional)) {
HashMap<String, String> contextParameters = new HashMap<>();
contextParameters.put(CONTEXT_DOI, doi.asString());
contextParameters.put(CONTEXT_OBJ, obj.getId().toString());
this.addJob(PiJobAction.DELETE, contextParameters);
}
}
}
@Override
public void deleteJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
MCRDigitalObjectIdentifier doi = getDOIFromJob(parameters);
try {
getDataciteClient().deleteMetadata(doi);
} catch (MCRPersistentIdentifierException e) {
LOGGER.error("Error while setting {} inactive! Delete of object should continue!", doi.asString());
}
}
@Override
public void updateJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
MCRDigitalObjectIdentifier doi = getDOIFromJob(parameters);
String idString = parameters.get(CONTEXT_OBJ);
if (!checkJobValid(idString, PiJobAction.UPDATE)) {
return;
}
MCRObjectID objectID = MCRObjectID.getInstance(idString);
this.validateJobUserRights(objectID);
MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
Document newDataciteMetadata = transform(object, doi.asString());
MCRDataciteClient dataciteClient = getDataciteClient();
Document oldDataciteMetadata = null;
try {
oldDataciteMetadata = dataciteClient.resolveMetadata(doi);
} catch (JDOMException e) {
LOGGER.info("Old metadata is invalid.. replace it with new metadata!");
}
if (oldDataciteMetadata == null || !MCRXMLHelper.deepEqual(newDataciteMetadata, oldDataciteMetadata)) {
LOGGER.info("Sending new Metadata of {} to Datacite!", idString);
dataciteClient.storeMetadata(newDataciteMetadata);
}
try {
URI uri = dataciteClient.resolveDOI(doi);
URI registeredURI = getRegisteredURI(object);
if (!uri.equals(registeredURI)) {
LOGGER.info("Sending new URL({}) to Datacite!", registeredURI);
dataciteClient.mintDOI(doi, registeredURI);
}
} catch (URISyntaxException e) {
throw new MCRPersistentIdentifierException("Error while updating URL!", e);
}
}
@Override
public void registerJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
MCRDigitalObjectIdentifier doi = getDOIFromJob(parameters);
String idString = parameters.get(CONTEXT_OBJ);
if (!checkJobValid(idString, PiJobAction.REGISTER)) {
return;
}
MCRObjectID objectID = MCRObjectID.getInstance(idString);
this.validateJobUserRights(objectID);
MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
MCRObject mcrBase = MCRMetadataManager.retrieveMCRObject(objectID);
Document dataciteDocument = transform(mcrBase, doi.asString());
MCRDataciteClient dataciteClient = getDataciteClient();
dataciteClient.storeMetadata(dataciteDocument);
URI registeredURI;
try {
registeredURI = getRegisteredURI(object);
dataciteClient.mintDOI(doi, registeredURI);
} catch (URISyntaxException e) {
throw new MCRException("Base-URL seems to be invalid!", e);
}
List<Map.Entry<String, URI>> entryList = getMediaList(object);
dataciteClient.setMediaList(doi, entryList);
this.updateRegistrationDate(objectID, "", new Date());
}
/**
* Gets the {@link MCRDigitalObjectIdentifier} from the job parameters. This method does not ensure that the
* returned {@link MCRDigitalObjectIdentifier} object instance is the same as the generated one.
*
* @param parameters the job parameters
* @return the parsed DOI
* @throws MCRPersistentIdentifierException if the DOI can not be parsed
*/
protected MCRDigitalObjectIdentifier getDOIFromJob(Map<String, String> parameters)
throws MCRPersistentIdentifierException {
String doiString = parameters.get(CONTEXT_DOI);
return parseIdentifier(doiString)
.orElseThrow(
() -> new MCRPersistentIdentifierException("The String " + doiString + " can not be parsed to a DOI!"));
}
}
| 16,701 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCreateDateDOIGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRCreateDateDOIGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mycore.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.common.MCRISO8601Date;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.pi.MCRPIGenerator;
import org.mycore.pi.MCRPIManager;
import org.mycore.pi.MCRPIRegistrationInfo;
import org.mycore.pi.MCRPersistentIdentifier;
public class MCRCreateDateDOIGenerator extends MCRPIGenerator<MCRDigitalObjectIdentifier> {
private static final String DATE_PATTERN = "yyyyMMdd-HHmmss";
private static final String CREATE_DATE_PLACEHOLDER = "$createDate$";
private static final String DATE_REGEXP = CREATE_DATE_PLACEHOLDER + "-([0-9]+)";
private static final Map<String, AtomicInteger> PATTERN_COUNT_MAP = new HashMap<>();
private final MCRDOIParser mcrdoiParser;
private String prefix = MCRConfiguration2.getStringOrThrow("MCR.DOI.Prefix");
public MCRCreateDateDOIGenerator() {
super();
mcrdoiParser = new MCRDOIParser();
}
@Override
public MCRDigitalObjectIdentifier generate(MCRBase mcrObj, String additional) {
Date createdate = mcrObj.getService().getDate("createdate");
if (createdate != null) {
MCRISO8601Date mcrdate = new MCRISO8601Date();
mcrdate.setDate(createdate);
String createDate = mcrdate.format(DATE_PATTERN, Locale.ENGLISH);
final int count = getCountForCreateDate(createDate);
Optional<MCRDigitalObjectIdentifier> parse = mcrdoiParser.parse(prefix + "/" + createDate + "-" + count);
MCRPersistentIdentifier doi = parse.orElseThrow(() -> new MCRException("Error while parsing default doi!"));
return (MCRDigitalObjectIdentifier) doi;
} else {
throw new MCRPersistenceException("The object " + mcrObj.getId() + " doesn't have a createdate!");
}
}
private int getCountForCreateDate(String createDate) {
return getCount(prefix + "/" + DATE_REGEXP.replace(CREATE_DATE_PLACEHOLDER, createDate));
}
private synchronized int getCount(final String pattern) {
AtomicInteger count = PATTERN_COUNT_MAP.computeIfAbsent(pattern, (pattern_) -> {
Pattern regExpPattern = Pattern.compile(pattern_);
Predicate<String> matching = regExpPattern.asPredicate();
List<MCRPIRegistrationInfo> list = MCRPIManager.getInstance()
.getList(MCRDigitalObjectIdentifier.TYPE, -1, -1);
Comparator<Integer> integerComparator = Integer::compareTo;
// extract the number of the PI
Optional<Integer> highestNumber = list.stream()
.map(MCRPIRegistrationInfo::getIdentifier)
.filter(matching)
.map(pi -> {
// extract the number of the PI
Matcher matcher = regExpPattern.matcher(pi);
if (matcher.find() && matcher.groupCount() == 1) {
String group = matcher.group(1);
return Integer.parseInt(group, 10);
} else {
return null;
}
}).filter(Objects::nonNull)
.max(integerComparator)
.map(n -> n + 1);
return new AtomicInteger(highestNumber.orElse(0));
});
return count.getAndIncrement();
}
}
| 4,563 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDigitalObjectIdentifier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/MCRDigitalObjectIdentifier.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi;
import java.util.Locale;
import org.mycore.pi.MCRPersistentIdentifier;
public class MCRDigitalObjectIdentifier implements MCRPersistentIdentifier {
public static final String TYPE = "doi";
public static final String TEST_DOI_PREFIX = "10.5072";
private String prefix;
private String suffix;
protected MCRDigitalObjectIdentifier(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
@Override
public String asString() {
return String.format(Locale.ENGLISH, "%s/%s", prefix, suffix);
}
}
| 1,457 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteRestResponseEntry.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteRestResponseEntry.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
public class MCRDataciteRestResponseEntry {
int index;
String type;
MCRDataciteRestResponseEntryData data;
int ttl;
String timestamp;
public int getIndex() {
return index;
}
public String getType() {
return type;
}
public MCRDataciteRestResponseEntryData getData() {
return data;
}
public int getTtl() {
return ttl;
}
public String getTimestamp() {
return timestamp;
}
}
| 1,251 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteRestResponseEntryData.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteRestResponseEntryData.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
public class MCRDataciteRestResponseEntryData {
String format;
MCRDataciteRestResponseEntryDataValue value;
public MCRDataciteRestResponseEntryData(String format, MCRDataciteRestResponseEntryDataValue value) {
this.format = format;
this.value = value;
}
public MCRDataciteRestResponseEntryDataValue getValue() {
return value;
}
public String getFormat() {
return format;
}
}
| 1,214 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteRest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteRest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.mycore.pi.doi.MCRDOIParser;
import org.mycore.pi.doi.MCRDigitalObjectIdentifier;
import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class MCRDataciteRest {
private static final String URL_TEMPLATE = "http://doi.org/api/handles/{doi}";
private static CloseableHttpClient getHttpClient() {
return HttpClientBuilder.create().build();
}
public static MCRDataciteRestResponse get(MCRDigitalObjectIdentifier doi)
throws MCRIdentifierUnresolvableException {
HttpGet get = new HttpGet(URL_TEMPLATE.replaceAll("\\{doi\\}", doi.asString()));
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
try (BufferedReader buffer = new BufferedReader(
new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8))) {
String json = buffer.lines().collect(Collectors.joining("\n"));
Gson gson = new GsonBuilder().registerTypeAdapter(MCRDataciteRestResponseEntryData.class,
new MCRDOIRestResponseEntryDataValueDeserializer()).create();
return gson.fromJson(json, MCRDataciteRestResponse.class);
}
} catch (IOException e) {
throw new MCRIdentifierUnresolvableException(doi.asString(),
"The identifier " + doi.asString() + " is not resolvable!", e);
}
}
public static void main(String[] args) throws MCRIdentifierUnresolvableException {
get(new MCRDOIParser().parse("10.1000/1").get());
}
}
| 2,929 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteRestResponseEntryDataValue.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteRestResponseEntryDataValue.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
public class MCRDataciteRestResponseEntryDataValue {
}
| 827 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteClient.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.pi.doi.MCRDOIParser;
import org.mycore.pi.doi.MCRDigitalObjectIdentifier;
import org.mycore.pi.exceptions.MCRDatacenterAuthenticationException;
import org.mycore.pi.exceptions.MCRDatacenterException;
import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
/**
* Used for DOI registration.
* <ol>
* <li>use {@link #storeMetadata(Document)} to store a datacite document
* (should include a {@link MCRDigitalObjectIdentifier})</li>
* <li>use {@link #mintDOI(MCRDigitalObjectIdentifier, URI)} to "register"
* the {@link MCRDigitalObjectIdentifier} with a URI</li>
* <li>use {@link #setMediaList(MCRDigitalObjectIdentifier, List)} to add a list of mime-type URI pairs to a DOI</li>
* </ol>
*/
public class MCRDataciteClient {
public static final String DOI_REGISTER_REQUEST_TEMPLATE = "doi=%s\nurl=%s";
private static final String HTTPS_SCHEME = "https";
private static final Logger LOGGER = LogManager.getLogger();
private String host;
private String userName;
private String password;
/**
* @param host the host (in most cases mds.datacite.org)
* @param userName the login username will be used in every method or null if no login should be used
* @param password the password
*/
public MCRDataciteClient(String host, String userName, String password) {
this.host = host;
this.userName = userName;
this.password = password;
}
private static byte[] documentToByteArray(Document document) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(document, outputStream);
return outputStream.toByteArray();
}
private static String getStatusString(final HttpResponse resp) throws IOException {
StatusLine statusLine = resp.getStatusLine();
StringBuilder statusStringBuilder = new StringBuilder();
statusStringBuilder.append(statusLine.getStatusCode()).append(" - ").append(statusLine.getReasonPhrase())
.append(" - ");
try (Scanner scanner = new Scanner(resp.getEntity().getContent(), StandardCharsets.UTF_8)) {
while (scanner.hasNextLine()) {
statusStringBuilder.append(scanner.nextLine());
}
}
return statusStringBuilder.toString();
}
public List<Map.Entry<String, URI>> getMediaList(final MCRDigitalObjectIdentifier doi)
throws MCRPersistentIdentifierException {
ArrayList<Map.Entry<String, URI>> entries = new ArrayList<>();
URI requestURI = getRequestURI("/media/" + doi.asString());
HttpGet httpGet = new HttpGet(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
try (Scanner scanner = new Scanner(response.getEntity().getContent(), StandardCharsets.UTF_8)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split("=", 2);
String mediaType = parts[0];
URI mediaURI = new URI(parts[1]);
entries.add(new AbstractMap.SimpleEntry<>(mediaType, mediaURI));
}
return entries;
}
}
case HttpStatus.SC_UNAUTHORIZED -> throw new MCRDatacenterAuthenticationException();
case HttpStatus.SC_NOT_FOUND -> throw new MCRIdentifierUnresolvableException(doi.asString(),
doi.asString() + " is not resolvable! " + getStatusString(response));
// return entries; // datacite says no media attached or doi does not exist (not sure what to do)
default -> throw new MCRDatacenterException(
String.format(Locale.ENGLISH, "Datacenter-Error while set media-list for doi: \"%s\" : %s",
doi.asString(), getStatusString(response)));
}
} catch (IOException e) {
throw new MCRDatacenterException("Unknown error while set media list", e);
} catch (URISyntaxException e) {
throw new MCRDatacenterException("Could not parse media url!", e);
}
}
public void setMediaList(final MCRDigitalObjectIdentifier doi, List<Map.Entry<String, URI>> mediaList)
throws MCRPersistentIdentifierException {
URI requestURI = getRequestURI("/media/" + doi.asString());
HttpPost post = new HttpPost(requestURI);
String requestBodyString = mediaList.stream()
.map(buildPair())
.collect(Collectors.joining("\r\n"));
LOGGER.info(requestBodyString);
StringEntity requestEntity = new StringEntity(requestBodyString, ContentType.create("text/plain", "UTF-8"));
post.setEntity(requestEntity);
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(post);
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
return;
}
case HttpStatus.SC_BAD_REQUEST -> throw new MCRDatacenterException(
getStatusString(response)); // non-supported mime-type, not allowed URL domain
case HttpStatus.SC_UNAUTHORIZED -> throw new MCRDatacenterAuthenticationException();
default -> throw new MCRDatacenterException(
String.format(Locale.ENGLISH, "Datacenter-Error while set media-list for doi: \"%s\" : %s",
doi.asString(), getStatusString(response)));
}
} catch (IOException e) {
throw new MCRDatacenterException("Unknown error while set media list", e);
}
}
private Function<Map.Entry<String, URI>, String> buildPair() {
return entry -> entry.getKey() + "=" + entry.getValue();
}
public void mintDOI(final MCRDigitalObjectIdentifier doi, URI url) throws MCRPersistentIdentifierException {
URI requestURI = getRequestURI("/doi");
HttpPost post = new HttpPost(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
post.setEntity(new StringEntity(
String.format(Locale.ENGLISH, DOI_REGISTER_REQUEST_TEMPLATE, doi.asString(), url.toString())));
CloseableHttpResponse response = httpClient.execute(post);
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_CREATED -> {
return;
}
case HttpStatus.SC_BAD_REQUEST -> throw new MCRDatacenterException(
getStatusString(response)); // invalid PREFIX or wrong format, but format is hard defined!
case HttpStatus.SC_UNAUTHORIZED -> throw new MCRDatacenterAuthenticationException();
case HttpStatus.SC_PRECONDITION_FAILED -> throw new MCRDatacenterException(String.format(Locale.ENGLISH,
"Metadata must be uploaded first! (%s)", getStatusString(response)));
default -> throw new MCRDatacenterException(String.format(Locale.ENGLISH,
"Datacenter-Error while minting doi: \"%s\" : %s", doi.asString(), getStatusString(response)));
}
} catch (IOException e) {
throw new MCRDatacenterException("Unknown error while mint new doi", e);
}
}
public List<MCRDigitalObjectIdentifier> getDOIList() throws MCRPersistentIdentifierException {
URI requestURI = getRequestURI("/doi");
HttpGet get = new HttpGet(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
try (Scanner scanner = new Scanner(entity.getContent(), StandardCharsets.UTF_8)) {
List<MCRDigitalObjectIdentifier> doiList = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Optional<MCRDigitalObjectIdentifier> parse = new MCRDOIParser().parse(line);
MCRDigitalObjectIdentifier doi = parse
.orElseThrow(() -> new MCRException("Could not parse DOI from Datacite!"));
doiList.add(doi);
}
return doiList;
}
}
case HttpStatus.SC_NO_CONTENT -> {
return Collections.emptyList();
}
default -> throw new MCRDatacenterException(
String.format(Locale.ENGLISH, "Unknown error while resolving all doi’s \n %d - %s",
statusLine.getStatusCode(), statusLine.getReasonPhrase()));
}
} catch (IOException e) {
throw new MCRDatacenterException("Unknown error while resolving all doi’s", e);
}
}
public URI resolveDOI(final MCRDigitalObjectIdentifier doiParam) throws MCRPersistentIdentifierException {
URI requestURI = getRequestURI("/doi/" + doiParam.asString());
HttpGet get = new HttpGet(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
try (Scanner scanner = new Scanner(entity.getContent(), StandardCharsets.UTF_8)) {
String uriString = scanner.nextLine();
return new URI(uriString);
}
}
case HttpStatus.SC_NO_CONTENT -> throw new MCRIdentifierUnresolvableException(doiParam.asString(),
"The identifier " + doiParam.asString() + " is currently not resolvable");
case HttpStatus.SC_NOT_FOUND -> throw new MCRIdentifierUnresolvableException(doiParam.asString(),
"The identifier " + doiParam.asString() + " was not found in the Datacenter!");
case HttpStatus.SC_UNAUTHORIZED -> throw new MCRDatacenterAuthenticationException();
case HttpStatus.SC_INTERNAL_SERVER_ERROR -> throw new MCRDatacenterException(
String.format(Locale.ENGLISH, "Datacenter error while resolving doi: \"%s\" : %s",
doiParam.asString(), getStatusString(response)));
default -> throw new MCRDatacenterException(String.format(Locale.ENGLISH,
"Unknown error while resolving doi: \"%s\" : %s", doiParam.asString(),
getStatusString(response)));
}
} catch (IOException | URISyntaxException ex) {
throw new MCRDatacenterException(
String.format(Locale.ENGLISH, "Unknown error while resolving doi: \"%s\"", doiParam.asString()), ex);
}
}
private URI getRequestURI(String path) {
try {
URIBuilder builder = new URIBuilder()
.setScheme(HTTPS_SCHEME)
.setHost(this.host)
.setPath(path);
return builder.build();
} catch (URISyntaxException e) {
throw new MCRConfigurationException("Invalid URI Exception!", e);
}
}
/**
*
* @param doi the doi
* @return the resolved metadata of the doi
* @throws MCRDatacenterAuthenticationException if the authentication is wrong
* @throws MCRIdentifierUnresolvableException if the doi is not valid or can not be resolved
* @throws JDOMException if the metadata is empty or not a valid xml document
* @throws MCRDatacenterException if there is something wrong with the communication with the datacenter
*/
public Document resolveMetadata(final MCRDigitalObjectIdentifier doi) throws MCRDatacenterAuthenticationException,
MCRIdentifierUnresolvableException, JDOMException, MCRDatacenterException {
URI requestURI = getRequestURI("/metadata/" + doi.asString());
HttpGet get = new HttpGet(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
SAXBuilder builder = new SAXBuilder();
return builder.build(entity.getContent());
}
case HttpStatus.SC_UNAUTHORIZED -> throw new MCRDatacenterAuthenticationException();
case HttpStatus.SC_NO_CONTENT -> throw new MCRIdentifierUnresolvableException(doi.asString(),
"The identifier " + doi.asString() + " is currently not resolvable");
case HttpStatus.SC_NOT_FOUND -> throw new MCRIdentifierUnresolvableException(doi.asString(),
"The identifier " + doi.asString() + " was not found!");
case HttpStatus.SC_GONE -> throw new MCRIdentifierUnresolvableException(doi.asString(),
"The identifier " + doi.asString() + " was deleted!");
default -> throw new MCRDatacenterException("Unknown return status: " + getStatusString(response));
}
} catch (IOException e) {
throw new MCRDatacenterException("Error while resolving metadata!", e);
}
}
public URI storeMetadata(Document metadata) throws MCRPersistentIdentifierException {
URI requestURI = getRequestURI("/metadata");
HttpPost post = new HttpPost(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
byte[] documentBytes = documentToByteArray(metadata);
ByteArrayEntity inputStreamEntity = new ByteArrayEntity(documentBytes,
ContentType.create("application/xml", "UTF-8"));
post.setEntity(inputStreamEntity);
CloseableHttpResponse response = httpClient.execute(post);
StatusLine statusLine = response.getStatusLine();
StringBuilder sb = new StringBuilder();
try (InputStream is = response.getEntity().getContent()) {
Scanner scanner = new Scanner(is, StandardCharsets.UTF_8);
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(System.lineSeparator());
}
} catch (IOException | UnsupportedOperationException e) {
LOGGER.warn("Could not read content!", e);
}
String responseString = sb.toString();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_CREATED -> {
Header[] responseHeaders = response.getAllHeaders();
for (Header responseHeader : responseHeaders) {
if (responseHeader.getName().equals("Location")) {
return new URI(responseHeader.getValue());
}
}
// should not happen
throw new MCRDatacenterException("Location header not found in response! - " + responseString);
}
case HttpStatus.SC_BAD_REQUEST -> // invalid xml or wrong PREFIX
throw new MCRDatacenterException("Invalid xml or wrong PREFIX: " + statusLine.getStatusCode()
+ " - " + statusLine.getReasonPhrase() + " - " + responseString);
case HttpStatus.SC_UNAUTHORIZED -> // no login
throw new MCRDatacenterAuthenticationException();
default -> throw new MCRDatacenterException(
"Unknown return status: " + statusLine.getStatusCode() + " - "
+ statusLine.getReasonPhrase() + " - " + responseString);
}
} catch (IOException | URISyntaxException e) {
throw new MCRDatacenterException("Error while storing metadata!", e);
}
}
public void deleteMetadata(final MCRDigitalObjectIdentifier doi) throws MCRPersistentIdentifierException {
URI requestURI = getRequestURI("/metadata/" + doi.asString());
HttpDelete delete = new HttpDelete(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(delete);
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
return;
}
case HttpStatus.SC_UNAUTHORIZED -> throw new MCRDatacenterAuthenticationException();
case HttpStatus.SC_NOT_FOUND -> throw new MCRIdentifierUnresolvableException(doi.asString(),
doi.asString() + " was not found!");
default -> throw new MCRDatacenterException(
"Unknown return status: " + statusLine.getStatusCode() + " - " + statusLine.getReasonPhrase());
}
} catch (IOException e) {
throw new MCRDatacenterException("Error while deleting metadata!", e);
}
}
private CloseableHttpClient getHttpClient() {
return HttpClientBuilder.create().useSystemProperties().setDefaultCredentialsProvider(getCredentialsProvider())
.build();
}
private BasicCredentialsProvider getCredentialsProvider() {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (userName != null && !userName.isEmpty() && password != null && !password.isEmpty()) {
credentialsProvider.setCredentials(AuthScope.ANY, getCredentials());
}
return credentialsProvider;
}
private UsernamePasswordCredentials getCredentials() {
return new UsernamePasswordCredentials(this.userName, this.password);
}
}
| 21,457 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteRestResponse.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteRestResponse.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
import java.util.List;
public class MCRDataciteRestResponse {
int responseCode;
String handle;
List<MCRDataciteRestResponseEntry> values;
/**
* 1 : Success. (HTTP 200 OK)
* 2 : Error. Something unexpected went wrong during handle resolution. (HTTP 500 Internal Server Error)
* 100 : Handle Not Found. (HTTP 404 Not Found)
* 200 : Values Not Found. The handle exists but has no values
* (or no values according to the types and indices specified). (HTTP 200 OK)
*
* @return the code
*/
public int getResponseCode() {
return responseCode;
}
public String getHandle() {
return handle;
}
public List<MCRDataciteRestResponseEntry> getValues() {
return values;
}
}
| 1,545 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteRestResponseEntryDataBase64Value.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteRestResponseEntryDataBase64Value.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
import java.util.Base64;
public class MCRDataciteRestResponseEntryDataBase64Value extends MCRDataciteRestResponseEntryDataValue {
private final byte[] decodedValue;
public MCRDataciteRestResponseEntryDataBase64Value(String base64value) {
decodedValue = Base64.getDecoder().decode(base64value);
}
public byte[] getDecodedValue() {
return decodedValue;
}
}
| 1,166 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDataciteRestResponseEntryDataStringValue.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDataciteRestResponseEntryDataStringValue.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
public class MCRDataciteRestResponseEntryDataStringValue extends MCRDataciteRestResponseEntryDataValue {
private String value;
public MCRDataciteRestResponseEntryDataStringValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
| 1,071 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOIRestResponseEntryDataValueDeserializer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/datacite/MCRDOIRestResponseEntryDataValueDeserializer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.datacite;
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
public class MCRDOIRestResponseEntryDataValueDeserializer
implements JsonDeserializer<MCRDataciteRestResponseEntryData> {
@Override
public MCRDataciteRestResponseEntryData deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject dataObject = jsonElement.getAsJsonObject();
String format = dataObject.get("format").getAsJsonPrimitive().getAsString();
JsonElement value = dataObject.get("value");
MCRDataciteRestResponseEntryDataValue dcValue = switch (format) {
case "string" -> new MCRDataciteRestResponseEntryDataStringValue(value.getAsJsonPrimitive().getAsString());
case "base64" -> new MCRDataciteRestResponseEntryDataBase64Value(value.getAsJsonPrimitive().getAsString());
//hex, admin, vlist and site currently not supported
default -> new MCRDataciteRestResponseEntryDataValue();
};
return new MCRDataciteRestResponseEntryData(format, dcValue);
}
}
| 2,073 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCrossrefClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/client/crossref/MCRCrossrefClient.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.client.crossref;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.pi.exceptions.MCRDatacenterException;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import jakarta.validation.constraints.NotNull;
public class MCRCrossrefClient {
public static final Logger LOGGER = LogManager.getLogger();
private static final String HTTP_SCHEME_PREFIX = "http://";
private static final String HTTPS_SCHEME_PREFIX = "https://";
private static final String NOT_NULL_MESSAGE = "%s needs to be not null!";
private static final String DEPOSIT_PATH = "servlet/deposit";
private static final String OPERATION_PARAM = "operation";
private static final String USER_PARAM = "login_id";
private static final String PASSWORD_PARAM = "login_passwd";
private static final String OPERATION_DOMDUPLOAD = "doMDUpload";
private static final XMLOutputter METADATA_OUTPUTTER = new XMLOutputter(Format.getPrettyFormat());
private String host, username, password;
public MCRCrossrefClient(@NotNull String host, @NotNull String username, @NotNull String password) {
if (host == null) {
throw new IllegalArgumentException(String.format(Locale.ROOT, NOT_NULL_MESSAGE, "Host"));
}
if (username == null) {
throw new IllegalArgumentException(String.format(Locale.ROOT, NOT_NULL_MESSAGE, "Username"));
}
if (password == null) {
throw new IllegalArgumentException(String.format(Locale.ROOT, NOT_NULL_MESSAGE, "Password"));
}
this.host = host;
this.username = username;
this.password = password;
if (host.endsWith("/")) {
this.host = this.host.substring(0, host.length() - 1);
}
if (this.host.startsWith(HTTP_SCHEME_PREFIX)) {
this.host = this.host.substring(HTTP_SCHEME_PREFIX.length());
} else if (this.host.startsWith(HTTPS_SCHEME_PREFIX)) {
this.host = this.host.substring(HTTPS_SCHEME_PREFIX.length());
}
}
private static CloseableHttpClient getHttpClient() {
return HttpClientBuilder.create().build();
}
public void doMDUpload(Document metadata) throws MCRPersistentIdentifierException {
final HttpPost postRequest;
try {
final URIBuilder uriBuilder;
uriBuilder = new URIBuilder("https://" + this.host + "/" + DEPOSIT_PATH);
addAuthParameters(uriBuilder);
uriBuilder.addParameter(OPERATION_PARAM, OPERATION_DOMDUPLOAD);
postRequest = new HttpPost(uriBuilder.build());
} catch (URISyntaxException e) {
throw new MCRPersistentIdentifierException(
String.format(Locale.ROOT, "Can not build a valid URL with host: %s", this.host));
}
final String metadataXmlAsString = METADATA_OUTPUTTER.outputString(metadata);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addBinaryBody("fname", metadataXmlAsString.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_XML,
"crossref_query.xml")
.build();
postRequest.setEntity(reqEntity);
try (CloseableHttpClient client = getHttpClient()) {
try (CloseableHttpResponse response = client.execute(postRequest)) {
final int statusCode = response.getStatusLine().getStatusCode();
final HttpEntity entity = response.getEntity();
String message = "";
switch (statusCode) {
case 200:
if (entity != null) {
try (InputStream inputStream = entity.getContent()) {
List<String> doc = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
message = doc.stream().collect(Collectors.joining(System.lineSeparator()));
LOGGER.debug(message);
}
}
return; // everything OK!
case 503:
LOGGER.error("Seems like the quota of 10000 Entries is exceeded!");
default:
if (entity != null) {
try (InputStream inputStream = entity.getContent()) {
List<String> doc = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);
message = doc.stream().collect(Collectors.joining(System.lineSeparator()));
}
}
throw new MCRDatacenterException(
String.format(Locale.ROOT, "Error while doMDUpload: (%d)%s%s%s", statusCode,
response.getStatusLine().getReasonPhrase(), System.lineSeparator(), message));
}
}
} catch (IOException e) {
throw new MCRDatacenterException(String.format(Locale.ROOT, "Error while sending request to %s", host), e);
}
}
private void addAuthParameters(URIBuilder uriBuilder) {
uriBuilder.addParameter(USER_PARAM, this.username);
uriBuilder.addParameter(PASSWORD_PARAM, this.password);
}
}
| 6,862 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCrossrefUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/crossref/MCRCrossrefUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.crossref;
import java.util.List;
import java.util.Objects;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRConstants;
import org.mycore.common.function.MCRThrowFunction;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import jakarta.validation.constraints.NotNull;
/**
* Proivides Util functions for Crossref registration.
*/
public class MCRCrossrefUtil {
private static final Namespace CR = MCRConstants.CROSSREF_NAMESPACE;
/**
* Inserts informations to the crossref head element.
* @param headElement existing head element
* @param batchID Publisher generated ID that uniquely identifies the DOI submission batch. It will be used as a
* reference in error messages sent by the MDDB, and can be used for submission tracking. The
* publisher must insure that this number is unique for every submission to CrossRef.
* @param timestamp Indicates version of a batch file instance or DOI. timestamp is used
* to uniquely identify batch files and DOI values when a DOI has been updated one or
* more times. timestamp is an integer representation of date and time that serves as a
* version number for the record that is being deposited. Because CrossRef uses it as a
* version number, the format need not follow any public standard and therefore the
* publisher can determine the internal format. The schema format is a double of at
* least 64 bits, insuring that a fully qualified date/time stamp of 19 digits can be
* submitted. When depositing data, CrossRef will check to see if a DOI has already
* been deposited for the specific doi value. If the newer data carries a time stamp
* value that is equal to or greater than the old data based on a strict numeric
* comparison, the new data will replace the old data. If the new data value is less
* than the old data value, the new data will not replace the old data. timestamp is
* optional in doi_data and required in head. The value from the head instance
* timestamp will be used for all instances of doi_data that do not include a timestamp
* element.
* @param depositorName Name of the organization registering the DOIs. The name placed in this element should match
* the name under which a depositing organization has registered with CrossRef.
* @param depositorMail e-mail address to which batch success and/or error messages are sent.
* It is recommended that this address be unique to a position within the organization
* submitting data (e.g. "doi@...") rather than unique to a person. In this way, the
* alias for delivery of this mail can be changed as responsibility for submission of
* DOI data within the organization changes from one person to another.
* @param registrant The organization that owns the information being registered.
*/
public static void insertBatchInformation(@NotNull Element headElement, @NotNull String batchID,
@NotNull String timestamp, @NotNull String depositorName, @NotNull String depositorMail,
@NotNull String registrant) {
headElement.getChild("doi_batch_id", CR).setText(Objects.requireNonNull(batchID));
headElement.getChild("timestamp", CR).setText(Objects.requireNonNull(timestamp));
final Element depositorElement = headElement.getChild("depositor", CR);
depositorElement.getChild("depositor_name", CR).setText(Objects.requireNonNull(depositorName));
depositorElement.getChild("email_address", CR).setText(Objects.requireNonNull(depositorMail));
headElement.getChild("registrant", CR).setText(Objects.requireNonNull(registrant));
}
public static void replaceDOIData(Element root,
MCRThrowFunction<String, String, MCRPersistentIdentifierException> idDOIFunction, String baseURL)
throws MCRPersistentIdentifierException {
XPathFactory xpfac = XPathFactory.instance();
XPathExpression<Element> xp = xpfac
.compile(".//cr:doi_data_replace", Filters.element(), null, MCRConstants.getStandardNamespaces());
List<Element> evaluate = xp.evaluate(root);
for (Element element : evaluate) {
final String mycoreObjectID = element.getText();
final String doi = idDOIFunction.apply(mycoreObjectID);
element.removeContent();
if (doi != null) {
element.addContent(new Element("doi", CR).setText(doi));
element.addContent(new Element("resource", CR).setText(baseURL + "/receive/" + mycoreObjectID));
element.setName("doi_data");
} else {
element.getParentElement().removeContent(element);
}
}
}
}
| 5,834 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDOICommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/doi/cli/MCRDOICommands.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.doi.cli;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;
import org.mycore.access.MCRAccessException;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRBaseContent;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRContentTransformerFactory;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.pi.MCRPIMetadataService;
import org.mycore.pi.MCRPIServiceDates;
import org.mycore.pi.MCRPIServiceManager;
import org.mycore.pi.backend.MCRPI;
import org.mycore.pi.doi.MCRDOIParser;
import org.mycore.pi.doi.MCRDOIService;
import org.mycore.pi.doi.MCRDigitalObjectIdentifier;
import org.mycore.pi.doi.client.datacite.MCRDataciteClient;
import org.mycore.pi.doi.crossref.MCRCrossrefUtil;
import org.mycore.pi.exceptions.MCRIdentifierUnresolvableException;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import org.xml.sax.SAXException;
@MCRCommandGroup(name = "DOI Commands")
public class MCRDOICommands {
private static final Logger LOGGER = LogManager.getLogger();
private static final String REPAIR_MEDIALIST_OF_0_AND_SERVICE_1 = "repair medialist of {0} and service {1}";
public static final String CROSSREF_SCHEMA_PATH = "xsd/crossref/4.4.1/crossref4.4.1.xsd";
@MCRCommand(syntax = "repair incomplete registered doi {0} with registration service {1}",
help = "Use this method if a DOI is registered, but not inserted in the Database. {0} is the DOI and "
+ "{1} the registration service from configuration.")
public static void repairIncompleteRegisteredDOI(String doiString, String serviceID)
throws MCRPersistentIdentifierException, MCRAccessException {
MCRDOIService registrationService = (MCRDOIService) MCRConfiguration2
.getInstanceOf(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + serviceID).get();
MCRDataciteClient dataciteClient = registrationService.getDataciteClient();
MCRDigitalObjectIdentifier doi = new MCRDOIParser().parse(doiString)
.orElseThrow(() -> new MCRException("Invalid DOI: " + doiString));
URI uri = dataciteClient.resolveDOI(doi);
if (!uri.toString().startsWith(registrationService.getRegisterURL())) {
LOGGER.info("DOI/URL is not from this application: {}/{}", doi.asString(), uri);
return;
}
MCRObjectID objectID = getObjectID(uri);
if (!MCRMetadataManager.exists(objectID)) {
LOGGER.info("Could not find Object : {}", objectID);
return;
}
MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(objectID);
MCRPIMetadataService<MCRDigitalObjectIdentifier> synchronizer = registrationService
.getMetadataService();
if (!registrationService.isRegistered(objectID, doiString)) {
LOGGER.info("{} is not found in PI-Database. Insert it..", objectID);
Date now = new Date();
registrationService.insertIdentifierToDatabase(mcrObject, "", doi, new MCRPIServiceDates(now, now));
}
if (!synchronizer.getIdentifier(mcrObject, "").isPresent()) {
LOGGER.info("Object doesn't have Identifier inscribed! Insert it..");
synchronizer.insertIdentifier(doi, mcrObject, "");
MCRMetadataManager.update(mcrObject);
}
}
@MCRCommand(syntax = "repair registered dois {0}",
help = "Contacts the Registration Service and inserts all registered DOIs to the Database. "
+ "It also updates all media files. The Service ID{0} is the id from the configuration.",
order = 10)
public static void synchronizeDatabase(String serviceID) {
MCRDOIService registrationService = (MCRDOIService) MCRConfiguration2
.getInstanceOf(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + serviceID).get();
try {
MCRDataciteClient dataciteClient = registrationService.getDataciteClient();
List<MCRDigitalObjectIdentifier> doiList = dataciteClient.getDOIList();
doiList.stream().filter(doi -> {
boolean isTestDOI = doi.getPrefix().equals(MCRDigitalObjectIdentifier.TEST_DOI_PREFIX);
return !isTestDOI;
}).forEach(doi -> {
try {
URI uri = dataciteClient.resolveDOI(doi);
if (uri.toString().startsWith(registrationService.getRegisterURL())) {
LOGGER.info("Checking DOI: {}", doi.asString());
MCRObjectID objectID = getObjectID(uri);
if (MCRMetadataManager.exists(objectID)) {
if (!registrationService.isRegistered(objectID, "")) {
LOGGER.info("DOI is not registered in MyCoRe. Add to Database: {}", doi.asString());
MCRPI databaseEntry = new MCRPI(doi.asString(), registrationService.getType(),
objectID.toString(), "", serviceID, new MCRPIServiceDates(new Date(), null));
MCREntityManagerProvider.getCurrentEntityManager().persist(databaseEntry);
}
// Update main files
MCRObject obj = MCRMetadataManager.retrieveMCRObject(objectID);
List<Map.Entry<String, URI>> entryList = registrationService.getMediaList(obj);
dataciteClient.setMediaList(doi, entryList);
} else {
LOGGER.info("Could not find Object : {}", objectID);
}
} else {
LOGGER.info("DOI/URL is not from this application: {}/{}", doi.asString(), uri);
}
} catch (MCRPersistentIdentifierException e) {
LOGGER.error("Error occurred for DOI: {}", doi, e);
}
});
} catch (MCRPersistentIdentifierException e) {
LOGGER.error("Error while receiving DOI list from Registration-Service!", e);
}
}
private static MCRObjectID getObjectID(URI uri) {
String s = uri.toString();
String idString = s.substring(s.lastIndexOf("/") + 1);
return MCRObjectID.getInstance(idString);
}
@MCRCommand(syntax = "repair media list of {0}",
help = "Sends new media lists to Datacite. The Service ID{0} is the id from the configuration.")
public static List<String> updateMediaListOfAllDOI(String serviceID) {
MCRDOIService registrationService = (MCRDOIService) MCRConfiguration2
.getInstanceOf(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + serviceID).get();
try {
MCRDataciteClient dataciteClient = registrationService.getDataciteClient();
List<MCRDigitalObjectIdentifier> doiList = dataciteClient.getDOIList();
return doiList.stream()
.filter(doi -> {
boolean isTestDOI = doi.getPrefix().equals(MCRDigitalObjectIdentifier.TEST_DOI_PREFIX);
return !isTestDOI;
})
.map(MCRDigitalObjectIdentifier::asString)
.map(doiStr -> new MessageFormat(REPAIR_MEDIALIST_OF_0_AND_SERVICE_1, Locale.ROOT).format(
new Object[] { doiStr, serviceID }))
.collect(Collectors.toList());
} catch (MCRPersistentIdentifierException e) {
LOGGER.error("Error while receiving DOI list from Registration-Service!", e);
}
return Collections.emptyList();
}
@MCRCommand(syntax = REPAIR_MEDIALIST_OF_0_AND_SERVICE_1,
help = "Sends new media list to Datacite. {0} is the DOI. The Service ID{1} is the id from the configuration.")
public static void updateMediaListForDOI(String doiString, String serviceID) {
MCRDOIService registrationService = (MCRDOIService) MCRConfiguration2
.getInstanceOf(MCRPIServiceManager.REGISTRATION_SERVICE_CONFIG_PREFIX + serviceID).get();
MCRDataciteClient dataciteClient = registrationService.getDataciteClient();
MCRDigitalObjectIdentifier doi = new MCRDOIParser()
.parse(doiString)
.orElseThrow(() -> new IllegalArgumentException("The String " + doiString + " is no valid DOI!"));
try {
URI uri = dataciteClient.resolveDOI(doi);
if (uri.toString().startsWith(registrationService.getRegisterURL())) {
String s = uri.toString();
LOGGER.info("Checking DOI: {} / {}", doi.asString(), s);
String idString = s.substring(s.lastIndexOf("/") + 1);
MCRObjectID objectID = MCRObjectID.getInstance(idString);
if (MCRMetadataManager.exists(objectID)) {
MCRObject obj = MCRMetadataManager.retrieveMCRObject(objectID);
List<Map.Entry<String, URI>> newMediaList = registrationService.getMediaList(obj);
List<Map.Entry<String, URI>> oldMediaList;
try {
oldMediaList = dataciteClient.getMediaList(doi);
} catch (MCRIdentifierUnresolvableException e) {
LOGGER.warn("{} had no media list!", doi);
oldMediaList = new ArrayList<>();
}
HashMap<String, URI> newHashMap = new HashMap<>();
newMediaList.forEach(e -> newHashMap.put(e.getKey(), e.getValue()));
oldMediaList.forEach(e -> {
/*
Currently it is not possible to delete inserted values key values (mime types).
So we update old media mimetypes which are not present in new list to the same URL of the first
mimetype entry.
*/
if (!newHashMap.containsKey(e.getKey())) {
newHashMap.put(e.getKey(), newMediaList.stream()
.findFirst()
.orElseThrow(() -> new MCRException("new media list is empty (this should not happen)"))
.getValue());
}
});
dataciteClient.setMediaList(doi, newHashMap.entrySet().stream().collect(Collectors.toList()));
LOGGER.info("Updated media-list of {}", doiString);
} else {
LOGGER.info("Object {} does not exist in this application!", objectID);
}
} else {
LOGGER.info("DOI is not from this application: ({}) {}", uri, registrationService.getRegisterURL());
}
} catch (MCRPersistentIdentifierException e) {
LOGGER.error("Error occurred for DOI: {}", doi, e);
}
}
@MCRCommand(syntax = "validate document {0} with transformer {1} against crossref schema")
public static void validateCrossrefDocument(String mycoreIDString, String transformer)
throws MCRPersistentIdentifierException {
final MCRObjectID mycoreID = MCRObjectID.getInstance(mycoreIDString);
if (!MCRMetadataManager.exists(mycoreID)) {
LOGGER.error("Document with id {} does not exist", mycoreIDString);
return;
}
final MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(mycoreID);
final MCRContentTransformer contentTransformer = MCRContentTransformerFactory.getTransformer(transformer);
final MCRContent transform;
final Document document;
try {
transform = contentTransformer.transform(new MCRBaseContent(mcrObject));
document = transform.asXML();
} catch (IOException | JDOMException e) {
LOGGER.error("Error while transforming document {} with transformer {}", e, mycoreIDString, transformer);
return;
}
final Element root = document.getRootElement();
MCRCrossrefUtil.insertBatchInformation(root.getChild("head", MCRConstants.CROSSREF_NAMESPACE),
UUID.randomUUID().toString(), String.valueOf(new Date().getTime()),
"Test-Depositor", "email@mycore.de", "Test-Registrant");
MCRCrossrefUtil.replaceDOIData(root, "DOI for "::concat, "http://baseURL.de/");
final String documentAsString = new XMLOutputter(Format.getPrettyFormat()).outputString(document);
LOGGER.info("Crossref document is: {}", documentAsString);
final Schema schema;
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL localSchemaURL = MCRDOIService.class.getClassLoader().getResource(CROSSREF_SCHEMA_PATH);
if (localSchemaURL == null) {
LOGGER.error(CROSSREF_SCHEMA_PATH + " was not found!");
return;
}
schema = schemaFactory.newSchema(localSchemaURL);
} catch (SAXException e) {
LOGGER.error("Error while loading crossref schema!", e);
return;
}
try {
schema.newValidator().validate(new JDOMSource(document));
LOGGER.info("Check Complete!");
} catch (SAXException | IOException e) {
LOGGER.error("Error while checking schema!", e);
}
}
}
| 15,415 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIDPURLGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/purl/MCRIDPURLGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.purl;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.pi.MCRPIGenerator;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
/**
* The property BaseURLTemplate is your url and the {@link MCRIDPURLGenerator}
* will replace $ID with the actual MyCoRe-ID.
*/
public class MCRIDPURLGenerator extends MCRPIGenerator<MCRPURL> {
@Override
public MCRPURL generate(MCRBase mcrObj, String additional)
throws MCRPersistentIdentifierException {
String baseUrlTemplate = getProperties().getOrDefault("BaseURLTemplate", "");
String replace = baseUrlTemplate;
String before;
do {
before = replace;
replace = baseUrlTemplate.replace("$ID", mcrObj.getId().toString());
} while (!replace.equals(before));
try {
URL url = new URI(replace).toURL();
return new MCRPURL(url);
} catch (MalformedURLException | URISyntaxException e) {
throw new MCRPersistentIdentifierException("Error while creating URL object from string: " + replace, e);
}
}
}
| 1,974 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPURLParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURLParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.purl;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Optional;
import org.mycore.pi.MCRPIParser;
public class MCRPURLParser implements MCRPIParser<MCRPURL> {
@Override
public Optional<MCRPURL> parse(String identifier) {
try {
URL url = new URI(identifier).toURL();
return Optional.of(new MCRPURL(url));
} catch (MalformedURLException | URISyntaxException e) {
return Optional.empty();
}
}
}
| 1,303 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPURLService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURLService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.purl;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.pi.MCRPIJobService;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
public class MCRPURLService extends MCRPIJobService<MCRPURL> {
private static final String TYPE = "purl";
private static final String CONTEXT_PURL = "PURL";
private static final String CONTEXT_OBJECT = "ObjectID";
private static final String PURL_SERVER_CONFIG = "Server";
private static final String PURL_USER_CONFIG = "Username";
private static final String PURL_PASSWORD_CONFIG = "Password";
private static final String PURL_BASE_URL = "RegisterBaseURL";
private static final String PURL_CONTEXT_CONFIG = "RegisterURLContext";
private static final String PURL_MAINTAINER_CONFIG = "Maintainer";
private static final String DEFAULT_CONTEXT_PATH = "receive/$ID";
public MCRPURLService() {
super(TYPE);
}
@Override
public void registerJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
MCRPURL purl = getPURLFromJob(parameters);
String idString = parameters.get(CONTEXT_OBJECT);
validateJobUserRights(MCRObjectID.getInstance(idString));
doWithPURLManager(
manager -> manager
.registerNewPURL(purl.getUrl().getPath(), buildTargetURL(idString), "302", getProperties().getOrDefault(
PURL_MAINTAINER_CONFIG, "test")));
this.updateStartRegistrationDate(MCRObjectID.getInstance(idString), "", new Date());
}
protected String buildTargetURL(String objId) {
String baseURL = getProperties().get(PURL_BASE_URL);
return baseURL + getProperties().getOrDefault(PURL_CONTEXT_CONFIG, DEFAULT_CONTEXT_PATH)
.replaceAll("\\$[iI][dD]", objId);
}
@Override
protected Optional<String> getJobInformation(Map<String, String> contextParameters) {
return Optional.empty();
}
private MCRPURL getPURLFromJob(Map<String, String> parameters)
throws MCRPersistentIdentifierException {
String purlString = parameters.get(CONTEXT_PURL);
try {
return new MCRPURL(new URI(purlString).toURL());
} catch (MalformedURLException | URISyntaxException e) {
throw new MCRPersistentIdentifierException("Cannot parse " + purlString);
}
}
@Override
public void updateJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
String purlString = parameters.get(CONTEXT_PURL);
String objId = parameters.get(CONTEXT_OBJECT);
validateJobUserRights(MCRObjectID.getInstance(objId));
MCRPURL purl;
try {
purl = new MCRPURL(new URI(purlString).toURL());
} catch (MalformedURLException | URISyntaxException e) {
throw new MCRPersistentIdentifierException("Could not parse purl: " + purlString, e);
}
doWithPURLManager((purlManager) -> {
if (!purlManager.isPURLTargetURLUnchanged(purl.getUrl().toString(), buildTargetURL(
objId))) {
purlManager.updateExistingPURL(purl.getUrl().getPath(), buildTargetURL(objId), "302",
getProperties().getOrDefault(
PURL_MAINTAINER_CONFIG, "test"));
}
});
}
@Override
public void deleteJob(Map<String, String> parameters) {
// delete is not supported
}
@Override
protected void delete(MCRPURL identifier, MCRBase obj, String additional) {
// not supported
}
@Override
protected boolean validateRegistrationDocument(MCRBase obj, MCRPURL identifier, String additional) {
return true;
}
@Override
protected HashMap<String, String> createJobContextParams(PiJobAction action, MCRBase obj, MCRPURL purl,
String additional) {
HashMap<String, String> params = new HashMap<>();
params.put(CONTEXT_PURL, purl.asString());
params.put(CONTEXT_OBJECT, obj.getId().toString());
return params;
}
protected void doWithPURLManager(Consumer<MCRPURLManager> action) {
Map<String, String> props = getProperties();
String serverURL = props.get(PURL_SERVER_CONFIG);
String username = props.get(PURL_USER_CONFIG);
String password = props.get(PURL_PASSWORD_CONFIG);
MCRPURLManager manager = new MCRPURLManager();
manager.login(serverURL, username, password);
try {
action.accept(manager);
} finally {
manager.logout();
}
}
}
| 5,653 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPURL.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURL.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.purl;
import java.net.URL;
import org.mycore.pi.MCRPersistentIdentifier;
public class MCRPURL implements MCRPersistentIdentifier {
private URL url;
public MCRPURL(URL url) {
this.url = url;
}
public URL getUrl() {
return url;
}
@Override
public String asString() {
return url.toString();
}
}
| 1,104 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPURLManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/purl/MCRPURLManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.purl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* PURL Manager to register Persistent URLs on a PURL server
* <p>
* for further documentation see PURLZ Wiki:
* https://code.google.com/archive/p/persistenturls/wikis
* <p>
* Hint:
* -----
* Please check in your code that you do not register / override regular PURLs in test / development
* by checking:
* if (resolvingURL.contains("localhost")) {
* purl = "/test" + purl;
* }
*
* @author Robert Stephan
*/
public class MCRPURLManager {
private static final Logger LOGGER = LogManager.getLogger();
private static final String ADMIN_PATH = "/admin";
private static final String PURL_PATH = ADMIN_PATH + "/purl";
private static final String COOKIE_HEADER_PARAM = "Cookie";
private String purlServerBaseURL;
private String cookie = null;
/**
* sets the session cookie, if the login was successful
*
* @param purlServerURL - the base URL of the PURL server
* @param user - the PURL server user
* @param password - the user's password
*/
public void login(String purlServerURL, String user, String password) {
HttpURLConnection conn = null;
try {
purlServerBaseURL = purlServerURL;
// Get Cookie
URL url = new URI(purlServerBaseURL + ADMIN_PATH + "/login/login.bsh?referrer=/docs/index.html").toURL();
conn = (HttpURLConnection) url.openConnection();
conn.connect();
conn.getHeaderFields()
.getOrDefault("Set-Cookie", List.of())
.forEach(cookie -> {
this.cookie = cookie;
LOGGER.debug("Cookie: " + cookie);
});
conn.disconnect();
// Login
String data = "id=" + URLEncoder.encode(user, StandardCharsets.UTF_8);
data += "&passwd=" + URLEncoder.encode(password, StandardCharsets.UTF_8);
url = new URI(purlServerBaseURL + ADMIN_PATH + "/login/login-submit.bsh").toURL();
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty(COOKIE_HEADER_PARAM, cookie);
conn.setDoOutput(true);
try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)) {
wr.write(data);
wr.flush();
if (conn.getResponseCode() == 200) {
LOGGER.info(conn.getRequestMethod() + " " + conn.getURL() + " -> " + conn.getResponseCode());
} else {
LOGGER.error(conn.getRequestMethod() + " " + conn.getURL() + " -> " + conn.getResponseCode());
}
// Get the response
try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),
StandardCharsets.UTF_8))) {
String line;
while ((line = rd.readLine()) != null) {
if ("PURL User Login Failure".equals(line.trim())) {
cookie = null;
break;
}
}
}
}
conn.disconnect();
} catch (IOException | URISyntaxException e) {
if (!e.getMessage().contains(
"Server returned HTTP response code: 403 for URL: ")) {
LOGGER.error(e);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
/**
* logout from PURL server
*/
public void logout() {
HttpURLConnection conn = null;
int responseCode = -1;
try {
URL url = new URI(purlServerBaseURL + ADMIN_PATH + "/logout?referrer=/docs/index.html").toURL();
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty(COOKIE_HEADER_PARAM, cookie);
conn.setDoOutput(true);
try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)) {
wr.flush();
}
responseCode = conn.getResponseCode();
LOGGER.debug(conn.getRequestMethod() + " " + conn.getURL() + " -> " + responseCode);
} catch (IOException | URISyntaxException e) {
if (!e.getMessage().contains(
"Server returned HTTP response code: 403 for URL: ")) {
LOGGER.error(conn.getRequestMethod() + " " + conn.getURL() + " -> " + responseCode, e);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
// returns the response code
/**
* register a new PURL
*
* @param purl - the PURL
* @param target the target URL
* @param type - the PURL type
* @param maintainers - the maintainers
* @return the HTTP Status Code of the request
*/
public int registerNewPURL(String purl, String target, String type, String maintainers) {
int response = 0;
HttpURLConnection conn = null;
try {
// opener.open("http://localhost:8080/admin/purl/net/test2",
// urllib.urlencode(dict(type="410", maintainers="admin"))).read().close() #
// Create a 410 purl
URL url = new URI(purlServerBaseURL + PURL_PATH + purl).toURL();
LOGGER.debug(url.toString());
String data = "target=" + URLEncoder.encode(target, StandardCharsets.UTF_8);
data += "&maintainers=" + maintainers;
data += "&type=" + type;
LOGGER.debug(data);
// Send data
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(COOKIE_HEADER_PARAM, cookie);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)) {
wr.write(data);
wr.flush();
}
response = conn.getResponseCode();
if (response != 200 && conn.getErrorStream() != null && LOGGER.isErrorEnabled()) {
try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(),
StandardCharsets.UTF_8))) {
String line;
LOGGER.error(conn.getRequestMethod() + " " + conn.getURL() + " -> " + conn.getResponseCode());
while ((line = rd.readLine()) != null) {
LOGGER.error(line);
}
}
}
} catch (Exception e) {
LOGGER.error(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
/**
* updates an existing PURL
*
* @param purl - the PURL (relative URL)
* @param target - the target URL
* @param type - the PURL type
* @param maintainers list of maintainers (PURL server users or groups)
* @return the HTTP Status Code of the request
*/
public int updateExistingPURL(String purl, String target, String type, String maintainers) {
int response = 0;
HttpURLConnection conn = null;
try {
// opener.open("http://localhost:8080/admin/purl/net/test2",
// urllib.urlencode(dict(type="410", maintainers="admin"))).read().close() #
// Create a 410 purl
String strURL = purlServerBaseURL + PURL_PATH + purl;
strURL += "?target=" + URLEncoder.encode(target, StandardCharsets.UTF_8) + "&maintainers=" + maintainers
+ "&type=" + type;
URL url = new URI(strURL).toURL();
LOGGER.debug(url.toString());
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(COOKIE_HEADER_PARAM, cookie);
conn.setRequestMethod("PUT");
response = conn.getResponseCode();
if (response != 200 && conn.getErrorStream() != null && LOGGER.isErrorEnabled()) {
try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(),
StandardCharsets.UTF_8))) {
String line = null;
LOGGER.error(conn.getRequestMethod() + " " + conn.getURL() + " -> " + conn.getResponseCode());
while ((line = rd.readLine()) != null) {
LOGGER.error(line);
}
}
}
} catch (Exception e) {
LOGGER.error(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
/**
* deletes an existing PURL
*
* @return the HTTP Status Code of the request
*/
public int deletePURL(String purl) {
int response = 0;
HttpURLConnection conn = null;
try {
URL url = new URI(purlServerBaseURL + PURL_PATH + purl).toURL();
LOGGER.debug(url.toString());
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(COOKIE_HEADER_PARAM, cookie);
conn.setRequestMethod("DELETE");
response = conn.getResponseCode();
if (response != 200 || conn.getErrorStream() != null && LOGGER.isErrorEnabled()) {
try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(),
StandardCharsets.UTF_8))) {
String line = null;
LOGGER.error(conn.getRequestMethod() + " " + conn.getURL() + " -> " + conn.getResponseCode());
while ((line = rd.readLine()) != null) {
LOGGER.error(line);
}
}
}
} catch (Exception e) {
LOGGER.error(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}
/**
* check if a purl has the given target url
*
* @param purl - the purl
* @param targetURL - the target URL
* @return true, if the target URL is registered at the given PURL
*/
public boolean isPURLTargetURLUnchanged(String purl, String targetURL) {
HttpURLConnection conn = null;
try {
URL url = new URI(purlServerBaseURL + PURL_PATH + purl).toURL();
conn = (HttpURLConnection) url.openConnection();
int response = conn.getResponseCode();
if (response == 200) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(conn.getInputStream());
/*
* <purl status="1"> <id>/test/rosdok/ppn750527188</id> <type>302</type>
* <maintainers><uid>rosdok</uid><uid>test</uid></maintainers>
* <target><url>http://localhost:8080/rosdok/resolve/id/
* rosdok_document_0000000259</url></target> </purl>
*/
Element eTarget = (Element) doc.getDocumentElement().getElementsByTagName("target").item(0);
Element eTargetUrl = (Element) eTarget.getElementsByTagName("url").item(0);
return targetURL.equals(eTargetUrl.getTextContent().trim());
}
} catch (Exception e) {
LOGGER.error(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return false;
}
/**
* return the PURL metadata
*
* @param purl - the purl
* @return an XML document containing the metadata of the PURL
* or null if the PURL does not exist
*/
public Document retrievePURLMetadata(String purl, String targetURL) {
HttpURLConnection conn = null;
try {
URL url = new URI(purlServerBaseURL + PURL_PATH + purl).toURL();
conn = (HttpURLConnection) url.openConnection();
int response = conn.getResponseCode();
if (response == 200) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
return db.parse(conn.getInputStream());
/* <purl status="1">
* <id>/test/rosdok/ppn750527188</id>
* <type>302</type>
* <maintainers>
* <uid>rosdok</uid>
* <uid>test</uid>
* </maintainers>
* <target>
* <url>http://localhost:8080/rosdok/resolve/id/rosdok_document_0000000259</url>
* </target>
* </purl>
*/
}
} catch (Exception e) {
LOGGER.error(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
/**
* check if a PURL exists
*
* @param purl - the purl
* @return true, if the given PURL is known
*/
public boolean existsPURL(String purl) {
HttpURLConnection conn = null;
try {
URL url = new URI(purlServerBaseURL + PURL_PATH + purl).toURL();
conn = (HttpURLConnection) url.openConnection();
int response = conn.getResponseCode();
return response == 200;
} catch (Exception e) {
LOGGER.error(e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return false;
}
}
| 15,404 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIStatePredicateBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIStatePredicateBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import java.util.Optional;
import org.mycore.datamodel.metadata.MCRBase;
public abstract class MCRPIStatePredicateBase extends MCRPIPredicateBase
implements MCRPICreationPredicate, MCRPIObjectRegistrationPredicate {
protected abstract String getRequiredState();
@Override
public final boolean test(MCRBase base) {
return Optional.ofNullable(base.getService().getState())
.map(state -> state.getId().equals(getRequiredState()))
.orElse(false);
}
}
| 1,265 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIPredicateBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIPredicateBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import org.jdom2.filter.Filter;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRConstants;
public abstract class MCRPIPredicateBase implements MCRPIPredicate {
private static final XPathFactory FACTORY = XPathFactory.instance();
protected final <T> XPathExpression<T> compileXpath(String xPath, Filter<T> filter) {
return FACTORY.compile(xPath, filter, null, MCRConstants.getStandardNamespaces());
}
}
| 1,244 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIOrPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIOrPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import java.util.Collections;
import java.util.List;
import org.mycore.common.config.annotation.MCRInstanceList;
import org.mycore.datamodel.metadata.MCRBase;
public final class MCRPIOrPredicate extends MCRPIPredicateBase {
@MCRInstanceList(valueClass = MCRPIPredicate.class)
public List<MCRPIPredicate> predicates = Collections.emptyList();
@Override
public boolean test(MCRBase mcrBase) {
return predicates.stream().anyMatch(predicate -> predicate.test(mcrBase));
}
}
| 1,264 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIXPathPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIXPathPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.datamodel.metadata.MCRBase;
public class MCRPIXPathPredicate extends MCRPIPredicateBase
implements MCRPICreationPredicate, MCRPIObjectRegistrationPredicate {
private XPathExpression<Boolean> expression;
@MCRProperty(name = "XPath")
public void setXPath(String xPath) {
expression = compileXpath("boolean(" + xPath + ")", Filters.fboolean());
}
@Override
public boolean test(MCRBase mcrBase) {
return expression.evaluateFirst(mcrBase.createXML()) == Boolean.TRUE;
}
}
| 1,428 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIObjectRegistrationPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIObjectRegistrationPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
public interface MCRPIObjectRegistrationPredicate extends MCRPIPredicate {
}
| 838 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPICreationPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPICreationPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
public interface MCRPICreationPredicate extends MCRPIPredicate {
}
| 828 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import java.util.function.Predicate;
import org.mycore.datamodel.metadata.MCRBase;
public interface MCRPIPredicate extends Predicate<MCRBase> {
}
| 910 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIOtherPICreatedPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIOtherPICreatedPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.pi.MCRPIManager;
/**
* PI Predicate, that checks if another PersistentIdentifier was created within the PI component
* before the current PI will be created or registered.
* <p>
* Use the properties *.Service and *.Type
* to specify the PI service and type of the PI which should be checked.
* <p>
* sample configuration:
* MCR.PI.Service.RosDokURN.CreationPredicate=org.mycore.pi.condition.MCRPIAndPredicate
* MCR.PI.Service.RosDokURN.CreationPredicate.1=org.mycore.pi.condition.MCRPIOtherPICreatedPredicate
* MCR.PI.Service.RosDokURN.CreationPredicate.1.Service=MCRLocalID
* MCR.PI.Service.RosDokURN.CreationPredicate.1.Type=local_id
* ...
*
* @author Robert Stephan
*
*/
public class MCRPIOtherPICreatedPredicate extends MCRPIPredicateBase
implements MCRPICreationPredicate, MCRPIObjectRegistrationPredicate {
@MCRProperty(name = "Type")
public String type;
@MCRProperty(name = "Service")
public String service;
@Override
public boolean test(MCRBase mcrBase) {
return MCRPIManager.getInstance().isCreated(mcrBase.getId(), "", type, service);
}
}
| 1,993 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIOtherPIRegisteredPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIOtherPIRegisteredPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.pi.MCRPIManager;
/**
* PI Predicate, that checks if another PersistentIdentifier was registered within the PI component
* before the current PI will be created or registered.
* <p>
* Use the properties *.Service and *.Type
* to specify the PI service and type of the PI which should be checked.
* <p>
* sample configuration:
* MCR.PI.Service.RosDokURN.CreationPredicate=org.mycore.pi.condition.MCRPIAndPredicate
* MCR.PI.Service.RosDokURN.CreationPredicate.1=org.mycore.pi.condition.MCRPIOtherPIRegisteredPredicate
* MCR.PI.Service.RosDokURN.CreationPredicate.1.Service=MCRLocalID
* MCR.PI.Service.RosDokURN.CreationPredicate.1.Type=local_id
* ...
*
* @author Robert Stephan
*
*/
public class MCRPIOtherPIRegisteredPredicate extends MCRPIPredicateBase
implements MCRPICreationPredicate, MCRPIObjectRegistrationPredicate {
@MCRProperty(name = "Type")
public String type;
@MCRProperty(name = "Service")
public String service;
@Override
public boolean test(MCRBase mcrBase) {
return MCRPIManager.getInstance().isRegistered(mcrBase.getId(), "", type, service);
}
}
| 2,005 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIAndPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIAndPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import java.util.Collections;
import java.util.List;
import org.mycore.common.config.annotation.MCRInstanceList;
import org.mycore.datamodel.metadata.MCRBase;
public final class MCRPIAndPredicate extends MCRPIPredicateBase {
@MCRInstanceList(valueClass = MCRPIPredicate.class)
public List<MCRPIPredicate> predicates = Collections.emptyList();
@Override
public boolean test(MCRBase mcrBase) {
return predicates.stream().allMatch(predicate -> predicate.test(mcrBase));
}
}
| 1,265 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIClassificationXPathPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIClassificationXPathPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.xpath.XPathExpression;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.datamodel.metadata.MCRBase;
public class MCRPIClassificationXPathPredicate extends MCRPIPredicateBase
implements MCRPICreationPredicate, MCRPIObjectRegistrationPredicate {
private static final Logger LOGGER = LogManager.getLogger();
private XPathExpression<Element> classificationBaseExpression;
private XPathExpression<String> classificationIdExpression;
private XPathExpression<String> categoryIdExpression;
private XPathExpression<Boolean> expression;
@MCRProperty(name = "BaseXPath")
public void setClassificationBaseXPath(String xPath) {
classificationBaseExpression = compileXpath(xPath, Filters.element());
}
@MCRProperty(name = "ClassIdXPath")
public void setClassificationIdXPath(String xPath) {
classificationIdExpression = compileXpath(xPath, Filters.fstring());
}
@MCRProperty(name = "CategIdXPath")
public void setCategoryIdXPath(String xPath) {
categoryIdExpression = compileXpath(xPath, Filters.fstring());
}
@MCRProperty(name = "XPath")
public void setXPath(String xPath) {
expression = compileXpath("boolean(" + xPath + ")", Filters.fboolean());
}
@Override
public boolean test(MCRBase mcrBase) {
MCRURIResolver resolver = MCRURIResolver.instance();
return classificationBaseExpression.evaluate(mcrBase.createXML()).stream().anyMatch(baseElement -> {
String classificationId = classificationIdExpression.evaluateFirst(baseElement);
String categoryId = categoryIdExpression.evaluateFirst(baseElement);
if (classificationId == null || categoryId == null) {
return false;
}
String classificationUri = "classification:metadata:0:children:" + classificationId + ":" + categoryId;
try {
Document classificationDocument = new Document();
classificationDocument.setRootElement(resolver.resolve(classificationUri));
return expression.evaluateFirst(classificationDocument) == Boolean.TRUE;
} catch (Exception e) {
LOGGER.warn("Failed to load " + classificationUri, e);
return false;
}
});
}
}
| 3,339 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIPublishedPredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIPublishedPredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
/**
* Just here for backward compatibility
*/
public class MCRPIPublishedPredicate extends MCRPIStatePredicateBase {
@Override
protected String getRequiredState() {
return "published";
}
}
| 974 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIStatePredicate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/condition/MCRPIStatePredicate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.condition;
import org.mycore.common.config.annotation.MCRProperty;
public class MCRPIStatePredicate extends MCRPIStatePredicateBase {
@MCRProperty(name = "State")
public String state;
protected String getRequiredState() {
return state;
}
}
| 1,018 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPI.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/backend/MCRPI.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.backend;
import java.util.Date;
import org.mycore.common.MCRCoreVersion;
import org.mycore.pi.MCRPIServiceDates;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
@Entity
@NamedQueries({
@NamedQuery(name = "Count.PI.Created",
query = "select count(u) from MCRPI u "
+ "where u.mycoreID = :mcrId "
+ "and u.type = :type "
+ "and (u.additional = :additional OR (u.additional IS NULL AND :additional IS NULL))"
+ "and u.service = :service"),
@NamedQuery(name = "Count.PI.Registered",
query = "select count(u) from MCRPI u "
+ "where u.mycoreID = :mcrId "
+ "and u.type = :type "
+ "and (u.additional = :additional OR (u.additional IS NULL AND :additional IS NULL))"
+ "and u.service = :service "
+ "and u.registered is not null"),
@NamedQuery(name = "Count.PI.RegistrationStarted",
query = "select count(u) from MCRPI u "
+ "where u.mycoreID = :mcrId "
+ "and u.type = :type "
+ "and u.additional = :additional "
+ "and u.service = :service "
+ "and u.registrationStarted is not null"),
@NamedQuery(name = "Get.PI.Created",
query = "select u from MCRPI u "
+ "where u.mycoreID = :mcrId "
+ "and u.type = :type "
+ "and (u.additional != '' OR u.additional IS NOT NULL)"
+ "and u.service = :service"),
@NamedQuery(name = "Get.PI.Additional",
query = "select u from MCRPI u "
+ "where u.mycoreID = :mcrId "
+ "and (u.additional = :additional OR (u.additional IS NULL AND :additional IS NULL))"
+ "and u.service = :service"),
@NamedQuery(name = "Get.PI.Unregistered",
query = "select u from MCRPI u "
+ "where u.type = :type "
+ "and u.registered is null"),
@NamedQuery(name = "Update.PI.Registered.Date",
query = "update MCRPI u "
+ "set u.registered = :date "
+ "where u.id = :id")
})
@Table(
uniqueConstraints = {
@UniqueConstraint(columnNames = { "identifier", "type" }),
@UniqueConstraint(columnNames = { "mycoreID", "service", "additional" })
},
indexes = {
@Index(name = "Identifier", columnList = "identifier"),
@Index(name = "MCRIdentifierService", columnList = "mycoreID, service")
})
public class MCRPI implements org.mycore.pi.MCRPIRegistrationInfo {
private static final long serialVersionUID = 234168232792525611L;
// unique constraint für identifier type
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false)
private String identifier;
@Column(nullable = false)
private String type;
@Column(nullable = false)
private String mycoreID;
@Column(length = 4096)
private String additional;
@Column(length = 128)
private String service;
@Column(nullable = false)
private Date created;
@Column()
private Date registrationStarted;
@Column()
private Date registered;
@Column(nullable = false)
private String mcrVersion;
//TODO: nullable since MCR-1393
@Column
private int mcrRevision;
private MCRPI() {
}
public MCRPI(String identifier, String type, String mycoreID, String additional, String service,
MCRPIServiceDates dates) {
this();
this.identifier = identifier;
this.type = type;
this.mycoreID = mycoreID;
this.additional = additional;
this.service = service;
this.registered = dates.registered();
this.registrationStarted = dates.registrationStarted();
//TODO: disabled by MCR-1393
// this.mcrRevision = MCRCoreVersion.getRevision();
this.mcrVersion = MCRCoreVersion.getVersion();
this.created = new Date();
}
public Date getRegistrationStarted() {
return registrationStarted;
}
public void setRegistrationStarted(Date registrationStarted) {
this.registrationStarted = registrationStarted;
}
@Override
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
@Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String getMycoreID() {
return mycoreID;
}
public void setMycoreID(String mycoreID) {
this.mycoreID = mycoreID;
}
@Override
public String getAdditional() {
return additional;
}
public void setAdditional(String additional) {
this.additional = additional;
}
@Override
public String getMcrVersion() {
return mcrVersion;
}
public void setMcrVersion(String mcrVersion) {
this.mcrVersion = mcrVersion;
}
@Override
public int getMcrRevision() {
return mcrRevision;
}
public void setMcrRevision(int mcrRevision) {
this.mcrRevision = mcrRevision;
}
@Override
public Date getRegistered() {
return registered;
}
public void setRegistered(Date registered) {
this.registered = registered;
}
@Override
public Date getCreated() {
return created;
}
@Override
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public int getId() {
return id;
}
}
| 6,734 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIdentifierXSLUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/frontend/MCRIdentifierXSLUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.frontend;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.output.DOMOutputter;
import org.mycore.access.MCRAccessManager;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.pi.MCRPIManager;
import org.mycore.pi.MCRPIService;
import org.mycore.pi.MCRPIServiceManager;
import org.mycore.pi.MCRPersistentIdentifier;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import org.w3c.dom.NodeList;
public class MCRIdentifierXSLUtils {
private static final Logger LOGGER = LogManager.getLogger();
public static boolean hasIdentifierCreated(String service, String id, String additional) {
MCRPIService<MCRPersistentIdentifier> registrationService = MCRPIServiceManager
.getInstance().getRegistrationService(service);
return registrationService.isCreated(MCRObjectID.getInstance(id), additional);
}
public static boolean hasIdentifierRegistrationStarted(String service, String id, String additional) {
MCRPIService<MCRPersistentIdentifier> registrationService = MCRPIServiceManager
.getInstance().getRegistrationService(service);
return registrationService.hasRegistrationStarted(MCRObjectID.getInstance(id), additional);
}
public static boolean hasIdentifierRegistered(String service, String id, String additional) {
MCRPIService<MCRPersistentIdentifier> registrationService = MCRPIServiceManager
.getInstance().getRegistrationService(service);
return registrationService.isRegistered(MCRObjectID.getInstance(id), additional);
}
public static boolean hasManagedPI(String objectID) {
return MCRPIManager.getInstance()
.getRegistered(MCRMetadataManager.retrieveMCRObject(MCRObjectID.getInstance(objectID))).size() > 0;
}
public static boolean isManagedPI(String pi, String id) {
return MCRPIManager.getInstance().getInfo(pi).stream().anyMatch(info -> info.getMycoreID()
.equals(id));
}
/**
* Gets all available services which are configured.
* e.g.
* <ul>
* <li><service id="service1" inscribed="false" permission="true" type="urn" /></li>
* <li><service id="service2" inscribed="true" permission="false" type="doi" /></li>
* </ul>
*
* @param objectID the object
* @return a Nodelist
*/
public static NodeList getPIServiceInformation(String objectID) throws JDOMException {
Element e = new Element("list");
MCRBase obj = MCRMetadataManager.retrieve(MCRObjectID.getInstance(objectID));
MCRPIServiceManager.getInstance().getServiceList()
.stream()
.map((rs -> {
Element service = new Element("service");
service.setAttribute("id", rs.getServiceID());
// Check if the inscriber of this service can read a PI
try {
if (rs.getMetadataService().getIdentifier(obj, "").isPresent()) {
service.setAttribute("inscribed", "true");
} else {
service.setAttribute("inscribed", "false");
}
} catch (MCRPersistentIdentifierException e1) {
LOGGER.warn("Error happened while try to read PI from object: {}", objectID, e1);
service.setAttribute("inscribed", "false");
}
// rights
String permission = "register-" + rs.getServiceID();
boolean canRegister = MCRAccessManager.checkPermission(objectID, "writedb") &&
MCRAccessManager.checkPermission(obj.getId(), permission);
service.setAttribute("permission", Boolean.toString(canRegister));
// add the type
service.setAttribute("type", rs.getType());
return service;
}))
.forEach(e::addContent);
return new DOMOutputter().output(e).getElementsByTagName("service");
}
}
| 4,998 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPersistentIdentifierRegistrationResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/frontend/resources/MCRPersistentIdentifierRegistrationResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.frontend.resources;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRException;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.pi.MCRPIManager;
import org.mycore.pi.MCRPIRegistrationInfo;
import org.mycore.pi.MCRPIService;
import org.mycore.pi.MCRPIServiceManager;
import org.mycore.pi.MCRPersistentIdentifier;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import org.mycore.pi.frontend.model.MCRPIErrorJSON;
import org.mycore.pi.frontend.model.MCRPIListJSON;
import org.mycore.pi.frontend.model.MCRPIRegistrationJSON;
import com.google.gson.Gson;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("pi/registration")
public class MCRPersistentIdentifierRegistrationResource {
public static final int COUNT_LIMIT = 100;
private static final Logger LOGGER = LogManager.getLogger();
@GET
@Path("type/{type}")
@Produces(MediaType.APPLICATION_JSON)
public Response listByType(@PathParam("type") String type, @DefaultValue("0") @QueryParam("from") int from,
@DefaultValue("50") @QueryParam("size") int size) {
Response errorResponse = validateParameters(from, size);
if (errorResponse != null) {
return errorResponse;
}
List<MCRPIRegistrationInfo> mcrpiRegistrationInfos = MCRPIManager.getInstance().getList(type,
from, size);
return Response.status(Response.Status.OK)
.entity(new Gson().toJson(new MCRPIListJSON(type, from, size,
MCRPIManager.getInstance().getCount(type), mcrpiRegistrationInfos)))
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response list(@DefaultValue("0") @QueryParam("from") int from,
@DefaultValue("50") @QueryParam("size") int size) {
Response errorResponse = validateParameters(from, size);
if (errorResponse != null) {
return errorResponse;
}
List<MCRPIRegistrationInfo> mcrpiRegistrationInfos = MCRPIManager.getInstance().getList(from,
size);
return Response.status(Response.Status.OK)
.entity(new Gson().toJson(new MCRPIListJSON(null, from, size,
MCRPIManager.getInstance().getCount(), mcrpiRegistrationInfos)))
.build();
}
@GET
@Path("service")
@Produces(MediaType.TEXT_PLAIN)
public Response listServices() {
return Response
.status(Response.Status.OK)
.entity(MCRPIServiceManager
.getInstance()
.getServiceIDList()
.stream()
.collect(Collectors.joining(",")))
.build();
}
@POST
@Path("service/{serviceName}/{mycoreId}")
@Produces(MediaType.APPLICATION_JSON)
public Response register(@PathParam("serviceName") String serviceName, @PathParam("mycoreId") String mycoreId,
@DefaultValue("") @QueryParam("additional") String additional) {
if (!MCRPIServiceManager.getInstance().getServiceIDList().contains(serviceName)) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(buildErrorJSON("No Registration Service found for " + serviceName)).build();
}
MCRPIService<MCRPersistentIdentifier> registrationService = MCRPIServiceManager
.getInstance().getRegistrationService(serviceName);
MCRObjectID mycoreIDObject;
try {
mycoreIDObject = MCRObjectID.getInstance(mycoreId);
} catch (MCRException e) {
LOGGER.error(e);
return Response.status(Response.Status.BAD_REQUEST)
.entity(buildErrorJSON("The provided id " + mycoreId + " seems to be invalid!", e)).build();
}
MCRPersistentIdentifier identifier;
MCRBase object = MCRMetadataManager.retrieve(mycoreIDObject);
try {
identifier = registrationService.register(object, additional, true);
} catch (MCRPersistentIdentifierException | ExecutionException | InterruptedException e) {
LOGGER.error("Error while registering PI:", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(buildErrorJSON("Error while register new identifier!", e)).build();
} catch (MCRAccessException e) {
LOGGER.error("Error while registering PI:", e);
return Response.status(Response.Status.FORBIDDEN)
.entity(buildErrorJSON("Error while register new identifier!", e)).build();
} catch (Throwable t) {
LOGGER.error("Error while registering PI:", t);
throw t;
}
return Response.status(Response.Status.CREATED).entity(buildIdentifierObject(identifier)).build();
}
private Response validateParameters(int from, int size) {
if (from < 0) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(buildErrorJSON("From must be positive (" + from + ")"))
.build();
}
if (size <= 0) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(buildErrorJSON("Count must be larger then 0 (" + size + ")"))
.build();
}
if (size > COUNT_LIMIT) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(
buildErrorJSON(String.format(Locale.ROOT, "Count can't be larger then %d (%d)", COUNT_LIMIT, size)))
.build();
}
return null;
}
private String buildErrorJSON(String message) {
return new Gson().toJson(new MCRPIErrorJSON(message));
}
private String buildErrorJSON(String message, Exception e) {
return new Gson().toJson(new MCRPIErrorJSON(message, e));
}
private String buildIdentifierObject(MCRPersistentIdentifier pi) {
return new Gson().toJson(new MCRPIRegistrationJSON(pi.asString()));
}
}
| 7,294 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPersistentIdentifierResolvingResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/frontend/resources/MCRPersistentIdentifierResolvingResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.frontend.resources;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import org.mycore.pi.MCRPIManager;
import com.google.gson.Gson;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("pi/resolve")
public class MCRPersistentIdentifierResolvingResource {
@GET
@Path("{identifier:.+}")
@Produces(MediaType.APPLICATION_JSON)
public Response resolve(@PathParam("identifier") String identifier) {
HashMap<String, List<String>> resolveMap = new HashMap<>();
MCRPIManager.getInstance().getResolvers().forEach(resolver -> MCRPIManager
.getInstance().get(identifier)
.forEach(mcrPersistentIdentifier -> resolveMap.put(resolver.getName(),
resolver.resolveSuppress(mcrPersistentIdentifier).collect(Collectors.toList()))));
return Response.ok().entity(new Gson().toJson(resolveMap)).build();
}
}
| 1,803 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIListJSON.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/frontend/model/MCRPIListJSON.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.frontend.model;
import java.util.List;
import org.mycore.pi.MCRPIRegistrationInfo;
public class MCRPIListJSON {
public String type;
public int from;
public int size;
public int count;
public List<MCRPIRegistrationInfo> list;
public MCRPIListJSON(String type, int from, int size, int count, List<MCRPIRegistrationInfo> list) {
this.type = type;
this.from = from;
this.size = size;
this.count = count;
this.list = list;
}
}
| 1,248 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIErrorJSON.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/frontend/model/MCRPIErrorJSON.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.frontend.model;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
public class MCRPIErrorJSON {
public String message;
public String stackTrace;
public String translatedAdditionalInformation;
public String code;
public MCRPIErrorJSON(String message) {
this(message, null);
}
public MCRPIErrorJSON(String message, Exception e) {
this.message = message;
if (e instanceof MCRPersistentIdentifierException identifierException) {
identifierException.getCode().ifPresent(code -> this.code = Integer.toHexString(code));
identifierException.getTranslatedAdditionalInformation()
.ifPresent(msg -> this.translatedAdditionalInformation = msg);
}
if (e != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
stackTrace = sw.toString();
}
}
}
| 1,786 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIRegistrationJSON.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/frontend/model/MCRPIRegistrationJSON.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.frontend.model;
public class MCRPIRegistrationJSON {
public String registeredIdentifier;
public MCRPIRegistrationJSON(String registeredIdentifier) {
this.registeredIdentifier = registeredIdentifier;
}
}
| 976 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPICommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/cli/MCRPICommands.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.cli;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessException;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRException;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.pi.MCRPIManager;
import org.mycore.pi.MCRPIMetadataService;
import org.mycore.pi.MCRPIRegistrationInfo;
import org.mycore.pi.MCRPIService;
import org.mycore.pi.MCRPIServiceDates;
import org.mycore.pi.MCRPIServiceManager;
import org.mycore.pi.MCRPersistentIdentifier;
import org.mycore.pi.MCRPersistentIdentifierEventHandler;
import org.mycore.pi.backend.MCRPI;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
import org.mycore.pi.urn.MCRDNBURN;
import jakarta.persistence.EntityManager;
@MCRCommandGroup(name = "PI Commands")
public class MCRPICommands {
private static final Logger LOGGER = LogManager.getLogger();
@MCRCommand(syntax = "add pi flags to all objects",
help = "Should only be used if you used mycore-pi pre 2016 lts!",
order = 10)
public static List<String> addFlagsToObjects() {
return MCRPIManager.getInstance().getList().stream()
.filter(registrationInfo -> {
String mycoreID = registrationInfo.getMycoreID();
MCRObjectID objectID = MCRObjectID.getInstance(mycoreID);
MCRBase base = MCRMetadataManager.retrieve(objectID);
return !MCRPIService.hasFlag(base, registrationInfo.getAdditional(), registrationInfo);
})
.map(MCRPIRegistrationInfo::getMycoreID)
.distinct()
.map(id -> "add pi flags to object " + id)
.collect(Collectors.toList());
}
@MCRCommand(syntax = "add pi flags to object {0}", help = "see add pi flags to all objects!", order = 20)
public static void addFlagToObject(String mycoreIDString) {
MCRObjectID objectID = MCRObjectID.getInstance(mycoreIDString);
MCRBase base = MCRMetadataManager.retrieve(objectID);
final List<MCRPIRegistrationInfo> pi = MCRPIManager.getInstance().getRegistered(base);
final boolean addedAFlag = pi.stream().anyMatch(registrationInfo -> {
if (!MCRPIService.hasFlag(base, registrationInfo.getAdditional(), registrationInfo)) {
LOGGER.info("Add PI-Flag to " + mycoreIDString);
MCRPIService.addFlagToObject(base, (MCRPI) registrationInfo);
return true;
}
return false;
});
if (addedAFlag) {
try {
MCRMetadataManager.update(base);
} catch (MCRAccessException e) {
throw new MCRException(e);
}
}
}
@MCRCommand(syntax = "migrate urn granular to service id {0}",
help = "Used to migrate urn granular to MyCoRe-PI. "
+
"{0} should be your granular service id.",
order = 30)
public static void migrateURNGranularToServiceID(String serviceID) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
MCRXMLMetadataManager.instance().listIDsOfType("derivate").forEach(derivateID -> {
MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivateID));
String urn = derivate.getDerivate().getURN();
if (urn != null) {
LOGGER.info("Found URN in :{}", derivateID);
MCRPI derivatePI = new MCRPI(urn, MCRDNBURN.TYPE, derivateID, "", serviceID,
new MCRPIServiceDates(new Date(), null));
if (MCRPIManager.getInstance().exist(derivatePI)) {
LOGGER.warn("PI-Entry for {} already exist!", urn);
} else {
em.persist(derivatePI);
derivate.getUrnMap().forEach((file, fileURN) -> {
MCRPI filePI = new MCRPI(fileURN, MCRDNBURN.TYPE, derivateID, file, serviceID,
new MCRPIServiceDates(new Date(), null));
if (MCRPIManager.getInstance().exist(filePI)) {
LOGGER.warn("PI-Entry for {} already exist!", fileURN);
} else {
em.persist(fileURN);
}
});
}
}
});
}
@MCRCommand(syntax = "try to control {0} with pi service {1}",
help = "This command tries to" +
" read a pi from the object {0} with the MetadataManager from the specified service {1}." +
" If the service configuration is right then the pi is under control of MyCoRe.",
order = 50)
public static void controlObjectWithService(String objectIDString, String serviceID)
throws MCRAccessException {
controlObjectWithServiceAndAdditional(objectIDString, serviceID, "");
}
@MCRCommand(syntax = "try to control {0} with pi service {1} with additional {2}",
help = "This command tries to" +
" read a pi from the object {0} with the MetadataManager from the specified service {1}." +
" If the service configuration is right then the pi is under control of MyCoRe.",
order = 40)
public static void controlObjectWithServiceAndAdditional(String objectIDString, String serviceID,
final String additional)
throws MCRAccessException {
String trimAdditional = additional != null ? additional.trim() : null;
MCRPIService<MCRPersistentIdentifier> service = MCRPIServiceManager
.getInstance().getRegistrationService(serviceID);
MCRPIMetadataService<MCRPersistentIdentifier> metadataManager = service.getMetadataService();
MCRObjectID objectID = MCRObjectID.getInstance(objectIDString);
MCRBase mcrBase = MCRMetadataManager.retrieve(objectID);
Optional<MCRPersistentIdentifier> identifier;
try {
identifier = metadataManager.getIdentifier(mcrBase, trimAdditional);
} catch (MCRPersistentIdentifierException e) {
LOGGER.info("Could not detect any identifier with service {}", serviceID, e);
return;
}
if (!identifier.isPresent()) {
LOGGER.info("Could not detect any identifier with service {}", serviceID);
return;
}
MCRPersistentIdentifier persistentIdentifier = identifier.get();
if (service.isRegistered(objectID, trimAdditional)) {
LOGGER.info("Already present in Database: {}", serviceID);
return;
}
Date now = new Date();
MCRPI mcrpi = service.insertIdentifierToDatabase(mcrBase, trimAdditional, persistentIdentifier,
new MCRPIServiceDates(now, now));
MCRPIService.addFlagToObject(mcrBase, mcrpi);
MCRMetadataManager.update(mcrBase);
LOGGER.info("{}:{} is now under control of {}", objectID, trimAdditional, serviceID);
}
@MCRCommand(syntax = "remove control {0} with pi service {1} with additional {2}",
help = "This commands removes the "
+ "pi control from the object {0}(object id) with the serivce {1}(service id) and the additional {2}",
order = 60)
public static void removeControlFromObject(String objectIDString, String serviceID, String additional)
throws MCRAccessException, MCRPersistentIdentifierException {
MCRObjectID objectID = MCRObjectID.getInstance(objectIDString);
MCRPI mcrpi = MCRPIManager.getInstance()
.get(serviceID, objectIDString, additional != null ? additional.trim() : null);
MCRPIManager.getInstance()
.delete(mcrpi.getMycoreID(), mcrpi.getAdditional(), mcrpi.getType(), mcrpi.getService());
MCRBase base = MCRMetadataManager.retrieve(objectID);
if (MCRPIService.removeFlagFromObject(base, mcrpi) == null) {
throw new MCRPersistentIdentifierException("Could not delete Flag of object (flag not found)!");
}
MCRMetadataManager.update(base);
}
@MCRCommand(syntax = "remove control {0} with pi service {1}",
help = "This commands removes the "
+ "pi control from the object {0}(object id) with the serivce {1}(service id)",
order = 70)
public static void removeControlFromObject(String objectIDString, String serviceID)
throws MCRAccessException, MCRPersistentIdentifierException {
removeControlFromObject(objectIDString, serviceID, null);
}
@MCRCommand(syntax = "update all PI of object {0}",
help = "Triggers the update method of every Object!",
order = 80)
public static void updateObject(String objectIDString) {
MCRObjectID objectID = MCRObjectID.getInstance(objectIDString);
MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
MCRPersistentIdentifierEventHandler.updateObject(object);
}
@MCRCommand(syntax = "create pi with {0} for object {1} with additional ({2})",
help = "Creates a persistent identifier with the pi service with the id {0} for the object {1}"
+ " with additional ({2}). Does nothing if the object already has a pi from the service {0}.",
order = 90)
public static void createPIForObjectIfNotExist(String serviceID, String objectIDString, String additional)
throws MCRAccessException, ExecutionException, MCRPersistentIdentifierException,
InterruptedException {
final MCRObjectID objectID = MCRObjectID.getInstance(objectIDString);
if (!MCRMetadataManager.exists(objectID)) {
LOGGER.error("Object {} does not exist!", objectID);
return;
}
MCRPIService<MCRPersistentIdentifier> registrationService = MCRPIServiceManager
.getInstance().getRegistrationService(serviceID);
if (registrationService.isCreated(objectID, "")) {
LOGGER.info("Object {} already has a DOI!", objectID);
}
final MCRBase object = MCRMetadataManager.retrieve(objectID);
final MCRPersistentIdentifier doi = registrationService.register(object, additional);
LOGGER.info("Registered pi with {}: {} for object {}", serviceID, doi.asString(), objectID);
}
@MCRCommand(syntax = "create pi with {0} for object {1}",
help = "Creates a persistent identifier with the pi service with the id {0} for the object {1}."
+ " Does nothing if the object already has a pi from the service {0}.",
order = 100)
public static void createPIForObjectIfNotExist(String serviceID, String objectIDString)
throws MCRAccessException, ExecutionException, MCRPersistentIdentifierException,
InterruptedException {
createPIForObjectIfNotExist(serviceID, objectIDString, "");
}
}
| 12,192 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPIHasRegisteredCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/access/facts/condition/MCRPIHasRegisteredCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.access.facts.condition;
import java.util.List;
import java.util.Optional;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.condition.fact.MCRStringCondition;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.pi.MCRPIManager;
import org.mycore.pi.MCRPIRegistrationInfo;
import org.mycore.pi.MCRPIServiceManager;
/**
* condition for fact-based access system,
* that checks if a persistent identifier was registered for the given object.
*
* @author Robert Stephan
*
*/
public class MCRPIHasRegisteredCondition extends MCRStringCondition {
private String idFact = "objid";
@Override
public void parse(Element xml) {
super.parse(xml);
this.idFact = Optional.ofNullable(xml.getAttributeValue("idfact")).orElse("objid");
}
@Override
public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) {
Optional<MCRObjectIDFact> oIdFact = facts.require(idFact);
if (oIdFact.isPresent()) {
MCRObjectID objectID = oIdFact.get().getValue();
if (objectID != null) {
boolean anyRegistered = MCRPIServiceManager.getInstance().getServiceList().stream()
.anyMatch(service -> {
final List<MCRPIRegistrationInfo> createdIdentifiers = MCRPIManager.getInstance()
.getCreatedIdentifiers(objectID, service.getType(), service.getServiceID());
return createdIdentifiers.stream()
.anyMatch(pid -> service.isRegistered(objectID, pid.getAdditional()));
});
//only positive facts are added to the facts holder
if (anyRegistered) {
MCRStringFact fact = new MCRStringFact(getFactName(), getTerm());
fact.setValue(Boolean.TRUE.toString());
facts.add(fact);
return Optional.of(fact);
}
}
}
return Optional.empty();
}
}
| 2,926 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREpicException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.handle;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
public class MCREpicException extends MCRPersistentIdentifierException {
private static final long serialVersionUID = 1L;
public MCREpicException(String message) {
super(message);
}
public MCREpicException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,133 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHandle.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/handle/MCRHandle.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.handle;
import java.util.Objects;
import org.mycore.pi.MCRPersistentIdentifier;
public class MCRHandle implements MCRPersistentIdentifier {
private final String prefix;
private final String suffix;
MCRHandle(String prefix, String suffix) {
Objects.requireNonNull(prefix);
Objects.requireNonNull(suffix);
if (prefix.isEmpty() || suffix.isEmpty()) {
throw new IllegalArgumentException("prefix and suffix need to be not empty: " + prefix + "/" + suffix);
}
this.prefix = prefix;
this.suffix = suffix;
}
MCRHandle(String str) {
this(str.split("/", 2)[0], str.split("/", 2)[1]);
}
@Override
public String toString() {
return prefix + "/" + suffix;
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
@Override
public String asString() {
return toString();
}
}
| 1,721 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHandleInfo.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/handle/MCRHandleInfo.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.handle;
public class MCRHandleInfo {
private Integer idx;
private String type;
private String data;
private String timestamp;
public Integer getIdx() {
return idx;
}
public void setIdx(Integer idx) {
this.idx = idx;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
return "MCRHandleInfo{" +
"idx=" + idx +
", type='" + type + '\'' +
", data='" + data + '\'' +
", timestamp='" + timestamp + '\'' +
'}';
}
}
| 1,701 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREpicService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.handle;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import org.jdom2.Document;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRContentTransformerFactory;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.pi.MCRPIJobService;
import org.mycore.pi.exceptions.MCRPersistentIdentifierException;
public class MCREpicService extends MCRPIJobService<MCRHandle> {
public static final String EPIC_KEY = "EPIC";
public static final String OBJECT_ID_KEY = "ObjectID";
/**
* The Username which will be used by the epic client
*/
@MCRProperty(name = "Username")
public String username;
/**
* The password which will be used by the epic client
*/
@MCRProperty(name = "Password")
public String password;
/**
* The url to the actual epic api endpoint e.g. https://epic.grnet.gr/api/v2/, http://pid.gwdg.de/
*/
@MCRProperty(name = "Endpoint")
public String endpoint;
/**
* This is a alternative to mcr.baseurl mostly for testing purposes
*/
@MCRProperty(name = "BaseURL", required = false)
public String baseURL;
/**
* This can be used to store metadata as a Handle Object. The Transformer will be used to convert the Object to an
* String.
*/
@MCRProperty(name = "Transformer", required = false)
public String transformerID = null;
/**
* The Type which should be used in the Handle Object.
*/
@MCRProperty(name = "MetadataType", required = false)
public String metadataType = null;
/**
* The Index which should be used in the handle object.
*/
@MCRProperty(name = "MetadataIndex", required = false)
public String metadataIndex = null;
public ConcurrentHashMap<String, ReentrantLock> idLockMap = new ConcurrentHashMap<>();
public MCREpicService() {
super("handle");
}
@Override
protected boolean validateRegistrationDocument(MCRBase obj, MCRHandle identifier, String additional) {
return true;
}
@Override
protected void deleteJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
String epic = parameters.get(EPIC_KEY);
try {
getClient().delete(new MCRHandle(epic));
} catch (IOException e) {
throw new MCRPersistentIdentifierException("Error while communicating with epic service", e);
}
}
@Override
protected void registerJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
String epic = parameters.get(EPIC_KEY);
String objId = parameters.get(OBJECT_ID_KEY);
createOrUpdate(epic, objId);
}
@Override
protected void updateJob(Map<String, String> parameters) throws MCRPersistentIdentifierException {
String epic = parameters.get(EPIC_KEY);
String objId = parameters.get(OBJECT_ID_KEY);
createOrUpdate(epic, objId);
}
private void createOrUpdate(String epic, String objId) throws MCRPersistentIdentifierException {
new ReentrantLock();
final MCRObjectID objectID = MCRObjectID.getInstance(objId);
if (!MCRMetadataManager.exists(objectID)) {
return;
}
validateJobUserRights(objectID);
final MCRHandle mcrHandle = new MCRHandle(epic);
final String urlForObject = getURLForObject(objId);
try {
final ArrayList<MCRHandleInfo> handleInfos = new ArrayList<>();
processMedataData(objectID, handleInfos);
ReentrantLock reentrantLock = idLockMap.computeIfAbsent(epic, (l) -> new ReentrantLock());
try {
reentrantLock.lock();
getClient().create(urlForObject, mcrHandle, handleInfos);
} finally {
reentrantLock.unlock();
}
} catch (IOException e) {
throw new MCRPersistentIdentifierException("Error while communicating with EPIC Service", e);
}
}
private void processMedataData(MCRObjectID objectID, ArrayList<MCRHandleInfo> handleInfos) throws IOException {
if (transformerID != null && metadataType != null && metadataIndex != null) {
final int index = Integer.parseInt(metadataIndex, 10);
final Document xml = MCRMetadataManager.retrieve(objectID).createXML();
final MCRContentTransformer transformer = MCRContentTransformerFactory.getTransformer(transformerID);
final MCRContent result = transformer.transform(new MCRJDOMContent(xml));
final byte[] bytes = result.asByteArray();
final String encodedData = Base64.getEncoder().encodeToString(bytes);
final MCRHandleInfo metadataInfo = new MCRHandleInfo();
metadataInfo.setIdx(index);
metadataInfo.setData(encodedData);
metadataInfo.setType(metadataType);
handleInfos.add(metadataInfo);
}
}
protected String getURLForObject(String objectId) {
String baseURL = this.baseURL != null ? this.baseURL : MCRFrontendUtil.getBaseURL();
return baseURL + "receive/" + objectId;
}
@Override
protected Optional<String> getJobInformation(Map<String, String> contextParameters) {
return Optional.empty();
}
@Override
protected HashMap<String, String> createJobContextParams(PiJobAction action, MCRBase obj, MCRHandle epic,
String additional) {
HashMap<String, String> contextParameters = new HashMap<>();
contextParameters.put(EPIC_KEY, epic.asString());
contextParameters.put(OBJECT_ID_KEY, obj.getId().toString());
return contextParameters;
}
private MCREpicClient getClient() {
return new MCREpicClient(username, password, endpoint);
}
}
| 7,125 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHandleParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/handle/MCRHandleParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.handle;
import java.util.Optional;
import org.mycore.pi.MCRPIParser;
public class MCRHandleParser implements MCRPIParser<MCRHandle> {
public static final String DIRECTORY_INDICATOR = "10.";
@Override
public Optional<MCRHandle> parse(String handle) {
String[] handleParts = handle.split("/", 2);
if (handleParts.length != 2) {
return Optional.empty();
}
String prefix = handleParts[0];
String suffix = handleParts[1];
if (suffix.length() == 0) {
return Optional.empty();
}
return Optional.of(new MCRHandle(prefix, suffix));
}
}
| 1,389 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREpicUnauthorizedException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicUnauthorizedException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.handle;
public class MCREpicUnauthorizedException extends MCREpicException {
private static final long serialVersionUID = 1L;
public MCREpicUnauthorizedException(String message) {
super(message);
}
public MCREpicUnauthorizedException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,086 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREpicClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pi/src/main/java/org/mycore/pi/handle/MCREpicClient.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.pi.handle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import com.google.gson.Gson;
/**
* Implementation for this api <a href="https://doc.pidconsortium.eu/docs/">https://doc.pidconsortium.eu/docs/</a>
*/
public class MCREpicClient {
private final String userName;
private final String password;
private final String baseURL; // e.g. https://epic.grnet.gr/api/v2/, http://pid.gwdg.de/
public MCREpicClient(String userName, String password, String baseURL) {
this.userName = userName;
this.password = password;
this.baseURL = baseURL;
}
public void delete(MCRHandle handle) throws MCREpicException, IOException {
final HttpDelete httpDelete = new HttpDelete(baseURL + "handles/" + handle.toString());
try (CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = httpClient.execute(httpDelete)) {
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_NO_CONTENT -> {
return;
}
case HttpStatus.SC_UNAUTHORIZED -> throw new MCREpicUnauthorizedException(
"Error while create:" + statusLine.getReasonPhrase());
default -> {
final String content = new String(entity.getContent().readAllBytes(), StandardCharsets.UTF_8);
throw new MCREpicException("Unknown error: " + statusLine.getStatusCode() + " - "
+ statusLine.getReasonPhrase() + " - " + content);
}
}
}
}
public void create(String url, MCRHandle handle, List<MCRHandleInfo> additionalInformation)
throws IOException, MCREpicException {
final HttpPut httpPut = new HttpPut(baseURL + "handles/" + handle.toString());
final MCRHandleInfo register = new MCRHandleInfo();
register.setType("URL");
register.setData(url);
final String handleInfoStr = new Gson()
.toJson(Stream.concat(Stream.of(register), additionalInformation.stream()).collect(Collectors.toList()));
httpPut.setEntity(new StringEntity(handleInfoStr));
httpPut.setHeader("Content-Type", "application/json");
try (CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = httpClient.execute(httpPut)) {
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_CREATED, HttpStatus.SC_NO_CONTENT -> {
return;
}
case HttpStatus.SC_PRECONDITION_FAILED -> throw new MCREpicException(
"The Precondition failed, which means the handle already exist!");
case HttpStatus.SC_UNAUTHORIZED -> throw new MCREpicUnauthorizedException(
"Error while create:" + statusLine.getReasonPhrase());
default -> {
final String content = new String(entity.getContent().readAllBytes(), StandardCharsets.UTF_8);
throw new MCREpicException("Unknown error: " + statusLine.getStatusCode() + " - "
+ statusLine.getReasonPhrase() + " - " + content);
}
}
}
}
public List<MCRHandleInfo> get(MCRHandle hdl) throws IOException, MCREpicException {
try (CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = httpClient
.execute(new HttpGet(baseURL + "handles/" + hdl.toString()))) {
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
try (InputStream content = entity.getContent();
Reader reader = new InputStreamReader(content, StandardCharsets.UTF_8)) {
final Gson gson = new Gson();
final MCRHandleInfo[] handleInfos = gson.fromJson(reader, MCRHandleInfo[].class);
return Arrays.asList(handleInfos);
}
}
case HttpStatus.SC_UNAUTHORIZED -> throw new MCREpicUnauthorizedException(
"Error while listIds:" + statusLine.getReasonPhrase());
default -> throw new MCREpicException("Error while listIds" + statusLine.getReasonPhrase());
}
}
}
public List<MCRHandle> listIds(String prefix) throws IOException, MCREpicException {
try (CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = httpClient
.execute(new HttpGet(baseURL + "handles/" + prefix + "/"))) {
final String prefix2 = prefix + "/";
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK -> {
try (InputStream content = entity.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(content, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(inputStreamReader)) {
return br.lines().map(prefix2::concat).map(MCRHandle::new).collect(Collectors.toList());
}
}
case HttpStatus.SC_UNAUTHORIZED -> throw new MCREpicUnauthorizedException(
"Error while listIds:" + statusLine.getReasonPhrase());
default -> throw new MCREpicException("Error while listIds" + statusLine.getReasonPhrase());
}
}
}
private CloseableHttpClient getHttpClient() {
return HttpClientBuilder.create().setDefaultCredentialsProvider(getCredentialsProvider()).build();
}
private BasicCredentialsProvider getCredentialsProvider() {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (userName != null && !userName.isEmpty() && password != null && !password.isEmpty()) {
credentialsProvider.setCredentials(AuthScope.ANY, getCredentials());
}
return credentialsProvider;
}
private UsernamePasswordCredentials getCredentials() {
return new UsernamePasswordCredentials(this.userName, this.password);
}
}
| 8,320 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREnableTransactionFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCREnableTransactionFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
@Priority(Priorities.USER - 500)
public class MCREnableTransactionFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
requestContext.setProperty(MCRTransactionFilter.PROP_REQUIRE_TRANSACTION, true);
}
}
| 1,222 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNormalizeMCRObjectIDsFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRNormalizeMCRObjectIDsFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.net.URI;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.idmapper.MCRIDMapper;
import jakarta.annotation.Priority;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import jakarta.ws.rs.ext.Provider;
/**
* This prematching filter checks the given MCRObjectIDs in an REST API call beginning with /objects,
* normalizes them and sends a redirect if necessary.
*
* @author Robert Stephan
*
*/
@Provider
@PreMatching
@Priority(Priorities.AUTHORIZATION - 10)
public class MCRNormalizeMCRObjectIDsFilter implements ContainerRequestFilter {
@Context
ResourceInfo resourceInfo;
@Context
HttpServletResponse response;
private MCRIDMapper mcrIdMapper = MCRConfiguration2
.<MCRIDMapper>getInstanceOf(MCRIDMapper.MCR_PROPERTY_CLASS).get();
@Override
public void filter(ContainerRequestContext requestContext) {
UriInfo uriInfo = requestContext.getUriInfo();
String path = uriInfo.getPath().toString();
String[] pathParts = path.split("/", -1);
final int mcrIdPos = 1;
final int derIdPos = 3;
if (pathParts.length <= mcrIdPos || !"objects".equals(pathParts[mcrIdPos - 1])) {
return;
}
try {
String mcrid = pathParts[mcrIdPos];
String mcridExtension = getExtension(mcrid);
mcrid = mcrid.substring(0, mcrid.length() - mcridExtension.length());
Optional<MCRObjectID> optObjId = mcrIdMapper.mapMCRObjectID(mcrid);
if (optObjId.isEmpty()) {
throw new NotFoundException("No unique MyCoRe Object ID found for query " + mcrid);
}
pathParts[mcrIdPos] = optObjId.get().toString() + mcridExtension;
if (optObjId.isPresent() && pathParts.length > derIdPos && pathParts[derIdPos - 1].equals("derivates")) {
String derid = pathParts[derIdPos];
String deridExtension = getExtension(derid);
derid = derid.substring(0, derid.length() - deridExtension.length());
Optional<MCRObjectID> optDerId = mcrIdMapper.mapMCRDerivateID(optObjId.get(), derid);
if (optDerId.isEmpty()) {
throw new NotFoundException("No unique MyCoRe Derivate ID found for query " + derid);
}
pathParts[derIdPos] = optDerId.get().toString() + deridExtension;
}
} catch (MCRException ex) {
throw new BadRequestException("Could not detect MyCoRe ID", ex);
}
String newPath = StringUtils.join(pathParts, "/");
if (!newPath.equals(path)) {
String queryString = uriInfo.getRequestUri().getQuery();
URI uri = uriInfo.getBaseUri().resolve(queryString == null ? newPath : newPath + "?" + queryString);
requestContext.abortWith(Response.temporaryRedirect(uri).build());
}
}
private static String getExtension(String mcrid) {
if (mcrid.endsWith(".xml")) {
return ".xml";
}
if (mcrid.endsWith(".json")) {
return ".json";
}
return "";
}
}
| 4,496 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRemoveMsgBodyFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRRemoveMsgBodyFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.Provider;
/**
* Removed request message body if {@link #IGNORE_MESSAGE_BODY_HEADER} is set.
*
* Some user agent may set a {@link HttpHeaders#CONTENT_LENGTH} header, even if no message body was send.
* This filter removes Entity and the <code>Content-Length</code> and <code>Transfer-Encoding</code> header.
*/
@Priority(Priorities.HEADER_DECORATOR)
@Provider
public class MCRRemoveMsgBodyFilter implements ContainerRequestFilter {
public static final String IGNORE_MESSAGE_BODY_HEADER = "X-MCR-Ignore-Message-Body";
private static final Logger LOGGER = LogManager.getLogger();
@Override
public void filter(ContainerRequestContext requestContext) {
MultivaluedMap<String, String> headers = requestContext.getHeaders();
if (headers.containsKey(IGNORE_MESSAGE_BODY_HEADER)) {
LOGGER.info("Found {} header. Remove request message body.", IGNORE_MESSAGE_BODY_HEADER);
headers.remove(IGNORE_MESSAGE_BODY_HEADER);
headers.remove(HttpHeaders.CONTENT_LENGTH);
headers.remove("Transfer-Encoding");
requestContext.setEntityStream(null);
}
}
}
| 2,272 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRContentNegotiationViaExtensionFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRContentNegotiationViaExtensionFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;
import org.glassfish.jersey.server.filter.UriConnegFilter;
import org.mycore.common.config.MCRConfiguration2;
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.ext.Provider;
/**
* This filter uses Jersey's default implementation of UriConnectFilter to set
* the content headers by file extension.
*
* It is preconfigured for the extensions (*.json, *.xml) and ignores ressources
* behind REST-API path /contents/ since there is the possibility that a valid
* file extension (*.xml) will be removed through this filter by mistake
*
* @author Robert Stephan
*
*/
@Provider
@PreMatching
@Priority(Priorities.HEADER_DECORATOR - 10)
public class MCRContentNegotiationViaExtensionFilter implements ContainerRequestFilter {
private static Pattern P_URI = Pattern.compile(MCRConfiguration2.getStringOrThrow(
"MCR.RestAPI.V2.ContentNegotiationViaExtensionFilter.RegEx"));
private static final Map<String, MediaType> MEDIA_TYPE_MAPPINGS = Map.ofEntries(
Map.entry("json", MediaType.APPLICATION_JSON_TYPE),
Map.entry("xml", MediaType.APPLICATION_XML_TYPE),
Map.entry("rdf", MediaType.valueOf("application/rdf+xml")));
private UriConnegFilter uriConnegFilter = new UriConnegFilter(MEDIA_TYPE_MAPPINGS, Map.of());
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (P_URI.matcher(requestContext.getUriInfo().getPath()).matches()) {
uriConnegFilter.filter(requestContext);
}
}
}
| 2,582 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTransactionFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRTransactionFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import jakarta.annotation.Priority;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
@Priority(Priorities.USER)
public class MCRTransactionFilter implements ContainerRequestFilter {
public static final String PROP_REQUIRE_TRANSACTION = "mcr:jpaTrans";
public static final Logger LOGGER = LogManager.getLogger();
@Override
public void filter(ContainerRequestContext requestContext) {
if (MCRSessionMgr.isLocked()) {
return;
}
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
if (MCRTransactionHelper.isTransactionActive()) {
LOGGER.debug("Filter scoped JPA transaction is active.");
if (MCRTransactionHelper.transactionRequiresRollback()) {
try {
MCRTransactionHelper.rollbackTransaction();
} finally {
throw new InternalServerErrorException("Transaction rollback was required.");
}
}
MCRTransactionHelper.commitTransaction();
}
if (Boolean.TRUE.equals(requestContext.getProperty(PROP_REQUIRE_TRANSACTION))) {
LOGGER.debug("Starting user JPA transaction.");
MCRTransactionHelper.beginTransaction();
}
}
}
| 2,377 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestFeature.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRRestFeature.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.feature.MCRJerseyDefaultFeature;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.FeatureContext;
import jakarta.ws.rs.ext.Provider;
/**
* Jersey configuration
* @author Matthias Eichner
*
* @see MCRJerseyDefaultFeature
*
*/
@Provider
public class MCRRestFeature extends MCRJerseyDefaultFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
Class<?> resourceClass = resourceInfo.getResourceClass();
Method resourceMethod = resourceInfo.getResourceMethod();
if (requiresTransaction(resourceClass, resourceMethod)) {
context.register(MCREnableTransactionFilter.class);
}
super.configure(resourceInfo, context);
}
/**
* Checks if the class/method is annotated by {@link MCRRequireTransaction}.
*
* @param resourceClass the class to check
* @param resourceMethod the method to check
* @return true if one ore both is annotated and requires transaction
*/
protected boolean requiresTransaction(Class<?> resourceClass, Method resourceMethod) {
return resourceClass.getAnnotation(MCRRequireTransaction.class) != null
|| resourceMethod.getAnnotation(MCRRequireTransaction.class) != null;
}
@Override
protected List<String> getPackages() {
return Stream.concat(
MCRConfiguration2.getString("MCR.RestAPI.Resource.Packages").map(MCRConfiguration2::splitValue)
.orElse(Stream.empty()),
MCRConfiguration2.getString("MCR.RestAPI.V2.Resource.Packages").map(MCRConfiguration2::splitValue)
.orElse(Stream.empty()))
.collect(Collectors.toList());
}
@Override
protected void registerSessionHookFilter(FeatureContext context) {
// don't register transaction filter, is already implemented by MCRSessionFilter
}
@Override
protected void registerTransactionFilter(FeatureContext context) {
// don't register transaction filter, is already implemented by MCRSessionFilter
}
@Override
protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) {
if (resourceClass.getPackageName().contains(".v1")) {
context.register(org.mycore.restapi.v1.MCRRestAuthorizationFilter.class);
} else {
context.register(org.mycore.restapi.v2.MCRRestAuthorizationFilter.class);
}
super.registerAccessFilter(context, resourceClass, resourceMethod);
}
}
| 3,584 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNoFormDataPutFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRNoFormDataPutFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import jakarta.annotation.Priority;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.ext.Provider;
/**
* Aborts with <code>400</code> if a PUT request contains form data.
*/
@Priority(Priorities.USER)
@Provider
public class MCRNoFormDataPutFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
if (requestContext.getMethod().equals(HttpMethod.PUT) && requestContext.getMediaType() != null
&& requestContext.getMediaType().isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
throw new BadRequestException("Cannot PUT form data on this resource.");
}
}
}
| 1,652 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJerseyRestApp.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRJerseyRestApp.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import org.apache.logging.log4j.LogManager;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.access.MCRRequestScopeACLFilter;
public abstract class MCRJerseyRestApp extends ResourceConfig {
protected MCRJerseyRestApp() {
super();
initAppName();
property(ServerProperties.APPLICATION_NAME, getApplicationName());
String[] restPackages = getRestPackages();
packages(restPackages);
property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true);
register(MCRSessionFilter.class);
register(MCRTransactionFilter.class);
register(MultiPartFeature.class);
register(MCRRestFeature.class);
register(MCRCORSResponseFilter.class);
register(MCRRequestScopeACLFilter.class);
register(MCRIgnoreClientAbortInterceptor.class);
}
protected void initAppName() {
setApplicationName(MCRConfiguration2.getString("MCR.NameOfProject").orElse("MyCoRe") + " REST-API "
+ getVersion());
LogManager.getLogger().info("Initiialize {}", getApplicationName());
}
protected abstract String getVersion();
protected abstract String[] getRestPackages();
}
| 2,147 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDropSessionFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRDropSessionFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
@Priority(Priorities.USER + 1)
/**
* Drops and closes MCRSession if Resource produces Server-Sent Events.
*/
public class MCRDropSessionFilter implements ContainerRequestFilter {
@Context
ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) {
Produces produces = resourceInfo.getResourceMethod().getAnnotation(Produces.class);
if (produces == null || Stream.of(produces.value()).noneMatch(MediaType.SERVER_SENT_EVENTS::equals)) {
return;
}
LogManager.getLogger().info("Has Session? {}", MCRSessionMgr.hasCurrentSession());
if (MCRSessionMgr.hasCurrentSession()) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
if (MCRTransactionHelper.isTransactionActive()) {
MCRTransactionHelper.commitTransaction();
}
MCRSessionMgr.releaseCurrentSession();
currentSession.close();
}
}
}
| 2,280 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSessionFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRSessionFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.io.output.ProxyOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.jersey.MCRJWTUtil;
import org.mycore.frontend.jersey.resources.MCRJWTResource;
import org.mycore.restapi.v1.MCRRestAPIAuthentication;
import org.mycore.restapi.v1.utils.MCRRestAPIUtil;
import org.mycore.user2.MCRRealm;
import org.mycore.user2.MCRUser;
import org.mycore.user2.MCRUserManager;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.annotation.Priority;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.CacheControl;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import jakarta.ws.rs.ext.Provider;
import jakarta.ws.rs.ext.RuntimeDelegate;
@Provider
@Priority(Priorities.AUTHENTICATION)
public class MCRSessionFilter implements ContainerRequestFilter, ContainerResponseFilter {
public static final Logger LOGGER = LogManager.getLogger();
private static final String PROP_RENEW_JWT = "mcr:renewJWT";
private static final List<String> ALLOWED_JWT_SESSION_ATTRIBUTES = MCRConfiguration2
.getString("MCR.RestAPI.JWT.AllowedSessionAttributePrefixes").stream()
.flatMap(MCRConfiguration2::splitValue)
.collect(Collectors.toList());
@Context
HttpServletRequest httpServletRequest;
@Context
Application app;
/**
* If request was authenticated via JSON Web Token add a new token if <code>aud</code> was
* {@link MCRRestAPIAuthentication#AUDIENCE}.
*
* If the response has a status code that represents a client error (4xx), the JSON Web Token is ommited.
* If the response already has a JSON Web Token no changes are made.
*/
private static void addJWTToResponse(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
boolean renewJWT = Optional.ofNullable(requestContext.getProperty(PROP_RENEW_JWT))
.map(Boolean.class::cast)
.orElse(Boolean.FALSE);
Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION))
.filter(s -> s.startsWith("Bearer "))
.filter(s -> !responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.CLIENT_ERROR))
.filter(s -> responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null)
.map(h -> renewJWT ? ("Bearer " + MCRRestAPIAuthentication
.getToken(currentSession, currentSession.getCurrentIP())
.orElseThrow(() -> new InternalServerErrorException("Could not get JSON Web Token"))) : h)
.ifPresent(h -> {
responseContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, h);
//Authorization header may never be cached in public caches
Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.CACHE_CONTROL))
.map(RuntimeDelegate.getInstance()
.createHeaderDelegate(CacheControl.class)::fromString)
.filter(cc -> !cc.isPrivate())
.ifPresent(cc -> {
cc.setPrivate(true);
responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
});
});
}
@Override
public void filter(ContainerRequestContext requestContext) {
LOGGER.debug("Filter start.");
boolean isSecure = requestContext.getSecurityContext().isSecure();
if (MCRSessionMgr.hasCurrentSession()) {
throw new InternalServerErrorException("Session is already attached.");
}
MCRSessionMgr.unlock();
MCRSession currentSession = MCRSessionMgr.getCurrentSession(); //bind to this request
currentSession.setCurrentIP(MCRFrontendUtil.getRemoteAddr(httpServletRequest));
MCRTransactionHelper.beginTransaction();
//3 cases for authentication
Optional<MCRUserInformation> userInformation = Optional.empty();
String authorization = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
//1. no authentication
if (authorization == null) {
LOGGER.debug("No 'Authorization' header");
return;
}
//2. Basic Authentification
String basicPrefix = "Basic ";
if (authorization.startsWith(basicPrefix)) {
LOGGER.debug("Using 'Basic' authentication.");
byte[] encodedAuth = authorization.substring(basicPrefix.length()).trim()
.getBytes(StandardCharsets.ISO_8859_1);
String userPwd = new String(Base64.getDecoder().decode(encodedAuth), StandardCharsets.ISO_8859_1);
if (userPwd.contains(":") && userPwd.length() > 1) {
String[] upSplit = userPwd.split(":");
String username = upSplit[0];
String password = upSplit[1];
userInformation = Optional.ofNullable(MCRUserManager.checkPassword(username, password))
.map(MCRUserInformation.class::cast)
.map(Optional::of)
.orElseThrow(() -> {
LinkedHashMap<String, String> attrs = new LinkedHashMap<>();
attrs.put("error", "invalid_login");
attrs.put("error_description", "Wrong login or password.");
return new NotAuthorizedException(Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE,
MCRRestAPIUtil.getWWWAuthenticateHeader(null, attrs, app))
.build());
});
}
}
//3. JWT
String bearerPrefix = "Bearer ";
if (authorization.startsWith(bearerPrefix)) {
LOGGER.debug("Using 'JSON Web Token' authentication.");
//get JWT
String token = authorization.substring(bearerPrefix.length()).trim();
//validate against secret
try {
DecodedJWT jwt = JWT.require(MCRJWTUtil.getJWTAlgorithm())
.build()
.verify(token);
//validate ip
checkIPClaim(jwt.getClaim(MCRJWTUtil.JWT_CLAIM_IP), MCRFrontendUtil.getRemoteAddr(httpServletRequest));
//validate in audience
Optional<String> audience = jwt.getAudience().stream()
.filter(s -> MCRJWTResource.AUDIENCE.equals(s) || MCRRestAPIAuthentication.AUDIENCE.equals(s))
.findAny();
if (audience.isPresent()) {
switch (audience.get()) {
case MCRJWTResource.AUDIENCE -> MCRJWTResource.validate(token);
case MCRRestAPIAuthentication.AUDIENCE -> {
requestContext.setProperty(PROP_RENEW_JWT, true);
MCRRestAPIAuthentication.validate(token);
}
default -> LOGGER.warn("Cannot validate JWT for '{}' audience.", audience.get());
}
}
userInformation = Optional.of(new MCRJWTUserInformation(jwt));
if (!ALLOWED_JWT_SESSION_ATTRIBUTES.isEmpty()) {
for (Map.Entry<String, Claim> entry : jwt.getClaims().entrySet()) {
if (entry.getKey().startsWith(MCRJWTUtil.JWT_SESSION_ATTRIBUTE_PREFIX)) {
final String key = entry.getKey()
.substring(MCRJWTUtil.JWT_SESSION_ATTRIBUTE_PREFIX.length());
for (String prefix : ALLOWED_JWT_SESSION_ATTRIBUTES) {
if (key.startsWith(prefix)) {
currentSession.put(key, entry.getValue().asString());
break;
}
}
}
}
}
} catch (JWTVerificationException e) {
LOGGER.error(e.getMessage());
LinkedHashMap<String, String> attrs = new LinkedHashMap<>();
attrs.put("error", "invalid_token");
attrs.put("error_description", e.getMessage());
throw new NotAuthorizedException(e.getMessage(), e,
MCRRestAPIUtil.getWWWAuthenticateHeader("Bearer", attrs, app));
}
}
if (userInformation.isEmpty()) {
LOGGER.warn(() -> "Unsupported " + HttpHeaders.AUTHORIZATION + " header: " + authorization);
}
userInformation
.ifPresent(ui -> {
currentSession.setUserInformation(ui);
requestContext.setSecurityContext(new MCRRestSecurityContext(ui, isSecure));
});
LOGGER.info("user detected: " + currentSession.getUserInformation().getUserID());
}
private static void checkIPClaim(Claim ipClaim, String remoteAddr) {
try {
if (ipClaim.isNull() || !MCRFrontendUtil.isIPAddrAllowed(ipClaim.asString(), remoteAddr)) {
throw new JWTVerificationException(
"The Claim '" + MCRJWTUtil.JWT_CLAIM_IP + "' value doesn't match the required one.");
}
} catch (UnknownHostException e) {
throw new JWTVerificationException(
"The Claim '" + MCRJWTUtil.JWT_CLAIM_IP + "' value doesn't match the required one.", e);
}
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
LOGGER.debug("ResponseFilter start");
try {
MCRSessionMgr.unlock();
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
if (responseContext.getStatus() == Response.Status.FORBIDDEN.getStatusCode()
&& isUnAuthorized(requestContext)) {
LOGGER.debug("Guest detected, change response from FORBIDDEN to UNAUTHORIZED.");
responseContext.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
responseContext.getHeaders().putSingle(HttpHeaders.WWW_AUTHENTICATE,
MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app));
}
if (responseContext.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()
&& doNotWWWAuthenticate(requestContext)) {
LOGGER.debug("Remove {} header.", HttpHeaders.WWW_AUTHENTICATE);
responseContext.getHeaders().remove(HttpHeaders.WWW_AUTHENTICATE);
}
addJWTToResponse(requestContext, responseContext);
if (responseContext.hasEntity()) {
responseContext.setEntityStream(new ProxyOutputStream(responseContext.getEntityStream()) {
@Override
public void close() throws IOException {
LOGGER.debug("Closing EntityStream");
try {
super.close();
} finally {
closeSessionIfNeeded();
LOGGER.debug("Closing EntityStream done");
}
}
});
} else {
LOGGER.debug("No Entity in response, closing MCRSession");
closeSessionIfNeeded();
}
} finally {
LOGGER.debug("ResponseFilter stop");
}
}
private static boolean isUnAuthorized(ContainerRequestContext requestContext) {
return requestContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null;
}
//returns true for Ajax-Requests or requests for embedded images
private static boolean doNotWWWAuthenticate(ContainerRequestContext requestContext) {
return !"ServiceWorker".equals(requestContext.getHeaderString("X-Requested-With")) &&
("XMLHttpRequest".equals(requestContext.getHeaderString("X-Requested-With")) ||
requestContext.getAcceptableMediaTypes()
.stream()
.findFirst()
.filter(m -> "image".equals(m.getType()))
.isPresent());
}
private static void closeSessionIfNeeded() {
if (MCRSessionMgr.hasCurrentSession()) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
try {
if (MCRTransactionHelper.isTransactionActive()) {
LOGGER.debug("Active MCRSession and JPA-Transaction found. Clearing up");
if (MCRTransactionHelper.transactionRequiresRollback()) {
MCRTransactionHelper.rollbackTransaction();
} else {
MCRTransactionHelper.commitTransaction();
}
} else {
LOGGER.debug("Active MCRSession found. Clearing up");
}
} finally {
MCRSessionMgr.releaseCurrentSession();
currentSession.close();
LOGGER.debug("Session closed.");
}
}
}
private static class MCRJWTUserInformation implements MCRUserInformation {
private final DecodedJWT jwt;
MCRJWTUserInformation(DecodedJWT token) {
this.jwt = token;
}
@Override
public String getUserID() {
return jwt.getSubject();
}
@Override
public boolean isUserInRole(String role) {
return Arrays.asList(jwt.getClaim("mcr:roles").asArray(String.class)).contains(role);
}
@Override
public String getUserAttribute(String attribute) {
return switch (attribute) {
case MCRUserInformation.ATT_REAL_NAME -> jwt.getClaim("name").asString();
case MCRUserInformation.ATT_EMAIL -> jwt.getClaim("email").asString();
case MCRRealm.USER_INFORMATION_ATTR -> {
if (getUserID().contains("@")) {
yield getUserID().substring(getUserID().lastIndexOf("@") + 1);
}
yield null;
}
default -> jwt.getClaim(MCRJWTUtil.JWT_USER_ATTRIBUTE_PREFIX + attribute).asString();
};
}
}
private static class MCRRestSecurityContext implements SecurityContext {
private final MCRUserInformation ui;
private final boolean isSecure;
private final Principal principal;
MCRRestSecurityContext(MCRUserInformation ui, boolean isSecure) {
this.principal = ui::getUserID;
this.ui = ui;
this.isSecure = isSecure;
}
@Override
public Principal getUserPrincipal() {
return principal;
}
@Override
public boolean isUserInRole(String role) {
return ui.isUserInRole(role);
}
@Override
public boolean isSecure() {
return isSecure;
}
@Override
public String getAuthenticationScheme() {
if (ui.getUserID().equals(MCRSystemUserInformation.getGuestInstance().getUserID())) {
return null;
}
if (ui instanceof MCRUser) {
return SecurityContext.BASIC_AUTH;
}
if (ui instanceof MCRJWTUserInformation) {
return "BEARER";
}
return null;
}
}
}
| 17,772 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIgnoreClientAbortInterceptor.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRIgnoreClientAbortInterceptor.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.io.output.ProxyOutputStream;
import org.apache.logging.log4j.LogManager;
import jakarta.annotation.Priority;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.ext.WriterInterceptor;
import jakarta.ws.rs.ext.WriterInterceptorContext;
/**
* Ignores IOException when writing to client OutputStream
* @see <a href="https://stackoverflow.com/a/39006980">Stack Overflow</a>
*/
@Priority(1)
public class MCRIgnoreClientAbortInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext)
throws IOException, WebApplicationException {
writerInterceptorContext
.setOutputStream(new ClientAbortExceptionOutputStream(writerInterceptorContext.getOutputStream()));
try {
writerInterceptorContext.proceed();
} catch (Exception e) {
for (Throwable cause = e; cause != null; cause = cause.getCause()) {
if (cause instanceof ClientAbortException) {
LogManager.getLogger().info("Client closed response too early.");
return;
}
}
throw e;
}
}
private static class ClientAbortExceptionOutputStream extends ProxyOutputStream {
ClientAbortExceptionOutputStream(OutputStream out) {
super(out);
}
@Override
protected void handleIOException(IOException e) throws IOException {
throw new ClientAbortException(e);
}
}
@SuppressWarnings("serial")
private static class ClientAbortException extends IOException {
ClientAbortException(IOException e) {
super(e);
}
}
}
| 2,563 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCORSResponseFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRCORSResponseFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.util.ArrayList;
import java.util.Collections;
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.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.restapi.annotations.MCRAccessControlExposeHeaders;
import jakarta.annotation.Priority;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
@Priority(Priorities.AUTHENTICATION - 1)
public class MCRCORSResponseFilter implements ContainerResponseFilter {
private static final Logger LOGGER = LogManager.getLogger();
private static final String ORIGIN = "Origin";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
private static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
private static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
private static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
private static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
@Context
ResourceInfo resourceInfo;
private static boolean handlePreFlight(ContainerRequestContext requestContext,
MultivaluedMap<String, Object> responseHeaders) {
if (!requestContext.getMethod().equals(HttpMethod.OPTIONS)
|| requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_METHOD) == null) {
//required for CORS-preflight request
return false;
}
//allow all methods
responseHeaders.putSingle(ACCESS_CONTROL_ALLOW_METHODS, responseHeaders.getFirst(HttpHeaders.ALLOW));
String requestHeaders = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS);
if (requestHeaders != null) {
//todo: may be restricted?
responseHeaders.putSingle(ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders);
//check if the request is a preflight request and the Authorization header will be sent
if (StringUtils.containsIgnoreCase(requestHeaders, HttpHeaders.AUTHORIZATION)) {
responseHeaders.putSingle(ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
responseHeaders.putSingle(ACCESS_CONTROL_ALLOW_ORIGIN, requestContext.getHeaderString(ORIGIN));
}
}
long cacheSeconds = TimeUnit.DAYS.toSeconds(1);
responseHeaders.putSingle(ACCESS_CONTROL_MAX_AGE, cacheSeconds);
return true;
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
LOGGER.debug("Request-Header: {}", requestContext.getHeaders());
String origin = requestContext.getHeaderString(ORIGIN);
if (origin == null) {
return; //No CORS Request
}
boolean authenticatedRequest = requestContext.getSecurityContext().getAuthenticationScheme() != null
//check if the Authorization header was sent
|| requestContext.getHeaderString(HttpHeaders.AUTHORIZATION) != null;
MultivaluedMap<String, Object> responseHeaders = responseContext.getHeaders();
if (authenticatedRequest) {
responseHeaders.putSingle(ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
}
responseHeaders.putSingle(ACCESS_CONTROL_ALLOW_ORIGIN, authenticatedRequest ? origin : "*");
if (!handlePreFlight(requestContext, responseHeaders)) {
//not a CORS preflight request
ArrayList<String> exposedHeaders = new ArrayList<>();
//MCR-3041 expose all header starting with X-
responseHeaders.keySet().stream()
.filter(name -> name.startsWith("x-") || name.startsWith("X-"))
.forEach(exposedHeaders::add);
if (authenticatedRequest && responseHeaders.getFirst(HttpHeaders.AUTHORIZATION) != null) {
exposedHeaders.add(HttpHeaders.AUTHORIZATION);
}
if ("ServiceWorker".equals(requestContext.getHeaderString("X-Requested-With"))) {
exposedHeaders.add(HttpHeaders.WWW_AUTHENTICATE);
}
Optional.ofNullable(resourceInfo)
.map(ResourceInfo::getResourceMethod)
.map(method -> method.getAnnotation(MCRAccessControlExposeHeaders.class))
.map(MCRAccessControlExposeHeaders::value)
.map(Stream::of)
.orElse(Stream.empty())
.forEach(exposedHeaders::add);
if (!exposedHeaders.isEmpty()) {
responseHeaders.putSingle(ACCESS_CONTROL_EXPOSE_HEADERS,
exposedHeaders.stream().collect(Collectors.joining(",")));
}
}
if (!Objects.equals(responseHeaders.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN), "*")) {
String vary = Stream
.concat(Stream.of(ORIGIN),
responseHeaders.getOrDefault(HttpHeaders.VARY, Collections.emptyList())
.stream()
.map(Object::toString)
.flatMap(s -> Stream.of(s.split(",")))
.map(String::trim))
.distinct()
.collect(Collectors.joining(","));
responseHeaders.putSingle(HttpHeaders.VARY, vary);
}
LOGGER.debug("Response-Header: {}", responseHeaders);
}
}
| 6,917 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRApiDraftFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/MCRApiDraftFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.restapi.annotations.MCRApiDraft;
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
/**
* Filter all methods and classes marked by {@link MCRApiDraft} and return {@link Response.Status#NOT_FOUND}.
*
* Use Property <code>MCR.RestApi.Draft.{{@link MCRApiDraft#value()}}=true</code> to enable a group of endpoints
* marked with the same <code>value</code>, e.g.<br>
* "<code>MCR.RestApi.Draft.Proposed=true</code>" to include all endpoints marked with
* <code>@MCRApiDraft("Proposed")</code>.
* @author Thomas Scheffler (yagee)
* @see MCRApiDraft
*/
@Priority(Priorities.AUTHORIZATION)
public class MCRApiDraftFilter implements ContainerRequestFilter {
@Context
ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) {
final Optional<MCRApiDraft> apiDraft = Stream
.of(resourceInfo.getResourceMethod(), resourceInfo.getResourceClass())
.map(r -> r.getAnnotation(MCRApiDraft.class))
.filter(Objects::nonNull)
.findFirst();
if (apiDraft.isPresent()) {
final String apiDraftName = apiDraft.get().value();
final String propertyName = "MCR.RestApi.Draft." + apiDraftName;
if (!MCRConfiguration2.getBoolean(propertyName).orElse(false)) {
LogManager.getLogger().warn("Draft API not enabled. Set '" + propertyName + "=true' to enable access.");
requestContext.abortWith(Response.status(Response.Status.NOT_FOUND).build());
}
}
}
}
| 2,745 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPISearch.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRRestAPISearch.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Scanner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.solr.MCRSolrClientFactory;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
/**
* Rest API methods that cover SOLR searches.
*
* @author Robert Stephan
*
*/
@Path("/search")
public class MCRRestAPISearch {
private static Logger LOGGER = LogManager.getLogger(MCRRestAPISearch.class);
public static final String FORMAT_JSON = "json";
public static final String FORMAT_XML = "xml";
public static final String FORMAT_CSV = "csv";
/**
* see http://wiki.apache.org/solr/CommonQueryParameters for syntax of parameters
*
* @param info - the injected Jersey URIInfo object
* @param request - the injected HTTPServletRequest object
*
* @param query
* the Query in SOLR Query syntax
* @param sort
* the sort parameter - syntax as defined by SOLR
* @param wt
* the format parameter - syntax as defined by SOLR
* @param start
* the start parameter (number) - syntax as defined by SOLR
* @param rows
* the rows parameter (number) - syntax as defined by SOLR
* @param fq
* the filter query parameter - syntax as defined by SOLR
* @param fl
* the list of fields to be returned - syntax as defined by SOLR
* @param facet
* the facet parameter (true to return facets) - syntax as defined by SOLR
* @param facetFields
* the list of facetFields to be returned - syntax as defined by SOLR
* @param jsonWrf
* the name of the JSONP callback function - syntax as defined by SOLR
*
* @return a Jersey Response Object
*/
@GET
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8",
MediaType.TEXT_PLAIN + ";charset=ISO-8859-1", MediaType.TEXT_PLAIN + ";charset=UTF-8" })
public Response search(@Context UriInfo info, @Context HttpServletRequest request, @QueryParam("q") String query,
@QueryParam("sort") String sort, @QueryParam("wt") @DefaultValue("xml") String wt,
@QueryParam("start") String start, @QueryParam("rows") String rows,
@QueryParam("fq") List<String> fq, @QueryParam("fl") List<String> fl,
@QueryParam("facet") String facet, @QueryParam("facet.sort") String facetSort,
@QueryParam("facet.limit") String facetLimit, @QueryParam("facet.field") List<String> facetFields,
@QueryParam("facet.mincount") String facetMinCount,
@QueryParam("json.wrf") String jsonWrf) {
StringBuilder url = new StringBuilder(MCRSolrClientFactory.getMainSolrCore().getV1CoreURL());
url.append("/select?");
if (query != null) {
url.append("&q=").append(URLEncoder.encode(query, StandardCharsets.UTF_8));
}
if (sort != null) {
url.append("&sort=").append(URLEncoder.encode(sort, StandardCharsets.UTF_8));
}
if (wt != null) {
url.append("&wt=").append(wt);
}
if (start != null) {
url.append("&start=").append(start);
}
if (rows != null) {
url.append("&rows=").append(rows);
}
if (fq != null) {
for (String fqItem : fq) {
url.append("&fq=").append(URLEncoder.encode(fqItem, StandardCharsets.UTF_8));
}
}
if (fl != null) {
for (String flItem : fl) {
url.append("&fl=").append(URLEncoder.encode(flItem, StandardCharsets.UTF_8));
}
}
if (facet != null) {
url.append("&facet=").append(URLEncoder.encode(facet, StandardCharsets.UTF_8));
}
for (String ff : facetFields) {
url.append("&facet.field=").append(URLEncoder.encode(ff, StandardCharsets.UTF_8));
}
if (facetSort != null) {
url.append("&facet.sort=").append(facetSort);
}
if (facetLimit != null) {
url.append("&facet.limit=").append(facetLimit);
}
if (facetMinCount != null) {
url.append("&facet.mincount=").append(facetMinCount);
}
if (jsonWrf != null) {
url.append("&json.wrf=").append(jsonWrf);
}
try (InputStream is = new URI(url.toString()).toURL().openStream()) {
try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8)) {
String text = scanner.useDelimiter("\\A").next();
String contentType = switch (wt) {
case FORMAT_XML -> "application/xml; charset=UTF-8";
case FORMAT_JSON -> "application/json; charset=UTF-8";
case FORMAT_CSV -> "text/comma-separated-values; charset=UTF-8";
default -> "text";
};
return Response.ok(text)
.type(contentType)
.build();
}
} catch (IOException | URISyntaxException e) {
LOGGER.error(e);
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
| 6,447 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAuthorizationFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRRestAuthorizationFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.mycore.access.MCRAccessInterface;
import org.mycore.access.MCRAccessManager;
import org.mycore.access.MCRRuleAccessInterface;
import org.mycore.access.mcrimpl.MCRAccessControlSystem;
import org.mycore.frontend.jersey.access.MCRRequestScopeACL;
import org.mycore.restapi.converter.MCRDetailLevel;
import org.mycore.restapi.v1.errors.MCRRestAPIError;
import org.mycore.restapi.v1.errors.MCRRestAPIException;
import org.mycore.restapi.v1.errors.MCRRestAPIExceptionMapper;
import jakarta.annotation.Priority;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
@Priority(Priorities.AUTHORIZATION)
public class MCRRestAuthorizationFilter implements ContainerRequestFilter {
public static final String PARAM_CLASSID = "classid";
public static final String PARAM_MCRID = "mcrid";
public static final String PARAM_DERID = "derid";
public static final String PARAM_DER_PATH = "path";
@Context
ResourceInfo resourceInfo;
/**
* checks if the given REST API operation is allowed
* @param permission "read" or "write"
* @param path - the REST API path, e.g. /v1/messages
*
* @throws MCRRestAPIException if access is restricted
*/
private void checkRestAPIAccess(ContainerRequestContext requestContext, MCRRestAPIACLPermission permission,
String path)
throws MCRRestAPIException {
MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext);
LogManager.getLogger().warn(path + ": Checking API access: " + permission);
String thePath = path.startsWith("/") ? path : "/" + path;
MCRAccessInterface acl = MCRAccessManager.getAccessImpl();
String permStr = permission.toString();
boolean hasAPIAccess = aclProvider.checkPermission("restapi:/", permStr);
if (hasAPIAccess) {
String objId = "restapi:" + thePath;
boolean isRuleInterface = acl instanceof MCRRuleAccessInterface;
if (!isRuleInterface || ((MCRRuleAccessInterface) acl).hasRule(objId, permStr)) {
if (aclProvider.checkPermission(objId, permStr)) {
return;
}
} else {
return;
}
}
throw new MCRRestAPIException(Response.Status.FORBIDDEN,
new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "REST-API action is not allowed.",
"Check access right '" + permission + "' on ACLs 'restapi:/' and 'restapi:" + path + "'!"));
}
private void checkBaseAccess(ContainerRequestContext requestContext, MCRRestAPIACLPermission permission,
String objectId, String derId, String path)
throws MCRRestAPIException {
LogManager.getLogger().debug("Permission: {}, Object: {}, Derivate: {}, Path: {}", permission, objectId, derId,
path);
Optional<String> checkable = Optional.ofNullable(derId)
.filter(d -> path != null) //only check for derId if path is given
.map(Optional::of)
.orElseGet(() -> Optional.ofNullable(objectId));
checkable.ifPresent(id -> LogManager.getLogger().info("Checking " + permission + " access on " + id));
MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext);
boolean allowed = checkable
.map(id -> aclProvider.checkPermission(id, permission.toString()))
.orElse(true);
if (allowed) {
return;
}
throw new MCRRestAPIException(Response.Status.FORBIDDEN,
new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "REST-API action is not allowed.",
"Check access right '" + permission + "' on '" + checkable.orElse(null) + "'!"));
}
private void checkDetailLevel(ContainerRequestContext requestContext, String... detail) throws MCRRestAPIException {
MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext);
List<String> missedPermissions = Stream.of(detail)
.map(d -> "rest-detail-" + d)
.filter(d -> MCRAccessManager.hasRule(MCRAccessControlSystem.POOL_PRIVILEGE_ID, d))
.filter(d -> !aclProvider.checkPermission(d))
.collect(Collectors.toList());
if (!missedPermissions.isEmpty()) {
throw new MCRRestAPIException(Response.Status.FORBIDDEN,
new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "REST-API action is not allowed.",
"Check permission(s) " + missedPermissions + "!"));
}
}
@Override
public void filter(ContainerRequestContext requestContext) {
MCRRestAPIACLPermission permission;
switch (requestContext.getMethod()) {
case HttpMethod.OPTIONS -> {
return;
}
case HttpMethod.GET, HttpMethod.HEAD -> {
permission = MCRRestAPIACLPermission.READ;
}
case HttpMethod.DELETE -> {
permission = MCRRestAPIACLPermission.DELETE;
}
default -> {
permission = MCRRestAPIACLPermission.WRITE;
}
}
Optional.ofNullable(resourceInfo.getResourceClass().getAnnotation(Path.class))
.map(Path::value)
.ifPresent(path -> {
try {
checkRestAPIAccess(requestContext, permission, path);
MultivaluedMap<String, String> pathParameters = requestContext.getUriInfo().getPathParameters();
checkBaseAccess(requestContext, permission, pathParameters.getFirst(PARAM_MCRID),
pathParameters.getFirst(PARAM_DERID), pathParameters.getFirst(PARAM_DER_PATH));
} catch (MCRRestAPIException e) {
LogManager.getLogger().warn("API Access denied!");
requestContext.abortWith(new MCRRestAPIExceptionMapper().toResponse(e));
}
});
try {
checkDetailLevel(requestContext,
requestContext.getAcceptableMediaTypes()
.stream()
.map(m -> m.getParameters().get(MCRDetailLevel.MEDIA_TYPE_PARAMETER))
.filter(Objects::nonNull)
.toArray(String[]::new));
} catch (MCRRestAPIException e) {
LogManager.getLogger().warn("API Access denied!");
requestContext.abortWith(new MCRRestAPIExceptionMapper().toResponse(e));
}
}
/**
* The REST API access permissions (read, write, delete)
*/
public enum MCRRestAPIACLPermission {
READ {
public String toString() {
return MCRAccessManager.PERMISSION_READ;
}
},
WRITE {
public String toString() {
return MCRAccessManager.PERMISSION_WRITE;
}
},
DELETE {
public String toString() {
return MCRAccessManager.PERMISSION_DELETE;
}
}
}
}
| 8,325 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIClassifications.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRRestAPIClassifications.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.glassfish.jersey.server.ContainerRequest;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.filter.Filters;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImpl;
import org.mycore.datamodel.classifications2.utils.MCRCategoryTransformer;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.restapi.v1.errors.MCRRestAPIError;
import org.mycore.restapi.v1.errors.MCRRestAPIException;
import org.mycore.solr.MCRSolrClientFactory;
import org.mycore.solr.MCRSolrUtils;
import com.google.gson.stream.JsonWriter;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;
/**
* REST API for classification objects.
*
* @author Robert Stephan
*
*/
@Path("/classifications")
public class MCRRestAPIClassifications {
public static final String FORMAT_JSON = "json";
public static final String FORMAT_XML = "xml";
private static final MCRCategoryDAO DAO = new MCRCategoryDAOImpl();
private static Logger LOGGER = LogManager.getLogger(MCRRestAPIClassifications.class);
@Context
ContainerRequest request;
private Date lastModified = new Date(DAO.getLastModified());
/**
* Output xml
* @param eRoot - the root element
* @param lang - the language which should be filtered or null for no filter
* @return a string representation of the XML
*/
private static String writeXML(Element eRoot, String lang) throws IOException {
StringWriter sw = new StringWriter();
if (lang != null) {
// <label xml:lang="en" text="part" />
XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']",
Filters.element(), null, Namespace.XML_NAMESPACE);
for (Element e : xpE.evaluate(eRoot)) {
e.getParentElement().removeContent(e);
}
}
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
Document docOut = new Document(eRoot.detach());
xout.output(docOut, sw);
return sw.toString();
}
/**
* output categories in JSON format
* @param eParent - the parent xml element
* @param writer - the JSON writer
* @param lang - the language to be filtered or null if all languages should be displayed
*
*/
private static void writeChildrenAsJSON(Element eParent, JsonWriter writer, String lang) throws IOException {
if (eParent.getChildren("category").size() == 0) {
return;
}
writer.name("categories");
writer.beginArray();
for (Element e : eParent.getChildren("category")) {
writer.beginObject();
writer.name("ID").value(e.getAttributeValue("ID"));
writer.name("labels").beginArray();
for (Element eLabel : e.getChildren("label")) {
if (lang == null || lang.equals(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE))) {
writer.beginObject();
writer.name("lang").value(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE));
writer.name("text").value(eLabel.getAttributeValue("text"));
if (eLabel.getAttributeValue("description") != null) {
writer.name("description").value(eLabel.getAttributeValue("description"));
}
writer.endObject();
}
}
writer.endArray();
if (e.getChildren("category").size() > 0) {
writeChildrenAsJSON(e, writer, lang);
}
writer.endObject();
}
writer.endArray();
}
/**
* output children in JSON format used as input for Dijit Checkbox Tree
*
* @param eParent - the parent xml element
* @param writer - the JSON writer
* @param lang - the language to be filtered or null if all languages should be displayed
*
*/
private static void writeChildrenAsJSONCBTree(Element eParent, JsonWriter writer, String lang, boolean checked)
throws IOException {
writer.beginArray();
for (Element e : eParent.getChildren("category")) {
writer.beginObject();
writer.name("ID").value(e.getAttributeValue("ID"));
for (Element eLabel : e.getChildren("label")) {
if (lang == null || lang.equals(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE))) {
writer.name("text").value(eLabel.getAttributeValue("text"));
}
}
writer.name("checked").value(checked);
if (e.getChildren("category").size() > 0) {
writer.name("children");
writeChildrenAsJSONCBTree(e, writer, lang, checked);
}
writer.endObject();
}
writer.endArray();
}
/**
* output children in JSON format used as input for a jsTree
*
* @param eParent - the parent xml element
* @param writer - the JSON writer
* @param lang - the language to be filtered or null if all languages should be displayed
* @param opened - true, if all leaf nodes should be displayed
* @param disabled - true, if all nodes should be disabled
* @param selected - true, if all node should be selected
*
*/
private static void writeChildrenAsJSONJSTree(Element eParent, JsonWriter writer, String lang, boolean opened,
boolean disabled, boolean selected) throws IOException {
writer.beginArray();
for (Element e : eParent.getChildren("category")) {
writer.beginObject();
writer.name("id").value(e.getAttributeValue("ID"));
for (Element eLabel : e.getChildren("label")) {
if (lang == null || lang.equals(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE))) {
writer.name("text").value(eLabel.getAttributeValue("text"));
}
}
if (opened || disabled || selected) {
writer.name("state");
writer.beginObject();
if (opened) {
writer.name("opened").value(true);
}
if (disabled) {
writer.name("disabled").value(true);
}
if (selected) {
writer.name("selected").value(true);
}
writer.endObject();
}
if (e.getChildren("category").size() > 0) {
writer.name("children");
writeChildrenAsJSONJSTree(e, writer, lang, opened, disabled, selected);
}
writer.endObject();
}
writer.endArray();
}
/**
* lists all available classifications as XML or JSON
*
* @param info - the URIInfo object
* @param format - the output format ('xml' or 'json)
* @return a Jersey Response Object
*/
@GET
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
public Response listClassifications(@Context UriInfo info,
@QueryParam("format") @DefaultValue("json") String format) {
Response.ResponseBuilder builder = request.evaluatePreconditions(lastModified);
if (builder != null) {
return builder.build();
}
if (FORMAT_XML.equals(format)) {
StringWriter sw = new StringWriter();
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
Document docOut = new Document();
Element eRoot = new Element("mycoreclassifications");
docOut.setRootElement(eRoot);
for (MCRCategory cat : DAO.getRootCategories()) {
eRoot.addContent(new Element("mycoreclass").setAttribute("ID", cat.getId().getRootID()).setAttribute(
"href", info.getAbsolutePathBuilder().path(cat.getId().getRootID()).build().toString()));
}
try {
xout.output(docOut, sw);
return Response.ok(sw.toString())
.lastModified(lastModified)
.type("application/xml; charset=UTF-8")
.build();
} catch (IOException e) {
//ToDo
}
}
if (FORMAT_JSON.equals(format)) {
StringWriter sw = new StringWriter();
try {
JsonWriter writer = new JsonWriter(sw);
writer.setIndent(" ");
writer.beginObject();
writer.name("mycoreclass");
writer.beginArray();
for (MCRCategory cat : DAO.getRootCategories()) {
writer.beginObject();
writer.name("ID").value(cat.getId().getRootID());
writer.name("href")
.value(info.getAbsolutePathBuilder().path(cat.getId().getRootID()).build().toString());
writer.endObject();
}
writer.endArray();
writer.endObject();
writer.close();
return Response.ok(sw.toString())
.type(MCRJerseyUtil.APPLICATION_JSON_UTF8)
.lastModified(lastModified)
.build();
} catch (IOException e) {
//toDo
}
}
return Response.status(Status.BAD_REQUEST).build();
}
/**
* returns a single classification object
*
* @param classID - the classfication id
* @param format
* Possible values are: json | xml (required)
* @param filter
* a ';'-separated list of ':'-separated key-value pairs, possible keys are:
* - lang - the language of the returned labels, if ommited all labels in all languages will be returned
* - root - an id for a category which will be used as root
* - nonempty - hide empty categories
* @param style
* a ';'-separated list of values, possible keys are:
* - 'checkboxtree' - create a json syntax which can be used as input for a dojo checkboxtree;
* - 'checked' - (together with 'checkboxtree') all checkboxed will be checked
* - 'jstree' - create a json syntax which can be used as input for a jsTree
* - 'opened' - (together with 'jstree') - all nodes will be opened
* - 'disabled' - (together with 'jstree') - all nodes will be disabled
* - 'selected' - (together with 'jstree') - all nodes will be selected
* @param callback - used in JSONP to wrap json result into a Javascript function named by callback parameter
* @return a Jersey Response object
*/
@GET
//@Path("/id/{value}{format:(\\.[^/]+?)?}") -> working, but returns empty string instead of default value
@Path("/{classID}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
public Response showObject(@PathParam("classID") String classID,
@QueryParam("format") @DefaultValue("xml") String format, @QueryParam("filter") @DefaultValue("") String filter,
@QueryParam("style") @DefaultValue("") String style,
@QueryParam("callback") @DefaultValue("") String callback) {
Response.ResponseBuilder builder = request.evaluatePreconditions(lastModified);
if (builder != null) {
return builder.build();
}
String rootCateg = null;
String lang = null;
boolean filterNonEmpty = false;
boolean filterNoChildren = false;
for (String f : filter.split(";")) {
if (f.startsWith("root:")) {
rootCateg = f.substring(5);
}
if (f.startsWith("lang:")) {
lang = f.substring(5);
}
if (f.startsWith("nonempty")) {
filterNonEmpty = true;
}
if (f.startsWith("nochildren")) {
filterNoChildren = true;
}
}
if (format == null || classID == null) {
return Response.serverError().status(Status.BAD_REQUEST).build();
//TODO response.sendError(HttpServletResponse.SC_NOT_FOUND,
// "Please specify parameters format and classid.");
}
try {
MCRCategory cl = DAO.getCategory(MCRCategoryID.rootID(classID), -1);
if (cl == null) {
throw new MCRRestAPIException(Status.NOT_FOUND,
new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Classification not found.",
"There is no classification with the given ID."));
}
Document docClass = MCRCategoryTransformer.getMetaDataDocument(cl, false);
Element eRoot = docClass.getRootElement();
if (rootCateg != null) {
XPathExpression<Element> xpe = XPathFactory.instance().compile("//category[@ID='" + rootCateg + "']",
Filters.element());
Element e = xpe.evaluateFirst(docClass);
if (e != null) {
eRoot = e;
} else {
throw new MCRRestAPIException(Status.NOT_FOUND,
new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Category not found.",
"The classfication does not contain a category with the given ID."));
}
}
if (filterNonEmpty) {
Element eFilter = eRoot;
if (eFilter.getName().equals("mycoreclass")) {
eFilter = eFilter.getChild("categories");
}
filterNonEmpty(docClass.getRootElement().getAttributeValue("ID"), eFilter);
}
if (filterNoChildren) {
eRoot.removeChildren("category");
}
if (FORMAT_JSON.equals(format)) {
String json = writeJSON(eRoot, lang, style);
//eventually: allow Cross Site Requests: .header("Access-Control-Allow-Origin", "*")
if (callback.length() > 0) {
return Response.ok(callback + "(" + json + ")")
.lastModified(lastModified)
.type(MCRJerseyUtil.APPLICATION_JSON_UTF8)
.build();
} else {
return Response.ok(json).type("application/json; charset=UTF-8")
.build();
}
}
if (FORMAT_XML.equals(format)) {
String xml = writeXML(eRoot, lang);
return Response.ok(xml)
.lastModified(lastModified)
.type(MCRJerseyUtil.APPLICATION_XML_UTF8)
.build();
}
} catch (Exception e) {
LogManager.getLogger(this.getClass()).error("Error outputting classification", e);
//TODO response.sendError(HttpServletResponse.SC_NOT_FOUND, "Error outputting classification");
}
return null;
}
/**
* Output JSON
* @param eRoot - the category element
* @param lang - the language to be filtered for or null if all languages should be displayed
* @param style - the style
* @return a string representation of a JSON object
*/
private String writeJSON(Element eRoot, String lang, String style) throws IOException {
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
writer.setIndent(" ");
if (style.contains("checkboxtree")) {
if (lang == null) {
lang = "de";
}
writer.beginObject();
writer.name("identifier").value(eRoot.getAttributeValue("ID"));
for (Element eLabel : eRoot.getChildren("label")) {
if (lang.equals(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE))) {
writer.name("label").value(eLabel.getAttributeValue("text"));
}
}
writer.name("items");
eRoot = eRoot.getChild("categories");
writeChildrenAsJSONCBTree(eRoot, writer, lang, style.contains("checked"));
writer.endObject();
} else if (style.contains("jstree")) {
if (lang == null) {
lang = "de";
}
eRoot = eRoot.getChild("categories");
writeChildrenAsJSONJSTree(eRoot, writer, lang, style.contains("opened"),
style.contains("disabled"), style.contains("selected"));
} else {
writer.beginObject(); // {
writer.name("ID").value(eRoot.getAttributeValue("ID"));
writer.name("label");
writer.beginArray();
for (Element eLabel : eRoot.getChildren("label")) {
if (lang == null || lang.equals(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE))) {
writer.beginObject();
writer.name("lang").value(eLabel.getAttributeValue("lang", Namespace.XML_NAMESPACE));
writer.name("text").value(eLabel.getAttributeValue("text"));
if (eLabel.getAttributeValue("description") != null) {
writer.name("description").value(eLabel.getAttributeValue("description"));
}
writer.endObject();
}
}
writer.endArray();
if (eRoot.equals(eRoot.getDocument().getRootElement())) {
writeChildrenAsJSON(eRoot.getChild("categories"), writer, lang);
} else {
writeChildrenAsJSON(eRoot, writer, lang);
}
writer.endObject();
}
writer.close();
return sw.toString();
}
private void filterNonEmpty(String classId, Element e) {
SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
Element[] categories = e.getChildren("category").toArray(Element[]::new);
for (Element cat : categories) {
SolrQuery solrQquery = new SolrQuery();
solrQquery.setQuery(
"category:\"" + MCRSolrUtils.escapeSearchValue(classId + ":" + cat.getAttributeValue("ID")) + "\"");
solrQquery.setRows(0);
try {
QueryResponse response = solrClient.query(solrQquery);
SolrDocumentList solrResults = response.getResults();
if (solrResults.getNumFound() == 0) {
cat.detach();
} else {
filterNonEmpty(classId, cat);
}
} catch (SolrServerException | IOException exc) {
LOGGER.error(exc);
}
}
}
}
| 21,200 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIMessages.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRRestAPIMessages.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Properties;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.common.config.MCRProperties;
import org.mycore.services.i18n.MCRTranslation;
import com.google.gson.stream.JsonWriter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;
/**
* REST API for messages.
* Allows access to message properties of the application
*
*
* @author Robert Stephan
*
*/
@Path("/messages")
public class MCRRestAPIMessages {
public static final String FORMAT_JSON = "json";
public static final String FORMAT_XML = "xml";
public static final String FORMAT_PROPERTY = "property";
/**
* lists all message properties for a given language
*
* @param info - the injected Jersey Context Object for URI
*
* @param request - the injected HTTPServletRequest object
*
* @param lang - the language in which the messages should be returned (default: 'de')
*
* @param format
* Possible values are: props (default) | json | xml
* @param filter
* ';'-separated list of message key prefixes
*
* @return a Jersey Response object
*
*/
@GET
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8",
MediaType.TEXT_PLAIN + ";charset=ISO-8859-1" })
public Response listMessages(@Context UriInfo info, @Context HttpServletRequest request,
@QueryParam("lang") @DefaultValue("de") String lang,
@QueryParam("format") @DefaultValue("property") String format,
@QueryParam("filter") @DefaultValue("") String filter) {
Locale locale = Locale.forLanguageTag(lang);
String[] check = filter.split(";");
Properties data = new MCRProperties();
for (String prefix : check) {
data.putAll(MCRTranslation.translatePrefixToLocale(prefix, locale));
}
try {
if (FORMAT_PROPERTY.equals(format)) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
data.store(baos, "MyCoRe Messages (charset='ISO-8859-1')");
return Response.ok(baos.toByteArray()).type("text/plain; charset=ISO-8859-1").build();
}
if (FORMAT_XML.equals(format)) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
data.storeToXML(baos, "MyCoRe Messages");
return Response.ok(baos.toString(StandardCharsets.UTF_8)).type("application/xml; charset=UTF-8")
.build();
}
if (FORMAT_JSON.equals(format)) {
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
writer.setIndent(" ");
writer.beginObject();
writer.name("messages");
writer.beginObject();
for (Object key : data.keySet()) {
writer.name(key.toString());
writer.value(data.getProperty(key.toString()));
}
writer.endObject();
writer.endObject();
writer.close();
return Response.ok(sw.toString()).type("application/json; charset=UTF-8")
.build();
}
} catch (IOException e) {
//toDo
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
/**
* returns a single messages entry.
*
* @param info - the injected Jersey context object for URI
* @param request - the injected HTTPServletRequest object
* @param key - the message key
* @param lang - the language
* @param format
* Possible values are: props (default) | json | xml (required)
* @return a Jersey Response Object
*/
@GET
@Path("/{value}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8",
MediaType.TEXT_PLAIN + ";charset=UTF-8" })
public Response getMessage(@Context UriInfo info, @Context HttpServletRequest request,
@PathParam("value") String key, @QueryParam("lang") @DefaultValue("de") String lang,
@QueryParam("format") @DefaultValue("text") String format) {
Locale locale = Locale.forLanguageTag(lang);
String result = MCRTranslation.translate(key, locale);
try {
if (FORMAT_PROPERTY.equals(format)) {
return Response.ok(key + "=" + result).type("text/plain; charset=ISO-8859-1")
.build();
}
if (FORMAT_XML.equals(format)) {
Document doc = new Document();
Element root = new Element("entry");
root.setAttribute("key", key);
root.setText(result);
doc.addContent(root);
StringWriter sw = new StringWriter();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, sw);
return Response.ok(sw.toString()).type("application/xml; charset=UTF-8")
.build();
}
if (FORMAT_JSON.equals(format)) {
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
writer.setIndent(" ");
writer.beginObject();
writer.name(key);
writer.value(result);
writer.endObject();
writer.close();
return Response.ok(sw.toString()).type("application/json; charset=UTF-8")
.build();
}
//text only
return Response.ok(result).type("text/plain; charset=UTF-8")
.build();
} catch (IOException e) {
//toDo
}
return Response.status(Status.BAD_REQUEST).build();
}
}
| 7,295 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestV1App.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRRestV1App.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import java.util.stream.Stream;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.resources.MCRJerseyExceptionMapper;
import org.mycore.restapi.MCRJerseyRestApp;
import org.mycore.restapi.MCRNormalizeMCRObjectIDsFilter;
import org.mycore.restapi.converter.MCRWrappedXMLWriter;
import org.mycore.restapi.v1.errors.MCRForbiddenExceptionMapper;
import org.mycore.restapi.v1.errors.MCRNotAuthorizedExceptionMapper;
import org.mycore.restapi.v1.errors.MCRRestAPIExceptionMapper;
import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource;
import jakarta.ws.rs.ApplicationPath;
/**
* @author Thomas Scheffler (yagee)
*
*/
@ApplicationPath("/api/v1")
public class MCRRestV1App extends MCRJerseyRestApp {
public MCRRestV1App() {
super();
register(MCRJerseyExceptionMapper.class);
register(MCRRestAPIExceptionMapper.class);
register(MCRForbiddenExceptionMapper.class);
register(MCRNotAuthorizedExceptionMapper.class);
register(MCRNormalizeMCRObjectIDsFilter.class);
}
@Override
protected String getVersion() {
return "v1";
}
@Override
protected String[] getRestPackages() {
return Stream
.concat(
Stream.of(MCRWrappedXMLWriter.class.getPackage().getName(),
OpenApiResource.class.getPackage().getName()),
MCRConfiguration2.getOrThrow("MCR.RestAPI.Resource.Packages", MCRConfiguration2::splitValue))
.toArray(String[]::new);
}
}
| 2,300 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInfo.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRInfo.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import java.util.Properties;
import org.mycore.common.MCRCoreVersion;
import org.mycore.frontend.jersey.MCRStaticContent;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/mycore")
@MCRStaticContent
public class MCRInfo {
@GET
@Path("version")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Properties getGitInfos() {
Properties properties = new Properties();
properties.putAll(MCRCoreVersion.getVersionProperties());
return properties;
}
}
| 1,356 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIObjects.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRRestAPIObjects.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import static org.mycore.restapi.v1.MCRRestAuthorizationFilter.PARAM_DERID;
import static org.mycore.restapi.v1.MCRRestAuthorizationFilter.PARAM_MCRID;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.restapi.annotations.MCRAccessControlExposeHeaders;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import org.mycore.restapi.v1.errors.MCRRestAPIError;
import org.mycore.restapi.v1.errors.MCRRestAPIException;
import org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper;
import org.mycore.restapi.v1.utils.MCRRestAPIUploadHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
/**
* REST API methods to retrieve objects and derivates.
*
* @author Robert Stephan
*
*/
@Path("/objects")
public class MCRRestAPIObjects {
public static final String STYLE_DERIVATEDETAILS = "derivatedetails";
public static final String FORMAT_JSON = "json";
public static final String FORMAT_XML = "xml";
public static final String SORT_ASC = "asc";
public static final String SORT_DESC = "desc";
@Context
Application app;
/** returns a list of mcrObjects
*
* @param info - the injected Jersey URIInfo object
* @param format - parameter for return format, values are
* * xml (default value)
* * json
*
* @param filter - parameter with filters as colon-separated key-value-pairs,
* pair separator is semicolon, allowed values are
* * project - the MyCoRe ProjectID - first Part of a MyCoRe ID
* * type - the MyCoRe ObjectType - middle Part of a MyCoRe ID
* * lastModifiedBefore - last modified date in UTC is lesser than or equals to given value
* * lastModifiedAfter - last modified date in UTC is greater than or equals to given value;
*
* @param sort - sortfield and sortorder combined by ':'
* * sortfield = ID | lastModified
* * sortorder = asc | desc
*
* @return a Jersey response object
*/
@GET
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response listObjects(@Context UriInfo info,
@QueryParam("format") @DefaultValue("xml") String format, @QueryParam("filter") String filter,
@QueryParam("sort") @DefaultValue("ID:asc") String sort) throws MCRRestAPIException {
return MCRRestAPIObjectsHelper.listObjects(info, format, filter, sort);
}
/**
* returns a list of derivates for a given MyCoRe Object
*
* @param info - the injected Jersey URIInfo object
* @param mcrid - an object identifier of syntax [id] or [prefix]:[id]
*
* Allowed Prefixes are "mcr" or application specific search keys
* "mcr" is the default prefix for MyCoRe IDs.
* @param format - parameter for return format, values are
* * xml (default value)
* * json
* @param sort - sortfield and sortorder combined by ':'
* * sortfield = ID | lastModified
* * sortorder = asc | desc
*
* @return a Jersey Response object
*/
@GET
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
@Path("/{" + PARAM_MCRID + "}/derivates")
public Response listDerivates(@Context UriInfo info,
@PathParam(PARAM_MCRID) String mcrid,
@QueryParam("format") @DefaultValue("xml") String format,
@QueryParam("sort") @DefaultValue("ID:asc") String sort) throws MCRRestAPIException {
return MCRRestAPIObjectsHelper.listDerivates(info, mcrid, format, sort);
}
/**
* returns a single derivate object in XML Format
*
* @param info - the injected Jersey URIInfo object
* @param id an object identifier of syntax [id] or [prefix]:[id]
*
* Allowed Prefixes are "mcr" or application specific search keys
* "mcr" is the default prefix for MyCoRe IDs.
*
* @param style allowed values are "derivatedetails"
* derivate details will be integrated into the output.
*
* @return a Jersey Response object
*/
@GET
@Produces(MediaType.TEXT_XML)
@Path("/{" + PARAM_MCRID + "}")
public Response returnMCRObject(@Context UriInfo info,
@PathParam(PARAM_MCRID) String id, @QueryParam("style") String style)
throws MCRRestAPIException {
return MCRRestAPIObjectsHelper.showMCRObject(id, style, info, app);
}
/**
* returns a single object in XML Format
*
* @param info - the injected Jersey URIInfo object
* @param mcrid - a object identifier of syntax [id] or [prefix]:[id]
* @param derid - a derivate identifier of syntax [id] or [prefix]:[id]
*
* Allowed Prefixes are "mcr" or application specific search keys
* "mcr" is the default prefix for MyCoRe IDs.
*
* @param style - controls the output:
* allowed values are "derivatedetails" to integrate derivate details into the output.
*
* @return a Jersey Response object
*/
@GET
@Produces(MediaType.TEXT_XML)
@Path("/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}")
public Response returnDerivate(@Context UriInfo info,
@PathParam(PARAM_MCRID) String mcrid,
@PathParam(PARAM_DERID) String derid,
@QueryParam("style") String style)
throws MCRRestAPIException {
return MCRRestAPIObjectsHelper.showMCRDerivate(mcrid, derid, info, app,
Objects.equals(style, "derivatedetails"));
}
/** returns a list of derivates for a given MyCoRe Object
*
* @param info - the injected Jersey URIInfo object
* @param request - the injected JAX-WS request object
*
* @param mcrid - a object identifier of syntax [id] or [prefix]:[id]
* @param derid - a derivate identifier of syntax [id] or [prefix]:[id]
*
* Allowed Prefixes are "mcr" or application specific search keys
* "mcr" is the default prefix for MyCoRe IDs.
*
* @param path - the relative path to a directory inside a derivate
* @param format - specifies the return format, allowed values are:
* * xml (default value)
* * json
*
* @param depth - the level of subdirectories that should be returned
*
* @return a Jersey Response object
*/
@GET
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MCRJerseyUtil.APPLICATION_JSON_UTF8 })
@Path("/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}/contents{path:(/.*)*}")
public Response listContents(@Context UriInfo info,
@Context Request request, @PathParam(PARAM_MCRID) String mcrid,
@PathParam(PARAM_DERID) String derid,
@PathParam("path") @DefaultValue("/") String path, @QueryParam("format") @DefaultValue("xml") String format,
@QueryParam("depth") @DefaultValue("-1") int depth) throws MCRRestAPIException {
return MCRRestAPIObjectsHelper.listContents(info, app, request, mcrid, derid, format, path, depth);
}
/**
* redirects to the maindoc of the given derivate
*
* @param info - the injected Jersey URIInfo object
* @param mcrObjID - a object identifier of syntax [id] or [prefix]:[id]
* @param mcrDerID - a derivate identifier of syntax [id] or [prefix]:[id]
*
* Allowed Prefixes are "mcr" or application specific search keys
* "mcr" is the default prefix for MyCoRe IDs.
*
* @return a Jersey Response object
*
*/
@GET
@Path("/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}/open")
public Response listContents(@Context UriInfo info,
@PathParam(PARAM_MCRID) String mcrObjID,
@PathParam(PARAM_DERID) String mcrDerID)
throws MCRRestAPIException {
try {
String url = MCRRestAPIObjectsHelper.retrieveMaindocURL(info, mcrObjID, mcrDerID, app);
if (url != null) {
return Response.seeOther(new URI(url)).build();
}
} catch (URISyntaxException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR,
"A problem occurred while opening maindoc from derivate " + mcrDerID, e.getMessage()));
}
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR,
"A problem occurred while opening maindoc from derivate " + mcrDerID, ""));
}
//*****************************
//* Upload API
//*****************************
/**
* create / update a MyCoRe object
*
* @param info - the injected Jersey URIInfo object
* @param request - the injected HTTPServletRequest object
*
* @param uploadedInputStream - the MyCoRe Object (XML) as inputstream from HTTP Post
* @param fileDetails - file metadata from HTTP Post
*
* @return a Jersey Response object
*
*/
@POST
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8" })
@Consumes(MediaType.MULTIPART_FORM_DATA)
@MCRRequireTransaction
@MCRAccessControlExposeHeaders(HttpHeaders.LOCATION)
public Response uploadObject(@Context UriInfo info, @Context HttpServletRequest request,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetails) throws MCRRestAPIException {
return MCRRestAPIUploadHelper.uploadObject(info, request, uploadedInputStream, fileDetails);
}
/**
* create a new (empty) MyCoRe derivate or returns one that already exists (by label)
*
* @param info - the injected Jersey URIInfo object
* @param request - the injected HTTPServletRequest object
*
* @param mcrObjID - a MyCoRe Object ID
*
* @param label - the label of the new derivate
* @param overwrite - if true, return an existing derivate (with same label)
*
* @return a Jersey Response object
*
*/
@POST
@Path("/{" + PARAM_MCRID + "}/derivates")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8" })
@Consumes(MediaType.MULTIPART_FORM_DATA)
@MCRRequireTransaction
@MCRAccessControlExposeHeaders(HttpHeaders.LOCATION)
public Response uploadDerivate(@Context UriInfo info, @Context HttpServletRequest request,
@PathParam(PARAM_MCRID) String mcrObjID, @FormDataParam("label") String label,
@FormDataParam("classifications") String classifications,
@FormDataParam("overwriteOnExistingLabel") @DefaultValue("false") boolean overwrite) {
return MCRRestAPIUploadHelper.uploadDerivate(info, request, mcrObjID, label, classifications, overwrite);
}
/**
* upload a file into a given derivate
* @param info - the injected Jersey URIInfo object
* @param request - the injected HTTPServletRequest object
*
* @param mcrObjID - a MyCoRe Object ID
* @param mcrDerID - a MyCoRe Derivate ID
*
* @param uploadedInputStream - the inputstream from HTTP Post
* @param fileDetails - file information from HTTP Post
* @param path - the target path inside the derivate
* @param maindoc - true, if the file should be set as maindoc
* @param unzip - true, if the file is a zip file, that should be extracted
* @param md5 - the md5 sum of the uploaded file
* @param size - the size of the uploaded file
* @return a Jersey Response object
*/
@POST
@Path("/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}/contents{path:(/.*)*}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8" })
@Consumes(MediaType.MULTIPART_FORM_DATA)
@MCRRequireTransaction
@MCRAccessControlExposeHeaders(HttpHeaders.LOCATION)
public Response uploadFile(@Context UriInfo info, @Context HttpServletRequest request,
@PathParam(PARAM_MCRID) String mcrObjID,
@PathParam(PARAM_DERID) String mcrDerID,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetails, @FormDataParam("path") String path,
@FormDataParam("maindoc") @DefaultValue("false") boolean maindoc,
@FormDataParam("unzip") @DefaultValue("false") boolean unzip, @FormDataParam("md5") String md5,
@FormDataParam("size") Long size) throws MCRRestAPIException {
return MCRRestAPIUploadHelper.uploadFile(info, request, mcrObjID, mcrDerID, uploadedInputStream, fileDetails,
path, maindoc, unzip, md5, size);
}
/**
* delete all file from a given derivate
*
* @param info - the injected Jersey URIInfo object
* @param request - the injected HTTPServletRequest object
*
* @param mcrObjID - a MyCoRe Object ID
* @param mcrDerID - a MyCoRe Derivate ID
*
* @return a Jersey Response object
*
*/
@DELETE
@Path("/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}/contents")
@MCRRequireTransaction
public Response deleteFiles(@Context UriInfo info, @Context HttpServletRequest request,
@PathParam(PARAM_MCRID) String mcrObjID,
@PathParam(PARAM_DERID) String mcrDerID) {
return MCRRestAPIUploadHelper.deleteAllFiles(info, request, mcrObjID, mcrDerID);
}
/**
* delete a whole derivate
*
* @param info - the injected Jersey URIInfo object
* @param request - the injected HTTPServletRequest object
*
* @param mcrObjID - a MyCoRe Object ID
* @param mcrDerID - a MyCoRe Derivate ID
*
* @return a Jersey Response object
*
*/
@DELETE
@Path("/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}")
@MCRRequireTransaction
public Response deleteDerivate(@Context UriInfo info, @Context HttpServletRequest request,
@PathParam(PARAM_MCRID) String mcrObjID,
@PathParam(PARAM_DERID) String mcrDerID) throws MCRRestAPIException {
return MCRRestAPIUploadHelper.deleteDerivate(info, request, mcrObjID, mcrDerID);
}
}
| 15,648 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIAuthentication.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/MCRRestAPIAuthentication.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1;
import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Optional;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.frontend.jersey.MCRJWTUtil;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.frontend.jersey.access.MCRRequireLogin;
import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess;
import org.mycore.restapi.v1.utils.MCRRestAPIUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTVerificationException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
/**
* Rest Controller that handles authentication.
*
* @author Thomas Scheffler
* @author Robert Stephan
*
*/
@Path("/auth")
public class MCRRestAPIAuthentication {
private static final int EXPIRATION_TIME_MINUTES = 10;
public static final String AUDIENCE = "mcr:rest-auth";
@Context
HttpServletRequest req;
@Context
Application app;
/**
* Unauthenticated requests should return a response whose header contains a HTTP 401 Unauthorized status and a
* WWW-Authenticate field.
*
* 200 OK Content-Type: application/json;charset=UTF-8
*
* { "access_token": "NgCXRK...MzYjw", "token_type": "Bearer", "expires_at": 1372700873, "refresh_token":
* "NgAagA...Um_SHo" }
*
* Returning the JWT (Java Web Token to the client is not properly specified). We use the "Authorization" Header in
* the response, which is unusual but not strictly forbidden.
*
* @param authorization - content HTTP Header Authorization
* @throws IOException if JWT cannot be written
* @return response message as JSON
*/
@GET
@Produces({ MCRJerseyUtil.APPLICATION_JSON_UTF8 })
@Path("/login")
@MCRCacheControl(noTransform = true,
noStore = true,
private_ = @MCRCacheControl.FieldArgument(active = true),
noCache = @MCRCacheControl.FieldArgument(active = true))
public Response authorize(@DefaultValue("") @HeaderParam("Authorization") String authorization) throws IOException {
if (authorization.startsWith("Basic ")) {
//login handled by MCRSessionFilter
Optional<String> jwt = getToken(MCRSessionMgr.getCurrentSession(),
MCRFrontendUtil.getRemoteAddr(req));
if (jwt.isPresent()) {
return MCRJWTUtil.getJWTLoginSuccessResponse(jwt.get());
}
}
throw new NotAuthorizedException(
"Login failed. Please provide proper user name and password via HTTP Basic Authentication.",
MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app));
}
public static Optional<String> getToken(MCRSession session, String remoteIp) {
ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
return Optional.ofNullable(session)
.map(MCRJWTUtil::getJWTBuilder)
.map(b -> b.withAudience(AUDIENCE)
.withClaim(MCRJWTUtil.JWT_CLAIM_IP, remoteIp)
.withExpiresAt(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant()))
.withNotBefore(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant()))
.sign(MCRJWTUtil.getJWTAlgorithm()));
}
@GET
@Path("/renew")
@MCRRestrictedAccess(MCRRequireLogin.class)
@MCRCacheControl(noTransform = true,
noStore = true,
private_ = @MCRCacheControl.FieldArgument(active = true),
noCache = @MCRCacheControl.FieldArgument(active = true))
public Response renew(@DefaultValue("") @HeaderParam("Authorization") String authorization) throws IOException {
if (authorization.startsWith("Bearer ")) {
//login handled by MCRSessionFilter
Optional<String> jwt = getToken(MCRSessionMgr.getCurrentSession(),
MCRFrontendUtil.getRemoteAddr(req));
if (jwt.isPresent()) {
return MCRJWTUtil.getJWTRenewSuccessResponse(jwt.get());
}
}
throw new NotAuthorizedException(
"Login failed. Please provide a valid JSON Web Token for authentication.",
MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app));
}
public static void validate(String token) throws JWTVerificationException {
JWT.require(MCRJWTUtil.getJWTAlgorithm())
.withAudience(AUDIENCE)
.acceptLeeway(0)
.build().verify(token);
}
}
| 5,703 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPropertiesToXMLTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRPropertiesToXMLTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.MessageBodyWriter;
import jakarta.ws.rs.ext.Provider;
@Produces(MediaType.APPLICATION_XML)
@Provider
public class MCRPropertiesToXMLTransformer implements MessageBodyWriter<Properties> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Properties.class.isAssignableFrom(type) && mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE);
}
@Override
public long getSize(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_XML_TYPE.withCharset(StandardCharsets.UTF_8.name()));
t.storeToXML(entityStream, null);
}
}
| 2,242 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPIUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import org.glassfish.jersey.server.ServerProperties;
import jakarta.ws.rs.core.Application;
/**
* This class contains some generic utility functions for the REST API
*
* @author Thomas Scheffler (yagee)
*/
public class MCRRestAPIUtil {
public static String getWWWAuthenticateHeader(String s,
Map<String, String> attributes, Application app) {
LinkedHashMap<String, String> attrMap = new LinkedHashMap<>();
String realm = app.getProperties()
.getOrDefault(ServerProperties.APPLICATION_NAME, "REST API")
.toString();
attrMap.put("realm", realm);
Optional.ofNullable(attributes).ifPresent(attrMap::putAll);
StringBuilder b = new StringBuilder();
attrMap.entrySet().stream()
.forEach(e -> appendFieldValue(b, e.getKey(), e.getValue()));
b.insert(0, " ");
return Optional.ofNullable(s).orElse("Basic") + b;
}
private static void appendField(StringBuilder b, String field) {
if (b.length() > 0) {
b.append(", ");
}
b.append(field);
}
private static void appendValue(StringBuilder b, String value) {
for (char c : value.toCharArray()) {
if ((c < 0x20) || (c == 0x22) || (c == 0x5c) || (c > 0x7e)) {
b.append(' ');
} else {
b.append(c);
}
}
}
private static void appendFieldValue(StringBuilder b, String field, String value) {
appendField(b, field);
if (value != null && !value.isEmpty()) {
b.append("=\"");
appendValue(b, value);
b.append('\"');
}
}
}
| 2,522 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPISortObject.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPISortObject.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
/**
* Helper Object that stores information for sorting:
* sort field and sort order
*
* ToDo: Check if this can be replaced with SOLR functionality
*
* @author Robert Stephan
*
*/
public class MCRRestAPISortObject {
enum SortOrder {
ASC, DESC
}
private String field;
private SortOrder order;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public SortOrder getOrder() {
return order;
}
public void setOrder(SortOrder order) {
this.order = order;
}
}
| 1,375 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJSONFileVisitor.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRJSONFileVisitor.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
import static org.mycore.datamodel.niofs.MCRAbstractFileSystem.SEPARATOR;
import static org.mycore.datamodel.niofs.MCRAbstractFileSystem.SEPARATOR_STRING;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import org.mycore.common.xml.MCRXMLFunctions;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRContentTypes;
import org.mycore.datamodel.niofs.MCRFileAttributes;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.filter.MCRSecureTokenV2FilterConfig;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import com.google.gson.stream.JsonWriter;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.UriInfo;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRJSONFileVisitor extends SimpleFileVisitor<Path> {
private JsonWriter jw;
private String baseURL;
private String objId;
private String derId;
public MCRJSONFileVisitor(JsonWriter jw, MCRObjectID objId, MCRObjectID derId, UriInfo info, Application app) {
super();
this.jw = jw;
this.baseURL = MCRJerseyUtil.getBaseURL(info, app);
this.objId = objId.toString();
this.derId = derId.toString();
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
jw.beginObject();
writePathInfo(dir, attrs);
jw.name("children").beginArray();
return super.preVisitDirectory(dir, attrs);
}
private String writePathInfo(Path path, BasicFileAttributes attrs) throws IOException {
MCRPath mcrPath = MCRPath.toMCRPath(path);
MCRPath relativePath = mcrPath.getRoot().relativize(mcrPath);
boolean isRoot = mcrPath.getNameCount() == 0;
jw.name("type").value(attrs.isDirectory() ? "directory" : "file");
if (isRoot) {
jw.name("mycoreobject").value(objId);
jw.name("mycorederivate").value(mcrPath.getOwner());
}
jw.name("name").value(isRoot ? "" : mcrPath.getFileName().toString());
String pathString;
String urlPathString;
try {
pathString = toStringValue(relativePath, attrs.isDirectory());
urlPathString = MCRXMLFunctions.encodeURIPath(pathString);
jw.name("path").value(pathString);
jw.name("urlPath").value(urlPathString);
} catch (URISyntaxException e) {
throw new IOException("Can't encode file path to URI " + relativePath, e);
}
if (!isRoot) {
jw.name("parentPath").value(toStringValue(relativePath.getParent(), true));
}
addBasicAttributes(path, attrs);
return urlPathString;
}
private void addBasicAttributes(Path path, BasicFileAttributes attrs) throws IOException {
jw.name("size").value(attrs.size());
jw.name("time").beginObject();
jw.name("created").value(attrs.creationTime().toString());
jw.name("modified").value(attrs.lastModifiedTime().toString());
jw.name("accessed").value(attrs.lastAccessTime().toString());
jw.endObject();
if (attrs.isRegularFile()) {
jw.name("contentType").value(MCRContentTypes.probeContentType(path));
if (attrs instanceof MCRFileAttributes<?> fileAttrs) {
jw.name("md5").value(fileAttrs.md5sum());
}
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
jw.beginObject();
String urlPathString = writePathInfo(file, attrs);
jw.name("extension").value(getFileExtension(file.getFileName().toString()));
jw.name("href").value(getHref(urlPathString));
jw.endObject();
return super.visitFile(file, attrs);
}
private String getHref(String urlPathString) {
return MCRSecureTokenV2FilterConfig.getFileNodeServletSecured(
MCRObjectID.getInstance(derId), urlPathString.substring(1), this.baseURL);
}
private static String getFileExtension(String fileName) {
if (fileName.endsWith(".")) {
return "";
}
int pos = fileName.lastIndexOf(".");
return pos == -1 ? "" : fileName.substring(pos + 1);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
jw.endArray();
jw.endObject();
return super.postVisitDirectory(dir, exc);
}
private static String toStringValue(MCRPath relativePath, boolean isDirectory) {
if (relativePath == null) {
return SEPARATOR_STRING;
}
String pathString = relativePath.toString();
if (pathString.isEmpty()) {
return SEPARATOR_STRING;
}
if (pathString.equals(SEPARATOR_STRING)) {
return SEPARATOR_STRING;
}
if (isDirectory) {
return SEPARATOR + pathString + SEPARATOR;
} else {
return SEPARATOR + pathString;
}
}
}
| 5,979 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIObjectsHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPIObjectsHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRContentTransformerFactory;
import org.mycore.datamodel.common.MCRObjectIDDate;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetaClassification;
import org.mycore.datamodel.metadata.MCRMetaLinkID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.datamodel.niofs.MCRPathXML;
import org.mycore.frontend.idmapper.MCRIDMapper;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.restapi.v1.MCRRestAPIObjects;
import org.mycore.restapi.v1.errors.MCRRestAPIError;
import org.mycore.restapi.v1.errors.MCRRestAPIException;
import org.mycore.restapi.v1.utils.MCRRestAPISortObject.SortOrder;
import com.google.gson.stream.JsonWriter;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.CacheControl;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.ResponseBuilder;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;
/**
* main utility class that handles REST requests
*
* to filter the XML output of showMCRObject, set the properties:
* MCR.RestAPI.v1.Filter.XML
* to your ContentTransformer-ID,
* MCR.ContentTransformer.[your ContentTransformer-ID here].Class
* to your ContentTransformer's class and
* MCR.ContentTransformer.[your ContentTransformer-ID here].Stylesheet
* to your filtering stylesheet.
*
* @author Robert Stephan
* @author Christoph Neidahl
*
*/
public class MCRRestAPIObjectsHelper {
private static final String GENERAL_ERROR_MSG = "A problem occured while fetching the data.";
private static Logger LOGGER = LogManager.getLogger(MCRRestAPIObjectsHelper.class);
private static SimpleDateFormat SDF_UTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
private static MCRIDMapper ID_MAPPER = MCRConfiguration2
.<MCRIDMapper>getInstanceOf(MCRIDMapper.MCR_PROPERTY_CLASS).get();
public static Response showMCRObject(String pathParamId, String queryParamStyle, UriInfo info, Application app)
throws MCRRestAPIException {
MCRObjectID mcrObjId = retrieveMCRObjectID(pathParamId);
MCRObject mcrObj = MCRMetadataManager.retrieveMCRObject(mcrObjId);
Document doc = mcrObj.createXML();
Element eStructure = doc.getRootElement().getChild("structure");
if (queryParamStyle != null && !MCRRestAPIObjects.STYLE_DERIVATEDETAILS.equals(queryParamStyle)) {
throw new MCRRestAPIException(Response.Status.BAD_REQUEST,
new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER,
"The value of parameter {style} is not allowed.",
"Allowed values for {style} parameter are: " + MCRRestAPIObjects.STYLE_DERIVATEDETAILS));
}
if (MCRRestAPIObjects.STYLE_DERIVATEDETAILS.equals(queryParamStyle) && eStructure != null) {
Element eDerObjects = eStructure.getChild("derobjects");
if (eDerObjects != null) {
for (Element eDer : eDerObjects.getChildren("derobject")) {
String derID = eDer.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE);
Element currentDerElement = eDer;
try {
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derID));
eDer.addContent(der.createXML().getRootElement().detach());
//<mycorederivate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:noNamespaceSchemaLocation="datamodel-derivate.xsd" ID="cpr_derivate_00003760" label="display_image" version="1.3">
// <derivate display="true">
currentDerElement = eDer.getChild("mycorederivate").getChild("derivate");
Document docContents = listDerivateContentAsXML(
MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derID)), "/", -1, info, app);
if (docContents.hasRootElement()) {
eDer.addContent(docContents.getRootElement().detach());
}
} catch (MCRException e) {
currentDerElement.addContent(new Comment("Error: Derivate not found."));
} catch (IOException e) {
currentDerElement
.addContent(new Comment("Error: Derivate content could not be listed: " + e.getMessage()));
}
}
}
}
StringWriter sw = new StringWriter();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
try {
String filterId = MCRConfiguration2.getString("MCR.RestAPI.v1.Filter.XML").orElse("");
if (filterId.length() > 0) {
MCRContentTransformer trans = MCRContentTransformerFactory.getTransformer(filterId);
Document filteredDoc = trans.transform(new MCRJDOMContent(doc)).asXML();
outputter.output(filteredDoc, sw);
} else {
outputter.output(doc, sw);
}
} catch (JDOMException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(
MCRRestAPIError.CODE_INTERNAL_ERROR, "Unable to transform MCRContent to XML document", e.getMessage()));
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(
MCRRestAPIError.CODE_INTERNAL_ERROR, "Unable to retrieve/transform MyCoRe object", e.getMessage()));
}
return Response.ok(sw.toString())
.type("application/xml")
.build();
}
public static Response showMCRDerivate(String paramMcrObjID, String paramMcrDerID, UriInfo info, Application app,
boolean withDetails) throws MCRRestAPIException {
try {
MCRObjectID mcrObjId = retrieveMCRObjectID(paramMcrObjID);
MCRObjectID derObjId = retrieveMCRDerivateID(mcrObjId, paramMcrDerID);
MCRDerivate derObj = MCRMetadataManager.retrieveMCRDerivate(derObjId);
Document doc = derObj.createXML();
if (withDetails) {
Document docContent = listDerivateContentAsXML(derObj, "/", -1, info, app);
if (docContent != null && docContent.hasRootElement()) {
doc.getRootElement().addContent(docContent.getRootElement().detach());
}
}
StringWriter sw = new StringWriter();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, sw);
return Response.ok(sw.toString())
.type("application/xml")
.build();
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
}
}
private static String listDerivateContentAsJson(MCRDerivate derObj, String path, int depth, UriInfo info,
Application app)
throws IOException {
StringWriter sw = new StringWriter();
MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
root = MCRPath.toMCRPath(root.resolve(path));
if (depth == -1) {
depth = Integer.MAX_VALUE;
}
if (root != null) {
JsonWriter writer = new JsonWriter(sw);
Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), depth,
new MCRJSONFileVisitor(writer, derObj.getOwnerID(), derObj.getId(), info, app));
writer.close();
}
return sw.toString();
}
private static Document listDerivateContentAsXML(MCRDerivate derObj, String path, int depth, UriInfo info,
Application app)
throws IOException {
Document doc = new Document();
MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
root = MCRPath.toMCRPath(root.resolve(path));
if (depth == -1) {
depth = Integer.MAX_VALUE;
}
if (root != null) {
Element eContents = new Element("contents");
eContents.setAttribute("mycoreobject", derObj.getOwnerID().toString());
eContents.setAttribute("mycorederivate", derObj.getId().toString());
doc.addContent(eContents);
if (!path.endsWith("/")) {
path += "/";
}
MCRPath p = MCRPath.getPath(derObj.getId().toString(), path);
if (p != null && Files.exists(p)) {
Element eRoot = MCRPathXML.getDirectoryXML(p).getRootElement();
eContents.addContent(eRoot.detach());
createXMLForSubdirectories(p, eRoot, 1, depth);
}
//add href Attributes
String baseURL = MCRJerseyUtil.getBaseURL(info, app)
+ MCRConfiguration2.getStringOrThrow("MCR.RestAPI.v1.Files.URL.path");
baseURL = baseURL.replace("${mcrid}", derObj.getOwnerID().toString()).replace("${derid}",
derObj.getId().toString());
XPathExpression<Element> xp = XPathFactory.instance().compile(".//child[@type='file']", Filters.element());
for (Element e : xp.evaluate(eContents)) {
String uri = e.getChildText("uri");
if (uri != null) {
int pos = uri.lastIndexOf(":/");
String subPath = uri.substring(pos + 2);
while (subPath.startsWith("/")) {
subPath = subPath.substring(1);
}
e.setAttribute("href", baseURL + subPath);
}
}
}
return doc;
}
private static void createXMLForSubdirectories(MCRPath mcrPath, Element currentElement, int currentDepth,
int maxDepth) {
if (currentDepth < maxDepth) {
XPathExpression<Element> xp = XPathFactory.instance().compile("./children/child[@type='directory']",
Filters.element());
for (Element e : xp.evaluate(currentElement)) {
String name = e.getChildTextNormalize("name");
try {
MCRPath pChild = (MCRPath) mcrPath.resolve(name);
Document doc = MCRPathXML.getDirectoryXML(pChild);
Element eChildren = doc.getRootElement().getChild("children");
if (eChildren != null) {
e.addContent(eChildren.detach());
createXMLForSubdirectories(pChild, e, currentDepth + 1, maxDepth);
}
} catch (IOException ex) {
//ignore
}
}
}
}
/**
* returns a list of objects
* @param info - the injected Jersey URIInfo object
*
* @param format - the output format ('xml'|'json')
* @param filter - a filter criteria
* @param sort - the sort criteria
*
* @return a Jersey response object
* @see MCRRestAPIObjects#listObjects(UriInfo, String, String, String)
*
*/
public static Response listObjects(UriInfo info, String format, String filter,
String sort) throws MCRRestAPIException {
List<MCRRestAPIError> errors = new ArrayList<>();
//analyze sort
MCRRestAPISortObject sortObj = null;
try {
sortObj = createSortObject(sort);
} catch (MCRRestAPIException rae) {
errors.addAll(rae.getErrors());
}
//analyze format
if (!format.equals(MCRRestAPIObjects.FORMAT_JSON) && !format.equals(MCRRestAPIObjects.FORMAT_XML)) {
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The parameter 'format' is wrong.",
"Allowed values for format are 'json' or 'xml'."));
}
//analyze filter
List<String> projectIDs = new ArrayList<>();
List<String> typeIDs = new ArrayList<>();
String lastModifiedBefore = null;
String lastModifiedAfter = null;
if (filter != null) {
for (String s : filter.split(";")) {
if (s.startsWith("project:")) {
projectIDs.add(s.substring(8));
continue;
}
if (s.startsWith("type:")) {
typeIDs.add(s.substring(5));
continue;
}
if (s.startsWith("lastModifiedBefore:")) {
if (!validateDateInput(s.substring(19))) {
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER,
"The parameter 'filter' is wrong.",
"The value of lastModifiedBefore could not be parsed. "
+ "Please use UTC syntax: yyyy-MM-dd'T'HH:mm:ss'Z'."));
continue;
}
if (lastModifiedBefore == null) {
lastModifiedBefore = s.substring(19);
} else if (s.substring(19).compareTo(lastModifiedBefore) < 0) {
lastModifiedBefore = s.substring(19);
}
continue;
}
if (s.startsWith("lastModifiedAfter:")) {
if (!validateDateInput(s.substring(18))) {
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER,
"The parameter 'filter' is wrong.",
"The value of lastModifiedAfter could not be parsed. "
+ "Please use UTC syntax: yyyy-MM-dd'T'HH:mm:ss'Z'."));
continue;
}
if (lastModifiedAfter == null) {
lastModifiedAfter = s.substring(18);
} else if (s.substring(18).compareTo(lastModifiedAfter) > 0) {
lastModifiedAfter = s.substring(18);
}
continue;
}
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The parameter 'filter' is wrong.",
"The syntax of the filter '" + s
+ "'could not be parsed. The syntax should be [filterName]:[value]. "
+ "Allowed filterNames are 'project', 'type', 'lastModifiedBefore' and 'lastModifiedAfter'."));
}
}
if (errors.size() > 0) {
throw new MCRRestAPIException(Status.BAD_REQUEST, errors);
}
//Parameters are validated - continue to retrieve data
//retrieve MCRIDs by Type and Project ID
Set<String> mcrIDs = new HashSet<>();
if (projectIDs.isEmpty()) {
if (typeIDs.isEmpty()) {
mcrIDs = MCRXMLMetadataManager.instance().listIDs().stream().filter(id -> !id.contains("_derivate_"))
.collect(Collectors.toSet());
} else {
for (String t : typeIDs) {
mcrIDs.addAll(MCRXMLMetadataManager.instance().listIDsOfType(t));
}
}
} else {
if (typeIDs.isEmpty()) {
for (String id : MCRXMLMetadataManager.instance().listIDs()) {
String[] split = id.split("_");
if (!split[1].equals("derivate") && projectIDs.contains(split[0])) {
mcrIDs.add(id);
}
}
} else {
for (String p : projectIDs) {
for (String t : typeIDs) {
mcrIDs.addAll(MCRXMLMetadataManager.instance().listIDsForBase(p + "_" + t));
}
}
}
}
//Filter by modifiedBefore and modifiedAfter
List<String> l = new ArrayList<>(mcrIDs);
List<MCRObjectIDDate> objIdDates = new ArrayList<>();
try {
objIdDates = MCRXMLMetadataManager.instance().retrieveObjectDates(l);
} catch (IOException e) {
//TODO
}
if (lastModifiedAfter != null || lastModifiedBefore != null) {
List<MCRObjectIDDate> testObjIdDates = objIdDates;
objIdDates = new ArrayList<>();
for (MCRObjectIDDate oid : testObjIdDates) {
String test = SDF_UTC.format(oid.getLastModified());
if (lastModifiedAfter != null && test.compareTo(lastModifiedAfter) < 0) {
continue;
}
if (lastModifiedBefore != null
&& lastModifiedBefore.compareTo(test.substring(0, lastModifiedBefore.length())) < 0) {
continue;
}
objIdDates.add(oid);
}
}
//sort if necessary
if (sortObj != null) {
objIdDates.sort(new MCRRestAPISortObjectComparator(sortObj));
}
//output as XML
if (MCRRestAPIObjects.FORMAT_XML.equals(format)) {
Element eMcrobjects = new Element("mycoreobjects");
Document docOut = new Document(eMcrobjects);
eMcrobjects.setAttribute("numFound", Integer.toString(objIdDates.size()));
for (MCRObjectIDDate oid : objIdDates) {
Element eMcrObject = new Element("mycoreobject");
eMcrObject.setAttribute("ID", oid.getId());
eMcrObject.setAttribute("lastModified", SDF_UTC.format(oid.getLastModified()));
eMcrObject.setAttribute("href", info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
eMcrobjects.addContent(eMcrObject);
}
try {
StringWriter sw = new StringWriter();
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(docOut, sw);
return Response.ok(sw.toString())
.type("application/xml; charset=UTF-8")
.build();
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
}
}
//output as JSON
if (MCRRestAPIObjects.FORMAT_JSON.equals(format)) {
StringWriter sw = new StringWriter();
try {
JsonWriter writer = new JsonWriter(sw);
writer.setIndent(" ");
writer.beginObject();
writer.name("numFound").value(objIdDates.size());
writer.name("mycoreobjects");
writer.beginArray();
for (MCRObjectIDDate oid : objIdDates) {
writer.beginObject();
writer.name("ID").value(oid.getId());
writer.name("lastModified").value(SDF_UTC.format(oid.getLastModified()));
writer.name("href").value(info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
writer.endObject();
}
writer.endArray();
writer.endObject();
writer.close();
return Response.ok(sw.toString())
.type("application/json; charset=UTF-8")
.build();
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
}
}
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "A problem in programm flow", null));
}
/**
* returns a list of derivate objects
* @param info - the injected Jersey URIInfo object
*
* @param paramMcrObjID - the MyCoRe object id as string
* @param format - the output format ('xml'|'json')
* @param sort - the sort criteria
*
* @return a Jersey response object
* @see MCRRestAPIObjects#listDerivates(UriInfo, String, String, String)
*/
public static Response listDerivates(UriInfo info, String paramMcrObjID, String format,
String sort) throws MCRRestAPIException {
List<MCRRestAPIError> errors = new ArrayList<>();
MCRRestAPISortObject sortObj = null;
try {
sortObj = createSortObject(sort);
} catch (MCRRestAPIException rae) {
errors.addAll(rae.getErrors());
}
//analyze format
if (!format.equals(MCRRestAPIObjects.FORMAT_JSON) && !format.equals(MCRRestAPIObjects.FORMAT_XML)) {
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The Parameter format is wrong.",
"Allowed values for format are 'json' or 'xml'."));
}
if (errors.size() > 0) {
throw new MCRRestAPIException(Status.BAD_REQUEST, errors);
}
//Parameters are checked - continue to retrieve data
MCRObjectID mcrObjId = retrieveMCRObjectID(paramMcrObjID);
List<MCRObjectIDDate> objIdDates = MCRMetadataManager.retrieveMCRObject(mcrObjId)
.getStructure().getDerivates().stream()
.map(MCRMetaLinkID::getXLinkHrefID).filter(MCRMetadataManager::exists).map(id -> new MCRObjectIDDate() {
long lastModified;
{
try {
lastModified = MCRXMLMetadataManager.instance().getLastModified(id);
} catch (IOException e) {
lastModified = 0;
LOGGER.error(
"Exception while getting last modified of {}",
id, e);
}
}
@Override
public String getId() {
return id.toString();
}
@Override
public Date getLastModified() {
return new Date(lastModified);
}
}).sorted(new MCRRestAPISortObjectComparator(sortObj)).collect(Collectors.toList());
//output as XML
if (MCRRestAPIObjects.FORMAT_XML.equals(format)) {
Element eDerObjects = new Element("derobjects");
Document docOut = new Document(eDerObjects);
eDerObjects.setAttribute("numFound", Integer.toString(objIdDates.size()));
for (MCRObjectIDDate oid : objIdDates) {
Element eDerObject = new Element("derobject");
eDerObject.setAttribute("ID", oid.getId());
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(oid.getId()));
String mcrID = der.getDerivate().getMetaLink().getXLinkHref();
eDerObject.setAttribute("metadata", mcrID);
if (der.getDerivate().getClassifications().size() > 0) {
StringBuilder c = new StringBuilder();
for (int i = 0; i < der.getDerivate().getClassifications().size(); i++) {
if (i > 0) {
c.append(' ');
}
MCRMetaClassification cl = der.getDerivate().getClassifications().get(i);
c.append(cl.getClassId()).append(':').append(cl.getCategId());
}
eDerObject.setAttribute("classifications", c.toString());
}
eDerObject.setAttribute("lastModified", SDF_UTC.format(oid.getLastModified()));
eDerObject.setAttribute("href", info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
eDerObjects.addContent(eDerObject);
}
try {
StringWriter sw = new StringWriter();
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(docOut, sw);
return Response.ok(sw.toString())
.type("application/xml; charset=UTF-8")
.build();
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
}
}
//output as JSON
if (MCRRestAPIObjects.FORMAT_JSON.equals(format)) {
StringWriter sw = new StringWriter();
try {
JsonWriter writer = new JsonWriter(sw);
writer.setIndent(" ");
writer.beginObject();
writer.name("numFound").value(objIdDates.size());
writer.name("mycoreobjects");
writer.beginArray();
for (MCRObjectIDDate oid : objIdDates) {
writer.beginObject();
writer.name("ID").value(oid.getId());
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(oid.getId()));
String mcrID = der.getDerivate().getMetaLink().getXLinkHref();
writer.name("metadata").value(mcrID);
writer.name("lastModified").value(SDF_UTC.format(oid.getLastModified()));
writer.name("href").value(info.getAbsolutePathBuilder().path(oid.getId()).build().toString());
writer.endObject();
}
writer.endArray();
writer.endObject();
writer.close();
return Response.ok(sw.toString())
.type("application/json; charset=UTF-8")
.build();
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG, e.getMessage()));
}
}
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Unexepected program flow termination.",
"Please contact a developer!"));
}
/**
* lists derivate content (file listing)
* @param info - the Jersey UriInfo Object
* @param request - the HTTPServletRequest object
* @param paramMcrObjID - the MyCoRe object id
* @param paramMcrDerID - the MyCoRe derivate id
* @param format - the output format ('xml'|'json')
* @param path - the sub path of a directory inside the derivate
* @param depth - the level of subdirectories to be returned
* @return a Jersey Response object
*/
public static Response listContents(UriInfo info, Application app, Request request, String paramMcrObjID,
String paramMcrDerID, String format, String path, int depth) throws MCRRestAPIException {
if (!format.equals(MCRRestAPIObjects.FORMAT_JSON) && !format.equals(MCRRestAPIObjects.FORMAT_XML)) {
throw new MCRRestAPIException(Response.Status.BAD_REQUEST,
new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "The syntax of format parameter is wrong.",
"Allowed values for format are 'json' or 'xml'."));
}
MCRObjectID mcrObjId = retrieveMCRObjectID(paramMcrObjID);
MCRObjectID derObjId = retrieveMCRDerivateID(mcrObjId, paramMcrDerID);
MCRDerivate derObj = MCRMetadataManager.retrieveMCRDerivate(derObjId);
try {
MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
BasicFileAttributes readAttributes = Files.readAttributes(root, BasicFileAttributes.class);
Date lastModified = new Date(readAttributes.lastModifiedTime().toMillis());
ResponseBuilder responseBuilder = request.evaluatePreconditions(lastModified);
if (responseBuilder != null) {
return responseBuilder.build();
}
switch (format) {
case MCRRestAPIObjects.FORMAT_XML:
Document docOut = listDerivateContentAsXML(derObj, path, depth, info, app);
try (StringWriter sw = new StringWriter()) {
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
xout.output(docOut, sw);
return response(sw.toString(), "application/xml", lastModified);
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, GENERAL_ERROR_MSG,
e.getMessage()));
}
case MCRRestAPIObjects.FORMAT_JSON:
if (MCRRestAPIObjects.FORMAT_JSON.equals(format)) {
String result = listDerivateContentAsJson(derObj, path, depth, info, app);
return response(result, "application/json", lastModified);
}
default:
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR,
"Unexepected program flow termination.",
"Please contact a developer!"));
}
} catch (IOException e) {
throw new MCRRestAPIException(Response.Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(
MCRRestAPIError.CODE_INTERNAL_ERROR, "Unexepected program flow termination.", e.getMessage()));
}
}
/**
* returns the URL of the main document of a derivate
*
* @param info - the Jersey UriInfo object
* @param paramMcrObjID - the MyCoRe object id
* @param paramMcrDerID - the MyCoRe derivate id
*
* @return the Resolving URL for the main document of the derivate
*/
public static String retrieveMaindocURL(UriInfo info, String paramMcrObjID, String paramMcrDerID, Application app) {
try {
MCRObjectID mcrObjId = retrieveMCRObjectID(paramMcrObjID);
MCRObjectID mcrDerId = retrieveMCRDerivateID(mcrObjId, paramMcrDerID);
MCRDerivate derObj = MCRMetadataManager.retrieveMCRDerivate(mcrDerId);
String maindoc = derObj.getDerivate().getInternals().getMainDoc();
String baseURL = MCRJerseyUtil.getBaseURL(info, app)
+ MCRConfiguration2.getStringOrThrow("MCR.RestAPI.v1.Files.URL.path");
baseURL = baseURL.replace("${mcrid}", mcrObjId.toString()).replace("${derid}", mcrDerId.toString());
return baseURL + maindoc;
} catch (MCRRestAPIException rae) {
return null;
}
}
private static Response response(String response, String type, Date lastModified) {
byte[] responseBytes = response.getBytes(StandardCharsets.UTF_8);
String mimeType = type + "; charset=UTF-8";
CacheControl cacheControl = new CacheControl();
cacheControl.setNoTransform(false);
cacheControl.setMaxAge(0);
return Response.ok(responseBytes, mimeType).lastModified(lastModified)
.header("Content-Length", responseBytes.length)
.cacheControl(cacheControl).build();
}
/**
* validates the given String if it matches the UTC syntax or the beginning of it
* @return true, if it is valid
*/
private static boolean validateDateInput(String test) {
String base = "0000-00-00T00:00:00Z";
if (test.length() > base.length()) {
return false;
}
test = test + base.substring(test.length());
try {
SDF_UTC.parse(test);
} catch (ParseException e) {
return false;
}
return true;
}
private static MCRRestAPISortObject createSortObject(String input) throws MCRRestAPIException {
if (input == null) {
return null;
}
List<MCRRestAPIError> errors = new ArrayList<>();
MCRRestAPISortObject result = new MCRRestAPISortObject();
String[] data = input.split(":");
if (data.length == 2) {
result.setField(data[0].replace("|", ""));
String sortOrder = data[1].toLowerCase(Locale.GERMAN).replace("|", "");
if (!"ID".equals(result.getField()) && !"lastModified".equals(result.getField())) {
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_QUERY_PARAMETER, "The sortField is wrong",
"Allowed values are 'ID' and 'lastModified'."));
}
if (Objects.equals(sortOrder, "asc")) {
result.setOrder(SortOrder.ASC);
}
if (Objects.equals(sortOrder, "desc")) {
result.setOrder(SortOrder.DESC);
}
if (result.getOrder() == null) {
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_QUERY_PARAMETER, "The sortOrder is wrong",
"Allowed values for sortOrder are 'asc' and 'desc'."));
}
} else {
errors.add(new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_QUERY_PARAMETER, "The sort parameter is wrong.",
"The syntax should be [sortField]:[sortOrder]."));
}
if (errors.size() > 0) {
throw new MCRRestAPIException(Status.BAD_REQUEST, errors);
}
return result;
}
private static MCRObjectID retrieveMCRObjectID(String paramMcrObjId) throws MCRRestAPIException {
Optional<MCRObjectID> optObjId = ID_MAPPER.mapMCRObjectID(paramMcrObjId);
if (optObjId.isEmpty() || !MCRMetadataManager.exists(optObjId.get())) {
throw new MCRRestAPIException(Response.Status.NOT_FOUND,
new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND,
"There is no object with the given MyCoRe ID '" + paramMcrObjId + "'.", null));
}
return optObjId.get();
}
private static MCRObjectID retrieveMCRDerivateID(MCRObjectID parentObjId, String paramMcrDerId)
throws MCRRestAPIException {
Optional<MCRObjectID> optDerObjId = ID_MAPPER.mapMCRDerivateID(parentObjId, paramMcrDerId);
if (optDerObjId.isEmpty() || !MCRMetadataManager.exists(optDerObjId.get())) {
throw new MCRRestAPIException(Response.Status.NOT_FOUND,
new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Derivate " + paramMcrDerId + " not found.",
"The MyCoRe Object with id '" + parentObjId
+ "' does not contain a derivate with id '" + paramMcrDerId + "'."));
}
return optDerObjId.get();
}
/**
* checks if the given path is a directory and contains children
*
* @param p - the path to check
* @return true, if there are children
*/
public static boolean hasChildren(Path p) {
try {
if (Files.isDirectory(p)) {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(p)) {
return ds.iterator().hasNext();
}
}
} catch (IOException e) {
LOGGER.error(e);
}
return false;
}
}
| 38,222 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIUploadHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPIUploadHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.access.MCRAccessException;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRUtils;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetaClassification;
import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID;
import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkIDFactory;
import org.mycore.datamodel.metadata.MCRMetaIFS;
import org.mycore.datamodel.metadata.MCRMetaLangText;
import org.mycore.datamodel.metadata.MCRMetaLinkID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter;
import org.mycore.datamodel.niofs.utils.MCRTreeCopier;
import org.mycore.frontend.cli.MCRObjectCommands;
import org.mycore.restapi.v1.errors.MCRRestAPIError;
import org.mycore.restapi.v1.errors.MCRRestAPIException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.UriInfo;
public class MCRRestAPIUploadHelper {
private static final Logger LOGGER = LogManager.getLogger(MCRRestAPIUploadHelper.class);
private static java.nio.file.Path UPLOAD_DIR = Paths
.get(MCRConfiguration2.getStringOrThrow("MCR.RestAPI.v1.Upload.Directory"));
static {
if (!Files.exists(UPLOAD_DIR)) {
try {
Files.createDirectories(UPLOAD_DIR);
} catch (IOException e) {
LOGGER.error(e);
}
}
}
/**
*
* uploads a MyCoRe Object
* based upon:
* http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/
*
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param uploadedInputStream - the inputstream from HTTP Post request
* @param fileDetails - the file information from HTTP Post request
* @return a Jersey Response object
*/
public static Response uploadObject(UriInfo info, HttpServletRequest request, InputStream uploadedInputStream,
FormDataContentDisposition fileDetails) throws MCRRestAPIException {
java.nio.file.Path fXML = null;
try {
SAXBuilder sb = new SAXBuilder();
Document docOut = sb.build(uploadedInputStream);
MCRObjectID mcrID = MCRObjectID.getInstance(docOut.getRootElement().getAttributeValue("ID"));
fXML = UPLOAD_DIR.resolve(mcrID.getBase() + '_' + UUID.randomUUID() + ".xml");
XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
try (BufferedWriter bw = Files.newBufferedWriter(fXML, StandardCharsets.UTF_8)) {
xmlOut.output(docOut, bw);
}
MCRObject object = MCRObjectCommands.updateFromFile(fXML.toString(), false);// handles "create" as well
mcrID = Objects.requireNonNull(object, "An error occurred while the object was created").getId();
return Response.created(info.getBaseUriBuilder().path("objects/" + mcrID).build())
.type("application/xml; charset=UTF-8")
.build();
} catch (Exception e) {
LOGGER.error("Unable to Upload file: {}", String.valueOf(fXML), e);
throw new MCRRestAPIException(Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER,
"Unable to Upload file: " + fXML, e.getMessage()));
} finally {
if (fXML != null) {
try {
Files.delete(fXML);
} catch (IOException e) {
LOGGER.error("Unable to delete temporary workflow file: {}", String.valueOf(fXML), e);
}
}
}
}
/**
* creates or updates a MyCoRe derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param mcrObjID - the MyCoRe Object ID
* @param label - the label of the new derivate
* @param overwriteOnExisting, if true, an existing MyCoRe derivate
* with the given label or classification will be returned
* @return a Jersey Response object
*/
public static Response uploadDerivate(UriInfo info, HttpServletRequest request, String mcrObjID, String label,
String classifications, boolean overwriteOnExisting) {
Response response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
// File fXML = null;
MCRObjectID mcrObjIDObj = MCRObjectID.getInstance(mcrObjID);
try {
MCRObject mcrObj = MCRMetadataManager.retrieveMCRObject(mcrObjIDObj);
MCRObjectID derID = null;
final MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance();
if (overwriteOnExisting) {
final List<MCRMetaEnrichedLinkID> currentDerivates = mcrObj.getStructure().getDerivates();
if (label != null && label.length() > 0) {
for (MCRMetaLinkID derLink : currentDerivates) {
if (label.equals(derLink.getXLinkLabel()) || label.equals(derLink.getXLinkTitle())) {
derID = derLink.getXLinkHrefID();
}
}
}
if (derID == null && classifications != null && classifications.length() > 0) {
final List<MCRCategoryID> categories = Stream.of(classifications.split(" "))
.map(MCRCategoryID::fromString)
.collect(Collectors.toList());
final List<MCRCategoryID> notExisting = categories.stream().filter(Predicate.not(dao::exist))
.collect(Collectors.toList());
if (notExisting.size() > 0) {
final String missingIDS = notExisting.stream()
.map(MCRCategoryID::toString).collect(Collectors.joining(", "));
throw new MCRRestAPIException(Status.NOT_FOUND,
new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Classification not found.",
"There are no classification with the IDs: " + missingIDS));
}
final Optional<MCRMetaEnrichedLinkID> matchingDerivate = currentDerivates.stream()
.filter(derLink -> {
final Set<MCRCategoryID> clazzSet = new HashSet<>(derLink.getClassifications());
return categories.stream().allMatch(clazzSet::contains);
}).findFirst();
if (matchingDerivate.isPresent()) {
derID = matchingDerivate.get().getXLinkHrefID();
}
}
}
if (derID == null) {
MCRDerivate mcrDerivate = new MCRDerivate();
if (label != null && label.length() > 0) {
mcrDerivate.getDerivate().getTitles()
.add(new MCRMetaLangText("title", null, null, 0, null, label));
}
MCRObjectID zeroDerId = MCRObjectID
.getInstance(MCRObjectID.formatID(mcrObjIDObj.getProjectId() + "_derivate", 0));
mcrDerivate.setId(zeroDerId);
mcrDerivate.setSchema("datamodel-derivate.xsd");
mcrDerivate.getDerivate().setLinkMeta(new MCRMetaLinkID("linkmeta", mcrObjIDObj, null, null));
mcrDerivate.getDerivate().setInternals(new MCRMetaIFS("internal", null));
if (classifications != null && classifications.length() > 0) {
final List<MCRMetaClassification> currentClassifications;
currentClassifications = mcrDerivate.getDerivate().getClassifications();
Stream.of(classifications.split(" "))
.map(MCRCategoryID::fromString)
.filter(dao::exist)
.map(categoryID -> new MCRMetaClassification("classification", 0, null, categoryID))
.forEach(currentClassifications::add);
}
MCRMetadataManager.create(mcrDerivate);
MCRMetadataManager.addOrUpdateDerivateToObject(mcrObjIDObj,
MCRMetaEnrichedLinkIDFactory.getInstance().getDerivateLink(mcrDerivate),
mcrDerivate.isImportMode());
derID = mcrDerivate.getId();
}
response = Response
.created(info.getBaseUriBuilder().path("objects/" + mcrObjID + "/derivates/" + derID).build())
.type("application/xml; charset=UTF-8")
.build();
} catch (Exception e) {
LOGGER.error("Exeption while uploading derivate", e);
}
return response;
}
/**
* uploads a file into a given derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - a MyCoRe Object ID
* @param pathParamMcrDerID - a MyCoRe Derivate ID
* @param uploadedInputStream - the inputstream from HTTP Post request
* @param fileDetails - the file information from HTTP Post request
* @param formParamPath - the path of the file inside the derivate
* @param formParamMaindoc - true, if this file should be marked as maindoc
* @param formParamUnzip - true, if the upload is zip file that should be unzipped inside the derivate
* @param formParamMD5 - the MD5 sum of the uploaded file
* @param formParamSize - the size of the uploaded file
* @return a Jersey Response object
*/
public static Response uploadFile(UriInfo info, HttpServletRequest request, String pathParamMcrObjID,
String pathParamMcrDerID, InputStream uploadedInputStream, FormDataContentDisposition fileDetails,
String formParamPath, boolean formParamMaindoc, boolean formParamUnzip, String formParamMD5,
Long formParamSize) throws MCRRestAPIException {
SortedMap<String, String> parameter = new TreeMap<>();
parameter.put("mcrObjectID", pathParamMcrObjID);
parameter.put("mcrDerivateID", pathParamMcrDerID);
parameter.put("path", formParamPath);
parameter.put("maindoc", Boolean.toString(formParamMaindoc));
parameter.put("unzip", Boolean.toString(formParamUnzip));
parameter.put("md5", formParamMD5);
parameter.put("size", Long.toString(formParamSize));
MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
if (!MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
throw new MCRRestAPIException(Status.FORBIDDEN,
new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "Could not add file to derivate",
"You do not have the permission to write to " + derID));
}
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
java.nio.file.Path derDir = null;
String path = null;
if (!der.getOwnerID().equals(objID)) {
throw new MCRRestAPIException(Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Derivate object mismatch",
"Derivate " + derID + " belongs to a different object: " + objID));
}
try {
derDir = UPLOAD_DIR.resolve(derID.toString());
if (Files.exists(derDir)) {
Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
}
path = formParamPath.replace("\\", "/").replace("../", "");
while (path.startsWith("/")) {
path = path.substring(1);
}
MCRPath derRoot = MCRPath.getPath(derID.toString(), "/");
if (Files.notExists(derRoot)) {
derRoot.getFileSystem().createRoot(derID.toString());
}
if (formParamUnzip) {
String maindoc = null;
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(uploadedInputStream))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
LOGGER.debug("Unzipping: {}", entry.getName());
java.nio.file.Path target = MCRUtils.safeResolve(derDir, entry.getName());
Files.createDirectories(target.getParent());
Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
if (maindoc == null && !entry.isDirectory()) {
maindoc = entry.getName();
}
}
} catch (IOException e) {
LOGGER.error(e);
}
Files.walkFileTree(derDir, new MCRTreeCopier(derDir, derRoot, true));
if (formParamMaindoc) {
der.getDerivate().getInternals().setMainDoc(maindoc);
}
} else {
java.nio.file.Path saveFile = MCRUtils.safeResolve(derDir, path);
Files.createDirectories(saveFile.getParent());
Files.copy(uploadedInputStream, saveFile, StandardCopyOption.REPLACE_EXISTING);
Files.walkFileTree(derDir, new MCRTreeCopier(derDir, derRoot, true));
if (formParamMaindoc) {
der.getDerivate().getInternals().setMainDoc(path);
}
}
MCRMetadataManager.update(der);
Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
} catch (IOException | MCRPersistenceException | MCRAccessException e) {
LOGGER.error(e);
throw new MCRRestAPIException(Status.INTERNAL_SERVER_ERROR,
new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Internal error", e.getMessage()));
}
return Response
.created(info.getBaseUriBuilder().path("objects/" + objID + "/derivates/" + derID + "/contents").build())
.type("application/xml; charset=UTF-8").build();
}
/**
* deletes all files inside a given derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - the MyCoRe Object ID
* @param pathParamMcrDerID - the MyCoRe Derivate ID
* @return a Jersey Response Object
*/
public static Response deleteAllFiles(UriInfo info, HttpServletRequest request, String pathParamMcrObjID,
String pathParamMcrDerID) {
MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
//MCRAccessManager.checkPermission uses CACHE, which seems to be dirty from other calls
MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
final MCRPath rootPath = MCRPath.getPath(der.getId().toString(), "/");
try {
Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance());
Files.createDirectory(rootPath);
} catch (IOException e) {
LOGGER.error(e);
}
}
return Response
.created(info.getBaseUriBuilder()
.path("objects/" + objID + "/derivates/" + derID + "/contents")
.build())
.type("application/xml; charset=UTF-8")
.build();
}
/**
* deletes a whole derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - the MyCoRe Object ID
* @param pathParamMcrDerID - the MyCoRe Derivate ID
* @return a Jersey Response Object
*/
public static Response deleteDerivate(UriInfo info, HttpServletRequest request, String pathParamMcrObjID,
String pathParamMcrDerID) throws MCRRestAPIException {
MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
try {
MCRMetadataManager.deleteMCRDerivate(derID);
return Response
.created(info.getBaseUriBuilder().path("objects/" + objID + "/derivates").build())
.type("application/xml; charset=UTF-8")
.build();
} catch (MCRAccessException e) {
throw new MCRRestAPIException(Status.FORBIDDEN,
new MCRRestAPIError(MCRRestAPIError.CODE_ACCESS_DENIED, "Could not delete derivate", e.getMessage()));
}
}
/**
* serializes a map of Strings into a compact JSON structure
* @param data a sorted Map of Strings
* @return a compact JSON
*/
public static String generateMessagesFromProperties(SortedMap<String, String> data) {
StringWriter sw = new StringWriter();
sw.append('{');
for (String key : data.keySet()) {
sw.append("\"").append(key).append("\"").append(':').append("\"").append(data.get(key)).append("\"")
.append(',');
}
String result = sw.toString();
if (result.length() > 1) {
result = result.substring(0, result.length() - 1);
}
result = result + "}";
return result;
}
}
| 19,964 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPISortObjectComparator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRRestAPISortObjectComparator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
import java.util.Comparator;
import java.util.Locale;
import org.mycore.datamodel.common.MCRObjectIDDate;
import org.mycore.restapi.v1.utils.MCRRestAPISortObject.SortOrder;
/**
* Comparator to sort a collection of result objects by id or date
*
* ToDo: Check if this can be replaced with SOLR functionality
*
* @author Robert Stephan
*
*/
public class MCRRestAPISortObjectComparator implements Comparator<MCRObjectIDDate> {
private MCRRestAPISortObject sortObj = null;
public MCRRestAPISortObjectComparator(MCRRestAPISortObject sortObj) {
this.sortObj = sortObj;
}
@Override
public int compare(MCRObjectIDDate o1, MCRObjectIDDate o2) {
if ("id".equals(sortObj.getField().toLowerCase(Locale.ROOT))) {
if (sortObj.getOrder() == SortOrder.ASC) {
return o1.getId().compareTo(o2.getId());
}
if (sortObj.getOrder() == SortOrder.DESC) {
return o2.getId().compareTo(o1.getId());
}
}
if ("lastmodified".equals(sortObj.getField().toLowerCase(Locale.ROOT))) {
if (sortObj.getOrder() == SortOrder.ASC) {
return o1.getLastModified().compareTo(o2.getLastModified());
}
if (sortObj.getOrder() == SortOrder.DESC) {
return o2.getLastModified().compareTo(o1.getLastModified());
}
}
return 0;
}
}
| 2,189 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPropertiesToJSONTransformer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/utils/MCRPropertiesToJSONTransformer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.MessageBodyWriter;
import jakarta.ws.rs.ext.Provider;
@Produces(MediaType.APPLICATION_JSON)
@Provider
public class MCRPropertiesToJSONTransformer implements MessageBodyWriter<Properties> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Properties.class.isAssignableFrom(type) && mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE);
}
@Override
public long getSize(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_TYPE.withCharset(StandardCharsets.UTF_8.name()));
final Type mapType = new TypeToken<Map<String, String>>() {
private static final long serialVersionUID = 1L;
}.getType();
Map<String, String> writeMap = t.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
String json = new GsonBuilder().registerTypeAdapter(mapType, new BundleMapSerializer())
.create()
.toJson(writeMap, mapType);
entityStream.write(json.getBytes(StandardCharsets.UTF_8));
}
public static class BundleMapSerializer implements JsonSerializer<Map<String, String>> {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public JsonElement serialize(final Map<String, String> bundleMap, final Type typeOfSrc,
final JsonSerializationContext context) {
final JsonObject resultJson = new JsonObject();
bundleMap.forEach((key, value) -> createFromBundleKey(resultJson, key, value));
return resultJson;
}
public static JsonObject createFromBundleKey(final JsonObject resultJson, final String key,
final String value) {
if (!key.contains(".")) {
resultJson.addProperty(key, value);
return resultJson;
}
final String currentKey = firstKey(key);
if (currentKey != null) {
final String subRightKey = key.substring(currentKey.length() + 1);
final JsonObject childJson = getJsonIfExists(resultJson, currentKey);
resultJson.add(currentKey, createFromBundleKey(childJson, subRightKey, value));
}
return resultJson;
}
private static String firstKey(final String fullKey) {
final String[] splittedKey = fullKey.split("\\.");
return (splittedKey.length != 0) ? splittedKey[0] : fullKey;
}
private static JsonObject getJsonIfExists(final JsonObject parent, final String key) {
if (parent == null) {
LOGGER.warn("Parent json parameter is null!");
return null;
}
if (parent.get(key) != null && !(parent.get(key) instanceof JsonObject)) {
throw new IllegalArgumentException("Invalid key \'" + key + "\' for parent: " + parent
+ "\nKey can not be JSON object and property or array in one time");
}
if (parent.getAsJsonObject(key) != null) {
return parent.getAsJsonObject(key);
} else {
return new JsonObject();
}
}
}
}
| 5,291 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIExceptionMapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/errors/MCRRestAPIExceptionMapper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.errors;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
/**
* maps a REST API exception to a proper response with message as JSON output
*
* @author Robert Stephan
*
*/
public class MCRRestAPIExceptionMapper implements ExceptionMapper<MCRRestAPIException> {
public Response toResponse(MCRRestAPIException ex) {
return Response.status(ex.getStatus()).entity(MCRRestAPIError.convertErrorListToJSONString(ex.getErrors()))
.type(MCRJerseyUtil.APPLICATION_JSON_UTF8).build();
}
}
| 1,347 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/errors/MCRRestAPIException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.errors;
import java.util.ArrayList;
import java.util.List;
import jakarta.ws.rs.core.Response.Status;
/**
* exception that can be thrown during rest api requests
*
* @author Robert Stephan
*
*/
public class MCRRestAPIException extends Exception {
private static final long serialVersionUID = 1L;
private List<MCRRestAPIError> errors = new ArrayList<>();
//default is 501 - internal server error, override if necessary
private Status status = Status.INTERNAL_SERVER_ERROR;
public MCRRestAPIException(Status status, MCRRestAPIError error) {
this.status = status;
errors.add(error);
}
public MCRRestAPIException(Status status, List<MCRRestAPIError> errors) {
this.status = status;
this.errors.addAll(errors);
}
public List<MCRRestAPIError> getErrors() {
return errors;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
| 1,765 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestAPIError.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/errors/MCRRestAPIError.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.errors;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* stores error informations during REST requests
*
* @author Robert Stephan
*
*/
public class MCRRestAPIError {
public static final String CODE_WRONG_PARAMETER = "WRONG_PARAMETER";
public static final String CODE_WRONG_QUERY_PARAMETER = "WRONG_QUERY_PARAMETER";
public static final String CODE_WRONG_ID = "WRONG_ID";
public static final String CODE_NOT_FOUND = "NOT_FOUND";
public static final String CODE_INTERNAL_ERROR = "INTERNAL_ERROR";
public static final String CODE_ACCESS_DENIED = "ACCESS_DENIED";
public static final String CODE_INVALID_AUTHENCATION = "INVALID_AUTHENTICATION";
public static final String CODE_INVALID_DATA = "INVALID_DATA";
String code = "";
String title = "";
String detail = null;
public MCRRestAPIError(String code, String title, String detail) {
this.code = code;
this.title = title;
this.detail = detail;
}
public JsonObject toJsonObject() {
JsonObject error = new JsonObject();
error.addProperty("code", code);
error.addProperty("title", title);
if (detail != null) {
error.addProperty("detail", detail);
}
return error;
}
public String toJSONString() {
JsonArray errors = new JsonArray();
errors.add(toJsonObject());
JsonObject errorMsg = new JsonObject();
errorMsg.add("errors", errors);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(errorMsg);
}
public static String convertErrorListToJSONString(List<MCRRestAPIError> errors) {
JsonArray jaErrors = new JsonArray();
for (MCRRestAPIError e : errors) {
jaErrors.add(e.toJsonObject());
}
JsonObject errorMsg = new JsonObject();
errorMsg.add("errors", jaErrors);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(errorMsg);
}
}
| 2,900 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRForbiddenExceptionMapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/errors/MCRForbiddenExceptionMapper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.errors;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.restapi.v1.utils.MCRRestAPIUtil;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
/**
* Maps response status {@link jakarta.ws.rs.core.Response.Status#FORBIDDEN} to
* {@link jakarta.ws.rs.core.Response.Status#UNAUTHORIZED} if current user is guest.
*/
public class MCRForbiddenExceptionMapper implements ExceptionMapper<ForbiddenException> {
@Context
Application app;
public Response toResponse(ForbiddenException ex) {
String userID = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
if (userID.equals(MCRSystemUserInformation.getGuestInstance().getUserID())) {
LogManager.getLogger().warn("Guest detected");
return Response.fromResponse(ex.getResponse())
.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE, MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app))
.build();
}
return ex.getResponse();
}
}
| 2,082 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNotAuthorizedExceptionMapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v1/errors/MCRNotAuthorizedExceptionMapper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v1.errors;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
/**
* Maps response status {@link Response.Status#FORBIDDEN} to
* {@link Response.Status#UNAUTHORIZED} if current user is guest.
*/
public class MCRNotAuthorizedExceptionMapper implements ExceptionMapper<NotAuthorizedException> {
public Response toResponse(NotAuthorizedException ex) {
if (ex.getMessage() == null || ex.getResponse().getEntity() != null) {
return ex.getResponse();
}
return Response.fromResponse(ex.getResponse())
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + ";charset=utf-8")
.entity(ex.getMessage())
.build();
}
}
| 1,594 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRErrorResponse.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRErrorResponse.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v2;
import java.beans.Transient;
import java.time.Instant;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.mycore.restapi.converter.MCRInstantXMLAdapter;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.ClientErrorException;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.InternalServerErrorException;
import jakarta.ws.rs.NotAcceptableException;
import jakarta.ws.rs.NotAllowedException;
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.NotSupportedException;
import jakarta.ws.rs.ServerErrorException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name = "error")
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
public class MCRErrorResponse {
UUID uuid;
Instant timestamp;
String errorCode;
Throwable cause;
String message;
String detail;
int status;
public static MCRErrorResponse fromStatus(int status) {
final MCRErrorResponse response = new MCRErrorResponse();
response.setStatus(status);
return response;
}
private MCRErrorResponse() {
uuid = UUID.randomUUID();
timestamp = Instant.now();
}
public WebApplicationException toException() {
WebApplicationException e;
Response.Status s = Response.Status.fromStatusCode(status);
final Response response = Response.status(s)
.header("X-Error-Code", getErrorCode())
.header("X-Error-Message", getMessage())
.header("X-Error-Time", new Date(getTimestamp().toEpochMilli())) //no HeaderDelegate for Instant
.header("X-Error-Detail", getDetail())
.header("X-Error-UUID", getUuid())
.entity(this)
.build();
//s maybe null
e = switch (Response.Status.Family.familyOf(status)) {
case CLIENT_ERROR ->
//Response.Status.OK is to trigger "default" case
switch (s != null ? s : Response.Status.OK) {
case BAD_REQUEST -> new BadRequestException(getMessage(), response, getCause());
case FORBIDDEN -> new ForbiddenException(getMessage(), response, getCause());
case NOT_ACCEPTABLE -> new NotAcceptableException(getMessage(), response, getCause());
case METHOD_NOT_ALLOWED -> new NotAllowedException(getMessage(), response, getCause());
case UNAUTHORIZED -> new NotAuthorizedException(getMessage(), response, getCause());
case NOT_FOUND -> new NotFoundException(getMessage(), response, getCause());
case UNSUPPORTED_MEDIA_TYPE -> new NotSupportedException(getMessage(), response, getCause());
default -> new ClientErrorException(getMessage(), response, getCause());
};
case SERVER_ERROR ->
//Response.Status.OK is to trigger "default" case
switch (s != null ? s : Response.Status.OK) {
case INTERNAL_SERVER_ERROR -> new InternalServerErrorException(getMessage(), response, getCause());
default -> new ServerErrorException(getMessage(), response, getCause());
};
default -> new WebApplicationException(getMessage(), getCause(), response);
};
LogManager.getLogger().error(this::getLogMessage, e);
return e;
}
String getLogMessage() {
return getUuid() + " - " + getErrorCode() + ": " + getMessage();
}
@XmlAttribute
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
@XmlAttribute
public String getErrorCode() {
return Optional.ofNullable(errorCode).filter(s -> !s.isBlank()).orElse("UNKNOWN");
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
@Transient
@XmlTransient
public Throwable getCause() {
return cause;
}
public void setCause(Throwable cause) {
this.cause = cause;
}
@XmlElement
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@XmlElement
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@XmlAttribute
@XmlJavaTypeAdapter(MCRInstantXMLAdapter.class)
public Instant getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp.toInstant();
}
@XmlTransient
@Transient
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public MCRErrorResponse withCause(Throwable cause) {
setCause(cause);
return this;
}
public MCRErrorResponse withMessage(String message) {
setMessage(message);
return this;
}
public MCRErrorResponse withDetail(String detail) {
setDetail(detail);
return this;
}
public MCRErrorResponse withErrorCode(String errorCode) {
setErrorCode(errorCode);
return this;
}
@Override
public String toString() {
return "MCRErrorResponse{" +
"uuid=" + uuid +
", status=" + status +
", timestamp=" + timestamp +
", errorCode='" + errorCode + '\'' +
", message='" + message + '\'' +
", detail='" + detail + '\'' +
", cause=" + cause +
'}';
}
}
| 7,039 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREvents.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCREvents.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v2;
import java.net.URI;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventManager;
import org.mycore.frontend.MCRFrontendUtil;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.PostConstruct;
import jakarta.inject.Singleton;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Application;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.UriInfo;
import jakarta.ws.rs.sse.Sse;
import jakarta.ws.rs.sse.SseBroadcaster;
import jakarta.ws.rs.sse.SseEventSink;
@Path("/events")
@OpenAPIDefinition(
tags = @Tag(name = MCRRestUtils.TAG_MYCORE_ABOUT, description = "repository events"))
@Singleton
public class MCREvents {
@Context
Sse sse;
@Context
ServletContext context;
@Context
Application application;
@Context
UriInfo uriInfo;
private volatile SseBroadcaster objectBroadcaster,
derivateBroadcaster, pathBroadcaster;
@PostConstruct
public void init() {
LogManager.getLogger().error("Base URI: {}", uriInfo::getBaseUri);
URI baseUri = uriInfo.getBaseUri(); //accquired from first request
URI webAppBase = URI.create(MCRFrontendUtil.getBaseURL()); //use official URL
Function<URI, URI> uriResolver = webAppBase.resolve(baseUri.getPath())::resolve;
objectBroadcaster = sse.newBroadcaster();
MCREventManager.instance().addEventHandler(MCREvent.ObjectType.OBJECT,
new MCREventHandler.MCRObjectHandler(objectBroadcaster, sse, uriResolver));
derivateBroadcaster = sse.newBroadcaster();
MCREventManager.instance().addEventHandler(MCREvent.ObjectType.DERIVATE,
new MCREventHandler.MCRDerivateHandler(derivateBroadcaster, sse, uriResolver));
pathBroadcaster = sse.newBroadcaster();
MCREventManager.instance().addEventHandler(MCREvent.ObjectType.PATH,
new MCREventHandler.MCRPathHandler(pathBroadcaster, sse, uriResolver, context));
}
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void registerAllEvents(@Context SseEventSink sseEventSink) {
registerObjectEvents(sseEventSink);
registerDerivateEvents(sseEventSink);
registerPathEvents(sseEventSink);
}
@GET
@Path("/objects")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void registerObjectEvents(@Context SseEventSink sseEventSink) {
objectBroadcaster.register(sseEventSink);
}
@GET
@Path("/derivates")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void registerDerivateEvents(@Context SseEventSink sseEventSink) {
derivateBroadcaster.register(sseEventSink);
}
@GET
@Path("/files")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void registerPathEvents(@Context SseEventSink sseEventSink) {
pathBroadcaster.register(sseEventSink);
}
}
| 3,889 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRExceptionMapper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRExceptionMapper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v2;
import java.util.List;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Variant;
import jakarta.ws.rs.ext.ExceptionMapper;
public class MCRExceptionMapper implements ExceptionMapper<Exception> {
private final static List<Variant> SUPPORTED_VARIANTS = Variant
.mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE).build();
private final static Logger LOGGER = LogManager.getLogger();
@Context
Request request;
@Override
public Response toResponse(Exception exception) {
return Optional.ofNullable(request.selectVariant(SUPPORTED_VARIANTS))
.map(v -> fromException(exception))
.orElseGet(() -> (exception instanceof WebApplicationException wae) ? wae.getResponse() : null);
}
public static Response fromWebApplicationException(WebApplicationException wae) {
if (wae.getResponse().hasEntity()) {
//usually WAEs with entity do not arrive here
LOGGER.warn("WebApplicationException already has an entity attached, forwarding response");
return wae.getResponse();
}
final Response response = getResponse(wae, wae.getResponse().getStatus());
response.getHeaders().putAll(wae.getResponse().getHeaders());
return response;
}
public static Response fromException(Exception e) {
if (e instanceof WebApplicationException wae) {
return fromWebApplicationException(wae);
}
return getResponse(e, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
private static Response getResponse(Exception e, int statusCode) {
MCRErrorResponse response = MCRErrorResponse.fromStatus(statusCode)
.withCause(e)
.withMessage(e.getMessage())
.withDetail(Optional.of(e)
.map(ex -> (ex instanceof WebApplicationException) ? ex.getCause() : ex)
.map(Object::getClass)
.map(Class::getName)
.orElse(null));
LogManager.getLogger().error(response::getLogMessage, e);
return Response.status(response.getStatus())
.entity(response)
.build();
}
}
| 3,232 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestClassifications.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestClassifications.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v2;
import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_CLASSID;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jdom2.Document;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.classifications2.MCRLabel;
import org.mycore.datamodel.classifications2.model.MCRClass;
import org.mycore.datamodel.classifications2.model.MCRClassCategory;
import org.mycore.datamodel.classifications2.model.MCRClassURL;
import org.mycore.datamodel.classifications2.utils.MCRSkosTransformer;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import org.mycore.restapi.converter.MCRDetailLevel;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.GenericEntity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.xml.bind.annotation.XmlElementWrapper;
@Path("/classifications")
@OpenAPIDefinition(
tags = @Tag(name = MCRRestUtils.TAG_MYCORE_CLASSIFICATION, description = "Operations on classifications"))
public class MCRRestClassifications {
private static final String PARAM_CATEGID = "categid";
@Context
ContainerRequestContext request;
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" })
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
@Operation(
summary = "Lists all classifications in this repository",
responses = @ApiResponse(
description = "List of root categories without child categories",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = MCRClass.class)))),
tags = MCRRestUtils.TAG_MYCORE_CLASSIFICATION)
@XmlElementWrapper(name = "classifications")
public Response listClassifications() {
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
Date lastModified = new Date(categoryDAO.getLastModified());
Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request.getRequest(), lastModified);
if (cachedResponse.isPresent()) {
return cachedResponse.get();
}
GenericEntity<List<MCRClass>> entity = new GenericEntity<>(
categoryDAO.getRootCategories()
.stream()
.map(MCRRestClassifications::convertToClass)
.collect(Collectors.toList())) {
};
return Response.ok(entity)
.lastModified(lastModified)
.build();
}
private static MCRClass convertToClass(MCRCategory cat) {
MCRClass mcrClass = new MCRClass();
mcrClass.setID(cat.getId().getRootID());
mcrClass.getLabel().addAll(cat.getLabels().stream().map(MCRLabel::clone).collect(Collectors.toList()));
Optional.ofNullable(cat.getURI())
.map(MCRClassURL::getInstance)
.ifPresent(mcrClass::setUrl);
return mcrClass;
}
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8", "application/rdf+xml" })
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
@Path("/{" + PARAM_CLASSID + "}")
@Operation(
summary = "Returns Classification with the given " + PARAM_CLASSID + ".",
responses = @ApiResponse(
description = "Classification with all child categories",
content = @Content(schema = @Schema(implementation = MCRClass.class))),
tags = MCRRestUtils.TAG_MYCORE_CLASSIFICATION)
public Response getClassification(@PathParam(PARAM_CLASSID) String classId) {
return getClassification(classId, dao -> dao.getCategory(MCRCategoryID.rootID(classId), -1));
}
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8", "application/rdf+xml" })
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
@Path("/{" + PARAM_CLASSID + "}/{" + PARAM_CATEGID + "}")
@Operation(summary = "Returns Classification with the given " + PARAM_CLASSID + " and " + PARAM_CATEGID + ".",
responses = @ApiResponse(content = {
@Content(schema = @Schema(implementation = MCRClass.class)),
@Content(schema = @Schema(implementation = MCRClassCategory.class))
},
description = "If media type parameter " + MCRDetailLevel.MEDIA_TYPE_PARAMETER
+ " is 'summary' an MCRClassCategory is returned. "
+ "In other cases MCRClass with different detail level."),
tags = MCRRestUtils.TAG_MYCORE_CLASSIFICATION)
public Response getClassification(@PathParam(PARAM_CLASSID) String classId,
@PathParam(PARAM_CATEGID) String categId) {
MCRDetailLevel detailLevel = request.getAcceptableMediaTypes()
.stream()
.flatMap(m -> m.getParameters().entrySet().stream()
.filter(e -> MCRDetailLevel.MEDIA_TYPE_PARAMETER.equals(e.getKey())))
.map(Map.Entry::getValue)
.findFirst()
.map(MCRDetailLevel::valueOf).orElse(MCRDetailLevel.normal);
MCRCategoryID categoryID = new MCRCategoryID(classId, categId);
return switch (detailLevel) {
case detailed -> getClassification(classId, dao -> dao.getRootCategory(categoryID, -1));
case summary -> getClassification(classId, dao -> dao.getCategory(categoryID, 0));
//normal is also default case
default -> getClassification(classId, dao -> dao.getRootCategory(categoryID, 0));
};
}
private Response getClassification(String classId, Function<MCRCategoryDAO, MCRCategory> categorySupplier) {
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
Date lastModified = getLastModifiedDate(classId, categoryDAO);
Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request.getRequest(), lastModified);
if (cachedResponse.isPresent()) {
return cachedResponse.get();
}
MCRCategory classification = categorySupplier.apply(categoryDAO);
if (classification == null) {
throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRCLASS_NOT_FOUND)
.withMessage("Could not find classification or category in " + classId + ".")
.toException();
}
if (request.getAcceptableMediaTypes().contains(MediaType.valueOf("application/rdf+xml"))) {
Document docSKOS = MCRSkosTransformer.getSkosInRDFXML(classification, MCRCategoryID.fromString(classId));
MCRJDOMContent content = new MCRJDOMContent(docSKOS);
try {
return Response.ok(content.asString()).type("application/rdf+xml; charset=UTF-8").build();
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRCLASS_NOT_FOUND)
.withMessage("Could not find classification or category in " + classId + ".")
.toException();
}
}
return Response.ok()
.entity(classification.isClassification() ? MCRClass.getClassification(classification)
: MCRClassCategory.getInstance(classification))
.lastModified(lastModified)
.build();
}
private static Date getLastModifiedDate(@PathParam(PARAM_CLASSID) String classId, MCRCategoryDAO categoryDAO) {
long categoryLastModified = categoryDAO.getLastModified(classId);
return new Date(categoryLastModified > 0 ? categoryLastModified : categoryDAO.getLastModified());
}
@PUT
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8" })
@Path("/{" + PARAM_CLASSID + "}")
@Produces(MediaType.APPLICATION_XML)
@Operation(
summary = "Creates Classification with the given " + PARAM_CLASSID + ".",
responses = {
@ApiResponse(responseCode = "400",
content = { @Content(mediaType = MediaType.TEXT_PLAIN) },
description = "'MCRCategoryID mismatch'"),
@ApiResponse(responseCode = "201", description = "Classification successfully created"),
@ApiResponse(responseCode = "204", description = "Classification successfully updated"),
},
tags = MCRRestUtils.TAG_MYCORE_CLASSIFICATION)
@MCRRequireTransaction
public Response createClassification(@PathParam(PARAM_CLASSID) String classId, MCRClass mcrClass) {
if (!classId.equals(mcrClass.getID())) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRCLASS_ID_MISMATCH)
.withMessage("Classification " + classId + " cannot be overwritten by " + mcrClass.getID() + ".")
.toException();
}
MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance();
Response.Status status;
if (!categoryDAO.exist(MCRCategoryID.rootID(classId))) {
categoryDAO.addCategory(null, mcrClass.toCategory());
status = Response.Status.CREATED;
} else {
Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request.getRequest(),
getLastModifiedDate(classId, categoryDAO));
if (cachedResponse.isPresent()) {
return cachedResponse.get();
}
categoryDAO.replaceCategory(mcrClass.toCategory());
status = Response.Status.NO_CONTENT;
}
Date lastModifiedDate = getLastModifiedDate(classId, categoryDAO);
return Response.status(status).lastModified(lastModifiedDate).build();
}
}
| 11,940 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRestDerivateContents.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-restapi/src/main/java/org/mycore/restapi/v2/MCRRestDerivateContents.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.restapi.v2;
import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_DERID;
import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_DER_PATH;
import static org.mycore.restapi.v2.MCRRestAuthorizationFilter.PARAM_MCRID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.SecureDirectoryStream;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.CountingOutputStream;
import org.apache.commons.io.output.DeferredFileOutputStream;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRPathContent;
import org.mycore.common.content.util.MCRRestContentHelper;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRFileAttributes;
import org.mycore.datamodel.niofs.MCRMD5AttributeView;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Ordering;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.servlet.ServletContext;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HEAD;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import jakarta.ws.rs.core.Variant;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
@Path("/objects/{" + PARAM_MCRID + "}/derivates/{" + PARAM_DERID + "}/contents{" + PARAM_DER_PATH + ":(/[^/]+)*}")
public class MCRRestDerivateContents {
private static final String HTTP_HEADER_IS_DIRECTORY = "X-MCR-IsDirectory";
private static final int BUFFER_SIZE = 8192;
@Context
ContainerRequestContext request;
@Context
ServletContext context;
@Parameter(example = "mir_mods_00004711")
@PathParam(PARAM_MCRID)
MCRObjectID mcrId;
@Parameter(example = "mir_derivate_00004711")
@PathParam(PARAM_DERID)
MCRObjectID derid;
@PathParam(PARAM_DER_PATH)
@DefaultValue("")
String path;
private static Response createDirectory(MCRPath mcrPath) {
try {
BasicFileAttributes directoryAttrs = Files.readAttributes(mcrPath, BasicFileAttributes.class);
if (!directoryAttrs.isDirectory()) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_CREATE_DIRECTORY_ON_FILE)
.withMessage("Could not create directory " + mcrPath + ". A file allready exist!")
.toException();
}
return Response.noContent().build();
} catch (IOException e) {
//does not exist
LogManager.getLogger().info("Creating directory: {}", mcrPath);
try {
doWithinTransaction(() -> Files.createDirectory(mcrPath));
} catch (IOException e2) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_CREATE_DIRECTORY)
.withMessage("Could not create directory " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
return Response.status(Response.Status.CREATED).build();
}
}
private static void doWithinTransaction(IOOperation op) throws IOException {
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
try {
MCRTransactionHelper.beginTransaction();
op.run();
} finally {
if (MCRTransactionHelper.transactionRequiresRollback()) {
MCRTransactionHelper.rollbackTransaction();
} else {
MCRTransactionHelper.commitTransaction();
}
}
}
private static Response updateFile(InputStream contents, MCRPath mcrPath) {
LogManager.getLogger().info("Updating file: {}", mcrPath);
int memBuf = getUploadMemThreshold();
java.io.File uploadDirectory = getUploadTempStorage();
try (DeferredFileOutputStream dfos = DeferredFileOutputStream.builder()
.setThreshold(memBuf)
.setPrefix(mcrPath.getOwner())
.setSuffix(mcrPath.getFileName().toString())
.setDirectory(uploadDirectory).get();
MaxBytesOutputStream mbos = new MaxBytesOutputStream(dfos)) {
IOUtils.copy(contents, mbos);
mbos.close(); //required if temporary file was used
OutputStream out = Files.newOutputStream(mcrPath);
try {
if (dfos.isInMemory()) {
out.write(dfos.getData());
} else {
java.io.File tempFile = dfos.getFile();
if (tempFile != null) {
try {
Files.copy(tempFile.toPath(), out);
} finally {
LogManager.getLogger().debug("Deleting file {} of size {}.", tempFile.getAbsolutePath(),
tempFile.length());
tempFile.delete();
}
}
}
} finally {
//close writes data to database
doWithinTransaction(out::close);
}
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_UPDATE_FILE)
.withMessage("Could not update file " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
return Response.noContent().build();
}
private static Response createFile(InputStream contents, MCRPath mcrPath) {
LogManager.getLogger().info("Creating file: {}", mcrPath);
try {
OutputStream out = Files.newOutputStream(mcrPath, StandardOpenOption.CREATE_NEW);
try {
IOUtils.copy(contents, out, BUFFER_SIZE);
} finally {
//close writes data to database
doWithinTransaction(out::close);
}
} catch (IOException e) {
try {
doWithinTransaction(() -> Files.deleteIfExists(mcrPath));
} catch (IOException e2) {
LogManager.getLogger().warn("Error while deleting incomplete file.", e2);
}
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_CREATE_DIRECTORY)
.withMessage("Could not create file " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
return Response.status(Response.Status.CREATED).build();
}
private static EntityTag getETag(MCRFileAttributes attrs) {
return new EntityTag(attrs.md5sum());
}
private static long getUploadMaxSize() {
return MCRConfiguration2.getOrThrow("MCR.FileUpload.MaxSize", Long::parseLong);
}
private static java.io.File getUploadTempStorage() {
return MCRConfiguration2.getOrThrow("MCR.FileUpload.TempStoragePath", java.io.File::new);
}
private static int getUploadMemThreshold() {
return MCRConfiguration2.getOrThrow("MCR.FileUpload.MemoryThreshold", Integer::parseInt);
}
/**
* Generate Digest header value.
* @see <a href="https://tools.ietf.org/html/rfc3230">RFC 3230</a>
* @see <a href="https://tools.ietf.org/html/rfc5843">RFC 45843</a>
*/
private static String getDigestHeader(String md5sum) {
final String md5Base64 = Base64.getEncoder().encodeToString(getMD5Digest(md5sum));
return "MD5=" + md5Base64;
}
private static byte[] getMD5Digest(String md5sum) {
final char[] data = md5sum.toCharArray();
final int len = data.length;
// two characters form the hex value.
final byte[] md5Bytes = new byte[len >> 1];
for (int i = 0, j = 0; j < len; i++) {
int f = Character.digit(data[j], 16) << 4;
j++;
f = f | Character.digit(data[j], 16);
j++;
md5Bytes[i] = (byte) (f & 0xFF);
}
return md5Bytes;
}
@HEAD
@MCRCacheControl(sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
@Operation(description = "get information about mime-type(s), last modified, ETag (md5sum) and ranges support",
tags = MCRRestUtils.TAG_MYCORE_FILE,
responses = @ApiResponse(
description = "Use this for single file metadata queries only. Support is implemented for user agents.",
headers = {
@Header(name = "Content-Type", description = "mime type of file"),
@Header(name = "Content-Length", description = "size of file"),
@Header(name = "ETag", description = "MD5 sum of file"),
@Header(name = "Last-Modified", description = "last modified date of file"),
}))
public Response getFileOrDirectoryMetadata() {
MCRRestDerivates.validateDerivateRelation(mcrId, derid);
MCRPath mcrPath = getPath();
MCRFileAttributes fileAttributes;
try {
fileAttributes = Files.readAttributes(mcrPath, MCRFileAttributes.class);
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_NOT_FOUND)
.withMessage("Could not find file or directory " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
if (fileAttributes.isDirectory()) {
return Response.ok()
.variants(Variant
.mediaTypes(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE)
.build())
.build();
}
String mimeType = context.getMimeType(path);
return Response
.status(Response.Status.PARTIAL_CONTENT)
.header("Accept-Ranges", "bytes")
.header(HttpHeaders.CONTENT_TYPE, mimeType)
.lastModified(Date.from(fileAttributes.lastModifiedTime().toInstant()))
.header(HttpHeaders.CONTENT_LENGTH, fileAttributes.size())
.tag(getETag(fileAttributes))
.header("Digest", getDigestHeader(fileAttributes.md5sum()))
.build();
}
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON + ";charset=UTF-8",
MediaType.WILDCARD })
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
@Operation(
summary = "List directory contents or serves file given by {path} in derivate",
tags = MCRRestUtils.TAG_MYCORE_FILE)
public Response getFileOrDirectory(@Context UriInfo uriInfo, @Context HttpHeaders requestHeader) {
MCRRestDerivates.validateDerivateRelation(mcrId, derid);
LogManager.getLogger().info("{}:{}", derid, path);
MCRPath mcrPath = MCRPath.getPath(derid.toString(), path);
MCRFileAttributes fileAttributes;
try {
fileAttributes = Files.readAttributes(mcrPath, MCRFileAttributes.class);
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_NOT_FOUND)
.withMessage("Could not find file or directory " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
Date lastModified = new Date(fileAttributes.lastModifiedTime().toMillis());
if (fileAttributes.isDirectory()) {
return MCRRestUtils
.getCachedResponse(request.getRequest(), lastModified)
.orElseGet(() -> serveDirectory(mcrPath, fileAttributes));
}
return MCRRestUtils
.getCachedResponse(request.getRequest(), lastModified, getETag(fileAttributes))
.orElseGet(() -> {
MCRPathContent content = new MCRPathContent(mcrPath, fileAttributes);
content.setMimeType(context.getMimeType(mcrPath.getFileName().toString()));
try {
final List<Map.Entry<String, String>> responseHeader = List
.of(Map.entry("Digest", getDigestHeader(fileAttributes.md5sum())));
return MCRRestContentHelper.serveContent(content, uriInfo, requestHeader, responseHeader);
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_IO_ERROR)
.withMessage("Could not send file " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
});
}
@PUT
@Consumes(MediaType.WILDCARD)
@Operation(summary = "Creates directory or file. Parent directories will be created if they do not exist.",
parameters = {
@Parameter(in = ParameterIn.HEADER,
name = HTTP_HEADER_IS_DIRECTORY,
description = "set to 'true' if a new directory should be created",
schema = @Schema(type = "boolean")) },
responses = {
@ApiResponse(responseCode = "204", description = "if directory already exists or while was updated"),
@ApiResponse(responseCode = "201", description = "if directory or file was created"),
@ApiResponse(responseCode = "400",
description = "if directory overwrites file or vice versa; content length is too big"),
},
tags = MCRRestUtils.TAG_MYCORE_FILE)
public Response createFileOrDirectory(InputStream contents) {
MCRRestDerivates.validateDerivateRelation(mcrId, derid);
MCRPath mcrPath = MCRPath.getPath(derid.toString(), path);
if (mcrPath.getNameCount() > 1) {
MCRPath parentDirectory = mcrPath.getParent();
try {
Files.createDirectories(parentDirectory);
} catch (FileAlreadyExistsException e) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NOT_DIRECTORY)
.withMessage("A file " + parentDirectory + " exists and can not be used as parent directory.")
.withDetail(e.getMessage())
.withCause(e)
.toException();
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_NOT_FOUND)
.withMessage("Could not find directory " + parentDirectory + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
}
if (isFile()) {
long maxSize = getUploadMaxSize();
String contentLength = request.getHeaderString(HttpHeaders.CONTENT_LENGTH);
if (contentLength != null && Long.parseLong(contentLength) > maxSize) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_SIZE)
.withMessage("Maximum file size (" + maxSize + " bytes) exceeded.")
.withDetail(contentLength)
.toException();
}
return updateOrCreateFile(contents, mcrPath);
} else {
//is directory
return createDirectory(mcrPath);
}
}
@DELETE
@Operation(summary = "Deletes file or directory.",
responses = { @ApiResponse(responseCode = "204", description = "if deletion was successful")
},
tags = MCRRestUtils.TAG_MYCORE_FILE)
@MCRRequireTransaction
public Response deleteFileOrDirectory() {
MCRRestDerivates.validateDerivateRelation(mcrId, derid);
MCRPath mcrPath = getPath();
try {
if (Files.exists(mcrPath) && Files.isDirectory(mcrPath)) {
//delete (sub-)directory and all its containing files and dirs
Files.walkFileTree(mcrPath, MCRRecursiveDeleter.instance());
return Response.noContent().build();
} else if (Files.deleteIfExists(mcrPath)) {
return Response.noContent().build();
}
} catch (DirectoryNotEmptyException e) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_DIRECTORY_NOT_EMPTY)
.withMessage("Directory " + mcrPath + " is not empty.")
.withDetail(e.getMessage())
.withCause(e)
.toException();
} catch (IOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_DELETE)
.withMessage("Could not delete file or directory " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
throw MCRErrorResponse.fromStatus(Response.Status.NOT_FOUND.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_NOT_FOUND)
.withMessage("Could not find file or directory " + mcrPath + ".")
.toException();
}
private Response updateOrCreateFile(InputStream contents, MCRPath mcrPath) {
MCRFileAttributes fileAttributes;
try {
fileAttributes = Files.readAttributes(mcrPath, MCRFileAttributes.class);
if (!fileAttributes.isRegularFile()) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_NOT_FILE)
.withMessage(mcrPath + " is not a file.")
.toException();
}
} catch (IOException e) {
//does not exist
return createFile(contents, mcrPath);
}
//file does already exist
Date lastModified = new Date(fileAttributes.lastModifiedTime().toMillis());
EntityTag eTag = getETag(fileAttributes);
Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request.getRequest(), lastModified,
eTag);
return cachedResponse.orElseGet(() -> updateFile(contents, mcrPath));
}
private boolean isFile() {
//as per https://tools.ietf.org/html/rfc7230#section-3.3
MultivaluedMap<String, String> headers = request.getHeaders();
return ((!"true".equalsIgnoreCase(headers.getFirst(HTTP_HEADER_IS_DIRECTORY))))
&& !request.getUriInfo().getPath().endsWith("/")
&& (headers.containsKey(HttpHeaders.CONTENT_LENGTH) || headers.containsKey("Transfer-Encoding"));
}
private Response serveDirectory(MCRPath mcrPath, MCRFileAttributes dirAttrs) {
Directory dir = new Directory(mcrPath, dirAttrs);
try (DirectoryStream ds = Files.newDirectoryStream(mcrPath)) {
//A SecureDirectoryStream may get attributes faster than reading attributes for every path instance
Function<MCRPath, MCRFileAttributes> attrResolver = p -> {
try {
return (ds instanceof SecureDirectoryStream)
? ((SecureDirectoryStream<MCRPath>) ds).getFileAttributeView(MCRPath.toMCRPath(p.getFileName()),
MCRMD5AttributeView.class).readAllAttributes() //usually faster
: Files.readAttributes(p, MCRFileAttributes.class);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
List<DirectoryEntry> entries = StreamSupport
.stream(((DirectoryStream<MCRPath>) ds).spliterator(), false)
.collect(Collectors.toMap(p -> p, attrResolver))
.entrySet()
.stream()
.map(e -> e.getValue().isDirectory() ? new Directory(e.getKey(), e.getValue())
: new File(e.getKey(), e.getValue(), context.getMimeType(e.getKey().getFileName().toString())))
.sorted() //directories first, than sort for filename
.collect(Collectors.toList());
dir.setEntries(entries);
} catch (IOException | UncheckedIOException e) {
throw MCRErrorResponse.fromStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_IO_ERROR)
.withMessage("Could not send directory " + mcrPath + ".")
.withDetail(e.getMessage())
.withCause(e)
.toException();
}
return Response.ok(dir).lastModified(new Date(dirAttrs.lastModifiedTime().toMillis())).build();
}
private MCRPath getPath() {
return MCRPath.getPath(derid.toString(), path);
}
@FunctionalInterface
private interface IOOperation {
void run() throws IOException;
}
@XmlRootElement(name = "directory")
@XmlAccessorType(XmlAccessType.PROPERTY)
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
@JsonInclude(content = JsonInclude.Include.NON_EMPTY)
private static class Directory extends DirectoryEntry {
private List<Directory> dirs;
private List<File> files;
Directory() {
super();
}
Directory(MCRPath p, MCRFileAttributes attr) {
super(p, attr);
}
void setEntries(List<? extends DirectoryEntry> entries) {
LogManager.getLogger().info(entries);
dirs = new ArrayList<>();
files = new ArrayList<>();
entries.stream()
.collect(Collectors.groupingBy(Object::getClass))
.forEach((c, e) -> {
if (File.class.isAssignableFrom(c)) {
files.addAll((List<File>) e);
} else if (Directory.class.isAssignableFrom(c)) {
dirs.addAll((List<Directory>) e);
}
});
}
@XmlElement(name = "directory")
@JsonProperty("directories")
@JsonInclude(content = JsonInclude.Include.NON_EMPTY)
public List<Directory> getDirs() {
return dirs;
}
@XmlElement(name = "file")
@JsonProperty("files")
@JsonInclude(content = JsonInclude.Include.NON_EMPTY)
public List<File> getFiles() {
return files;
}
}
private static class File extends DirectoryEntry {
private String mimeType;
private String md5;
private long size;
File() {
super();
}
File(MCRPath p, MCRFileAttributes attr, String mimeType) {
super(p, attr);
this.md5 = attr.md5sum();
this.size = attr.size();
this.mimeType = mimeType;
}
@XmlAttribute
@JsonProperty(index = 3)
public String getMd5() {
return md5;
}
@XmlAttribute
@JsonProperty(index = 1)
public long getSize() {
return size;
}
@XmlAttribute
@JsonProperty(index = 4)
public String getMimeType() {
return mimeType;
}
}
@JsonInclude(content = JsonInclude.Include.NON_NULL)
private abstract static class DirectoryEntry implements Comparable<DirectoryEntry> {
private String name;
private Date modified;
DirectoryEntry(MCRPath p, MCRFileAttributes attr) {
this.name = Optional.ofNullable(p.getFileName())
.map(java.nio.file.Path::toString)
.orElse(null);
this.modified = Date.from(attr.lastModifiedTime().toInstant());
}
DirectoryEntry() {
}
@XmlAttribute
@JsonProperty(index = 0)
@JsonInclude(content = JsonInclude.Include.NON_EMPTY)
String getName() {
return name;
}
@XmlAttribute
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = MCRRestUtils.JSON_DATE_FORMAT)
@JsonProperty(index = 2)
public Date getModified() {
return modified;
}
@Override
public int compareTo(DirectoryEntry o) {
return Ordering
.<DirectoryEntry>from((de1, de2) -> {
if (de1 instanceof Directory && !(de2 instanceof Directory)) {
return -1;
}
if (de1.getClass().equals(de2.getClass())) {
return 0;
}
return 1;
})
.compound(Comparator.comparing(DirectoryEntry::getName))
.compare(this, o);
}
}
private static class MaxBytesOutputStream extends CountingOutputStream {
private final long maxSize;
MaxBytesOutputStream(OutputStream out) {
super(out);
maxSize = getUploadMaxSize();
}
@Override
protected synchronized void beforeWrite(int n) {
super.beforeWrite(n);
if (getByteCount() > maxSize) {
throw MCRErrorResponse.fromStatus(Response.Status.BAD_REQUEST.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.MCRDERIVATE_FILE_SIZE)
.withMessage("Maximum file size (" + maxSize + " bytes) exceeded.")
.toException();
}
}
}
}
| 29,425 | 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.